From 7b3afd06a0bf62c20e0e91ab884e269cca3bba23 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:22:35 +0000 Subject: [PATCH 1/8] docs: track a framework-wide contract completeness audit Audit real consumers and implementation semantics for behavior every conforming implementation must expose. Treat Hypervel contracts as greenfield interfaces rather than inheriting missing declarations from Laravel. Keep internal helpers and implementation-specific capabilities off general contracts, and update implementations, tests and public-contract documentation together during the audit. --- docs/todo.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/todo.md b/docs/todo.md index b36085c4f..dec93ad04 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -21,6 +21,8 @@ ## Framework-wide +- Audit the entire codebase for behavior missing from its contracts, designing them as complete greenfield framework interfaces rather than copying Laravel's omissions. Add methods every conforming implementation must provide, based on real consumers and implementation semantics; keep internal helpers and implementation- or driver-specific capabilities off general contracts. Update implementations, tests and public-contract documentation together. + - In a separate PR, make factory-created dates immutable by contract, removing the application-wide mutable opt-out from `Date` / `DateFactory`, `now()` and `today()`. Audit custom classes, factories, callbacks and consumers; preserve useful timezone, locale and test-clock customization and immutable subclasses. Keep explicit mutable conversion at third-party boundaries. Update runtime enforcement, return types, tests and docs together, then tighten `hypervel/phpstan` typing and discarded-date diagnostics wherever immutability is guaranteed; retain accurate handling of external mutable dates. Review the Laravel API departures before implementation. - Once a released `nesbot/carbon` version fixes generated fluent return annotations to preserve subclasses, raise the applicable Carbon minimum through Composer and remove the redundant `@method static` overrides from `Hypervel\Support\CarbonImmutable` (`src/support/src/CarbonImmutable.php`). Carbon's `phpdoc.php::compileDoc()` currently emits concrete `CarbonImmutable`/`CarbonInterface` return types for these methods even though runtime preserves the calling class. Retain the existing overrides until a fixed release is verified; do not expand them into a duplicate of Carbon's complete method list. Keep `types/Support/CarbonImmutable.php` as dependency regression coverage, verify further subclasses as well, and remove `SupportCarbonImmutableTest::testMagicModifierMetadataMatchesRuntimeStaticType()` if no local overrides remain. From 9e2c833a21d279665a95ce114faf75db4d5218fb Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:19:38 +0000 Subject: [PATCH 2/8] docs: standardize Double testing and porting conventions Use Double for new test doubles and convert direct Mockery mocks and spies when porting from any upstream. Preserve upstream PHPUnit doubles and Mockery-backed framework helpers, with framework-owned cleanup and explicit Double verification. Explain lenient argument matching, overlapping allowed calls that bypass maximum counts, native fluent self-returns and static-return requirements. Retain concrete model fixtures for distinct instances and remove redundant guidance. Align the porting policy and checklists through links to the shared convention. Convert the Hypervel container and error-handler examples in the Hyperf guide, including the container control-name collision, while preserving the Hyperf source examples. --- AGENTS.md | 57 +++++++++++++++++++-------------------- docs/ai/porting-hyperf.md | 19 ++++++++----- 2 files changed, 39 insertions(+), 37 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 798660e43..73c600040 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -591,9 +591,17 @@ Do **not** create per-package abstract test case classes (e.g., `EngineTestCase` A per-package base class is only justified when there is shared setUp logic — e.g., shared container mock setup, shared helpers, or shared test fixtures that multiple test classes in the package need. -### Mockery +### Test doubles -**Always import as `m`:** Use `use Mockery as m;` and call `m::mock()`, `m::spy()`, etc. Never use the full `Mockery::` prefix. +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. + +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. + +#### Mockery + +Where Mockery is required by a framework integration, import it as `m`. Framework base test cases own Mockery verification in `tearDown()` so unmet expectations are attributed to the test that created them. The global @@ -620,44 +628,34 @@ public bool $timestamps = false; **Mock return types must match:** ```php -// Laravel (loose - stdClass works) -$connection = m::mock(stdClass::class); - -// Hypervel (strict - use correct type) -$connection = m::mock(PDO::class); -$query = m::mock(QueryBuilder::class); +// Use the native type required by the consumer. +$connection = Double::for(PDO::class); +$query = Double::for(QueryBuilder::class); ``` -**Fluent methods need return values:** -```php -// Laravel (null return silently accepted) -$builder->shouldReceive('where')->with(...); +**Fluent return values:** -// Hypervel (must return for chaining) -$builder->shouldReceive('where')->with(...)->andReturnSelf(); -``` +Double's type-based defaults return the double itself for non-nullable `self`, `static`, or declaring-class return types, and `null` for nullable types. These defaults apply to configured calls without an explicit return and unconfigured calls in lenient mode; unconfigured passthru calls run the real method. **Mocking methods with `static` return type:** -Methods like `newInstance()` have `static` return type, meaning they must return the same class (or subclass) as the object they're called on. Mockery creates proxy subclasses, so returning the parent class fails: +Methods like `newInstance()` have `static` return type, meaning they must return the same class (or subclass) as the object they're called on. Doubles are generated subclasses, so returning the parent class fails: ```php -// FAILS - mock is Mockery_1_MyModel, returning MyModel fails static type -$this->related = m::mock(MyModel::class); -$this->related->shouldReceive('newInstance')->andReturn(new MyModel); +// Returning the parent class violates the generated subclass's static return type. +$this->related = Double::for(MyModel::class); +$this->related->expects('newInstance')->returns(new MyModel); -// WORKS - use partial mock and andReturnSelf() -$this->related = m::mock(MyModel::class)->makePartial(); -$this->related->shouldReceive('newInstance')->andReturnSelf(); +// Initialize real model behavior and intentionally return the double itself. +$this->related = Double::for(new MyModel)->passthru(); +$this->related->expects('newInstance'); -// Test attributes on the mock itself (partial mock has real Model behavior) +// Test attributes on the double itself (passthru keeps real Model behavior) $result = $relation->getResults(); $this->assertSame('taylor', $result->username); ``` -This is a testing-only issue — the strict types are correct and an improvement. In production code, you never mock Models and call `newInstance()`. - -**When `andReturnSelf()` isn't enough:** +**When distinct instances are required:** If a test needs to verify distinct instances (e.g., `makeMany()` returns different objects), use a concrete test stub instead of mocks: @@ -685,8 +683,6 @@ $this->assertNotSame($instances[0], $instances[1]); $this->assertFalse(EloquentHasManyRelatedStub::$saveCalled); ``` -Concrete stubs are the correct approach here — they test actual behavior rather than just verifying mocks were called correctly. - ### When tests expose source code type errors If a test fails with a type error, the source code type may be wrong — not the test. Types should be **correct**, not just strict. A narrow type that doesn't cover all valid cases is incorrect. @@ -789,6 +785,7 @@ Run full PHPStan checks with `composer analyse`. During implementation, use targ When porting Laravel packages, whether first-party or third-party, keep them as close to 1:1 with upstream as possible so future changes are easy to merge. The exceptions are: - Modernizing PHP types, including native parameter, return, property, and class-constant types, plus other appropriate PHP 8.4+ features, strict types, and strict comparisons - Applying the class-import convention, including its exceptions +- Converting direct Mockery test doubles to Double under [Test doubles](#test-doubles) - Converting mutable Laravel date construction to Hypervel's immutable date conventions, typing configurable factory output as `CarbonInterface`, and capturing date-modifier return values - Converting container array access (`$app['events']`) and dynamic service-property access (`$app->events`) in ported code to named container methods, and applying the Configuration rules to ported config and its consumers - Adding Laravel-style title docblocks to methods (not classes — see Development Conventions) @@ -963,8 +960,8 @@ Tests for these features should be **removed** (not commented out) without askin 4. Extend the appropriate test base listed under [Base classes](#base-classes) 5. Ensure `parent::setUp()` is called 6. Add type declarations to model properties -7. Fix mock types (PDO, QueryBuilder, Grammar, etc.) -8. Add `->andReturnSelf()` to chained method mocks +7. Convert direct Mockery doubles to Double (see [Test doubles](#test-doubles)) and double the correct native types (PDO, QueryBuilder, Grammar, etc.) +8. Ensure fluent doubles return the intended object, accounting for Double's automatic self-return 9. Use a test-specific namespace only when helper classes have generic, collision-prone names — already-specific helper names do not need extra namespace ceremony. 10. Remove tests only under the rules in Handling failing tests 11. Run tests and fix any remaining type errors diff --git a/docs/ai/porting-hyperf.md b/docs/ai/porting-hyperf.md index c92e8145f..809e13f87 100644 --- a/docs/ai/porting-hyperf.md +++ b/docs/ai/porting-hyperf.md @@ -239,8 +239,12 @@ $result = $container->get(Foo::class); // test setup call // Hypervel use Hypervel\Contracts\Container\Container as ContainerContract; -$container = m::mock(ContainerContract::class); -$container->shouldReceive('make')->with(Foo::class)->andReturn(new Foo()); +use JMac\Testing\Double; + +// The container's instance() method collides with Double's control API. +$containerDouble = Double::for(ContainerContract::class, override: true); +$containerDouble->allows('make')->with(Foo::class)->returns(new Foo); +$container = $containerDouble->instance(); $result = $container->make(Foo::class); // test setup call ``` @@ -258,10 +262,11 @@ $formatter->shouldReceive('format')->with($exception)->twice()->andReturn('unit' // Hypervel use Hypervel\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract; -$container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturnTrue(); -$container->shouldReceive('make')->with(ExceptionHandlerContract::class) - ->andReturn($handler = m::mock(ExceptionHandlerContract::class)); -$handler->shouldReceive('report')->with($exception)->twice(); + +$handler = Double::for(ExceptionHandlerContract::class); +$containerDouble->allows('has')->with(ExceptionHandlerContract::class)->returns(true); +$containerDouble->allows('make')->with(ExceptionHandlerContract::class)->returns($handler); +$handler->expects('report')->with($exception)->times(2); ``` ### NonCoroutine tests @@ -275,7 +280,7 @@ Hyperf uses `#[Group('NonCoroutine')]` on individual test methods to mark tests 3. Change `Hyperf\` imports to `Hypervel\` 4. Remove Hyperf license header; remove `#[CoversNothing]` and `#[CoversClass(…)]` attributes 5. Extend `Hypervel\Tests\TestCase` (not `PHPUnit\Framework\TestCase`) -6. Change container mock to `Hypervel\Contracts\Container\Container`, all `->get()` to `->make()` (expectations AND direct calls) +6. Convert Mockery doubles to Double per the [test double conventions](../../AGENTS.md#test-doubles); use `Hypervel\Contracts\Container\Container` and change all `->get()` to `->make()` (expectations and direct calls) 7. Change error handler mock to `Hypervel\Contracts\Debug\ExceptionHandler` 8. Extract `#[Group('NonCoroutine')]` methods to separate class with `$runTestsInCoroutine = false` 9. Ensure `parent::setUp()` is called From 6f757e372e5ae7f6fa89b6a49665504f29910e12 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:32:59 +0000 Subject: [PATCH 3/8] build: add Double for framework test development Add jasonmccreary/double ^1.1.1 as a development dependency for native test doubles and per-test verification. Retain Mockery for the framework testing APIs that expose its expectations and spies. This prepares the test conversion from Laravel framework PR #61947 at c980cb5827c6512c12ac44493d172a593b41299a. Dependencies are installed independently in the worktree; the root lock file remains untracked. --- composer.json | 1 + 1 file changed, 1 insertion(+) diff --git a/composer.json b/composer.json index 1837f48b9..6e0c0bb42 100644 --- a/composer.json +++ b/composer.json @@ -127,6 +127,7 @@ "fakerphp/faker": "^1.24", "friendsofphp/php-cs-fixer": "^3.57.2", "intervention/image": "^4.2", + "jasonmccreary/double": "^1.1.1", "league/flysystem-ftp": "^3.36", "league/flysystem-google-cloud-storage": "^3.0", "league/flysystem-sftp-v3": "^3.36", From b3b592e1bcc645c3e8cac62b49f46cc3062882a0 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:33:16 +0000 Subject: [PATCH 4/8] fix(mail): remove the ignored SES v1 sender parameter SES v2 ignores Source, and the envelope sender can describe the return path rather than the FromEmailAddress identity. Remove the unsupported parameter while preserving raw sender headers, explicit SES options and recipient handling. Replace transport mocks with the real SDK MockHandler and verify serialized HTTP payloads, message identifiers, tenant options and error behavior. Reconcile the transport test conversion from Laravel framework PR #61947 without mapping a bounce address to the sending identity. Validation: MailSesV2TransportTest, all three static-analysis configurations and repository formatting pass. --- src/mail/src/Transport/SesV2Transport.php | 3 +- tests/Mail/MailSesV2TransportTest.php | 154 +++++++++++----------- 2 files changed, 79 insertions(+), 78 deletions(-) diff --git a/src/mail/src/Transport/SesV2Transport.php b/src/mail/src/Transport/SesV2Transport.php index aaab6e16d..4f01bad4e 100644 --- a/src/mail/src/Transport/SesV2Transport.php +++ b/src/mail/src/Transport/SesV2Transport.php @@ -58,7 +58,8 @@ protected function doSend(SentMessage $message): void array_merge( $options, [ - 'Source' => $message->getEnvelope()->getSender()->toString(), + // SES v2 drops Laravel's v1-only Source field. Keep the raw sender headers; + // the envelope sender may be a Return-Path, not the FromEmailAddress identity. 'Destination' => [ 'ToAddresses' => (new Collection($message->getEnvelope()->getRecipients())) ->map diff --git a/tests/Mail/MailSesV2TransportTest.php b/tests/Mail/MailSesV2TransportTest.php index f6b7d2798..6ba4060a6 100644 --- a/tests/Mail/MailSesV2TransportTest.php +++ b/tests/Mail/MailSesV2TransportTest.php @@ -7,16 +7,15 @@ use Aws\Command; use Aws\Credentials\Credentials; use Aws\Exception\AwsException; +use Aws\MockHandler; use Aws\Result; use Aws\SesV2\SesV2Client; use GuzzleHttp\Promise\Create; use GuzzleHttp\Promise\PromiseInterface; -use Hypervel\Contracts\View\Factory as ViewFactory; use Hypervel\Mail\Mailer; use Hypervel\Mail\MailManager; use Hypervel\Mail\Transport\SesV2Transport; use Hypervel\Testbench\TestCase; -use Mockery as m; use Symfony\Component\Mailer\Envelope; use Symfony\Component\Mailer\Exception\TransportException; use Symfony\Component\Mailer\Header\MetadataHeader; @@ -29,15 +28,6 @@ class MailSesV2TransportTest extends TestCase { // REMOVED: Laravel's SES v1 transport tests. Hypervel supports SES v2 only. - /** - * Set up the test environment. - */ - protected function setUp(): void - { - parent::setUp(); - $this->app->instance('view', m::mock(ViewFactory::class)); - } - public function testGetTransport(): void { $this->app->make('config')->set('services.ses', [ @@ -87,19 +77,19 @@ public function testSend(): void $message->getHeaders()->add(new MetadataHeader('FooTag', 'TagValue')); $message->getHeaders()->addTextHeader('X-SES-LIST-MANAGEMENT-OPTIONS', 'contactListName=TestList;topicName=TestTopic'); - $client = m::mock(SesV2Client::class); - $sesResult = new Result(['MessageId' => 'ses-message-id']); - $client->expects('sendEmail') - ->with(m::on(function (array $arg): bool { - return $arg['Source'] === 'myself@example.com' - && $arg['Destination']['ToAddresses'] === ['me@example.com', 'you@example.com'] - && $arg['ListManagementOptions'] === ['ContactListName' => 'TestList', 'TopicName' => 'TestTopic'] - && $arg['EmailTags'] === [['Name' => 'FooTag', 'Value' => 'TagValue']] - && str_contains($arg['Content']['Raw']['Data'], 'Reply-To: Taylor Otwell '); - })) - ->andReturn($sesResult); + $handler = new MockHandler([new Result(['MessageId' => 'ses-message-id'])]); + + $sentMessage = (new SesV2Transport($this->sesClient($handler)))->send($message); - $sentMessage = (new SesV2Transport($client))->send($message); + $this->assertSame('SendEmail', $handler->getLastCommand()->getName()); + $parameters = json_decode((string) $handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR); + + $this->assertSame(['me@example.com', 'you@example.com'], $parameters['Destination']['ToAddresses']); + $this->assertSame(['ContactListName' => 'TestList', 'TopicName' => 'TestTopic'], $parameters['ListManagementOptions']); + $this->assertSame([['Name' => 'FooTag', 'Value' => 'TagValue']], $parameters['EmailTags']); + $raw = base64_decode($parameters['Content']['Raw']['Data']); + $this->assertStringContainsString('Sender: myself@example.com', $raw); + $this->assertStringContainsString('Reply-To: Taylor Otwell ', $raw); $this->assertSame('mime-message-id@example.com', $sentMessage->getMessageId()); $headers = $sentMessage->getOriginalMessage()->getHeaders(); @@ -109,22 +99,38 @@ public function testSend(): void public function testSendRawMessageWithExplicitEnvelope(): void { - $message = new RawMessage("From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Raw mail\r\n\r\nBody"); - $envelope = new Envelope(new Address('sender@example.com'), [new Address('recipient@example.com')]); + $message = new RawMessage("From: sender@example.com\r\nReturn-Path: \r\nTo: recipient@example.com\r\nSubject: Raw mail\r\n\r\nBody"); + $envelope = new Envelope(new Address('bounce@example.com'), [new Address('recipient@example.com')]); + $handler = new MockHandler([new Result(['MessageId' => 'ses-message-id'])]); - $client = m::mock(SesV2Client::class); - $client->expects('sendEmail')->with([ - 'Source' => 'sender@example.com', - 'Destination' => ['ToAddresses' => ['recipient@example.com']], - 'Content' => ['Raw' => ['Data' => $message->toString()]], - ])->andReturn(new Result(['MessageId' => 'ses-message-id'])); - - $sentMessage = (new SesV2Transport($client))->send($message, $envelope); + $sentMessage = (new SesV2Transport($this->sesClient($handler)))->send($message, $envelope); + $parameters = json_decode((string) $handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR); + $this->assertSame([ + 'Destination' => ['ToAddresses' => ['recipient@example.com']], + 'Content' => ['Raw' => ['Data' => base64_encode($message->toString())]], + ], $parameters); $this->assertInstanceOf(SentMessage::class, $sentMessage); $this->assertSame('ses-message-id', $sentMessage->getMessageId()); } + public function testExplicitSenderOptionsReachSes(): void + { + $message = (new Email)->from('sender@example.com')->to('recipient@example.com')->text('Body'); + $handler = new MockHandler([new Result(['MessageId' => 'ses-message-id'])]); + $transport = new SesV2Transport($this->sesClient($handler), [ + 'FromEmailAddress' => 'identity@example.com', + 'FeedbackForwardingEmailAddress' => 'feedback@example.com', + ]); + + $transport->send($message); + + $parameters = json_decode((string) $handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR); + $this->assertSame('identity@example.com', $parameters['FromEmailAddress']); + $this->assertSame('feedback@example.com', $parameters['FeedbackForwardingEmailAddress']); + $this->assertStringContainsString('From: sender@example.com', base64_decode($parameters['Content']['Raw']['Data'])); + } + public function testSendWithTenantName(): void { $message = new Email; @@ -134,15 +140,12 @@ public function testSendWithTenantName(): void $message->to('me@example.com'); $message->getHeaders()->addTextHeader('X-SES-TENANT-NAME', 'my-tenant'); - $client = m::mock(SesV2Client::class); - $sesResult = new Result(['MessageId' => 'ses-message-id']); - $client->expects('sendEmail') - ->with(m::on(function (array $arg): bool { - return $arg['TenantName'] === 'my-tenant'; - })) - ->andReturn($sesResult); + $handler = new MockHandler([new Result(['MessageId' => 'ses-message-id'])]); - (new SesV2Transport($client))->send($message); + (new SesV2Transport($this->sesClient($handler)))->send($message); + + $parameters = json_decode((string) $handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR); + $this->assertSame('my-tenant', $parameters['TenantName']); } public function testSendWithZeroTenantName(): void @@ -154,18 +157,12 @@ public function testSendWithZeroTenantName(): void $message->to('me@example.com'); $message->getHeaders()->addTextHeader('X-SES-TENANT-NAME', '0'); - $client = m::mock(SesV2Client::class); - $sesResult = m::mock(); - $sesResult->expects('get') - ->with('MessageId') - ->andReturn('ses-message-id'); - $client->expects('sendEmail') - ->with(m::on(function (array $arg): bool { - return $arg['TenantName'] === '0'; - })) - ->andReturn($sesResult); - - (new SesV2Transport($client))->send($message); + $handler = new MockHandler([new Result(['MessageId' => 'ses-message-id'])]); + + (new SesV2Transport($this->sesClient($handler)))->send($message); + + $parameters = json_decode((string) $handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR); + $this->assertSame('0', $parameters['TenantName']); } public function testSendWithoutTenantNameDoesNotSetTheOption(): void @@ -176,15 +173,12 @@ public function testSendWithoutTenantNameDoesNotSetTheOption(): void $message->sender('myself@example.com'); $message->to('me@example.com'); - $client = m::mock(SesV2Client::class); - $sesResult = new Result(['MessageId' => 'ses-message-id']); - $client->expects('sendEmail') - ->with(m::on(function (array $arg): bool { - return ! array_key_exists('TenantName', $arg); - })) - ->andReturn($sesResult); + $handler = new MockHandler([new Result(['MessageId' => 'ses-message-id'])]); + + (new SesV2Transport($this->sesClient($handler)))->send($message); - (new SesV2Transport($client))->send($message); + $parameters = json_decode((string) $handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR); + $this->assertArrayNotHasKey('TenantName', $parameters); } public function testSendWithEmptyTenantNameDoesNotSetTheOption(): void @@ -196,18 +190,12 @@ public function testSendWithEmptyTenantNameDoesNotSetTheOption(): void $message->to('me@example.com'); $message->getHeaders()->addTextHeader('X-SES-TENANT-NAME', ''); - $client = m::mock(SesV2Client::class); - $sesResult = m::mock(); - $sesResult->expects('get') - ->with('MessageId') - ->andReturn('ses-message-id'); - $client->expects('sendEmail') - ->with(m::on(function (array $arg): bool { - return ! array_key_exists('TenantName', $arg); - })) - ->andReturn($sesResult); - - (new SesV2Transport($client))->send($message); + $handler = new MockHandler([new Result(['MessageId' => 'ses-message-id'])]); + + (new SesV2Transport($this->sesClient($handler)))->send($message); + + $parameters = json_decode((string) $handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR); + $this->assertArrayNotHasKey('TenantName', $parameters); } public function testSendError(): void @@ -218,13 +206,25 @@ public function testSendError(): void $message->sender('myself@example.com'); $message->to('me@example.com'); - $client = m::mock(SesV2Client::class); - $client->expects('sendEmail') - ->andThrow(new AwsException('Email address is not verified.', new Command('sendRawEmail'))); + $handler = new MockHandler; + $handler->append(new AwsException('Email address is not verified.', new Command('sendEmail'))); $this->expectException(TransportException::class); - (new SesV2Transport($client))->send($message); + (new SesV2Transport($this->sesClient($handler)))->send($message); + } + + /** + * Create an SES client using the in-memory handler. + */ + protected function sesClient(MockHandler $handler): SesV2Client + { + return new SesV2Client([ + 'region' => 'us-east-1', + 'version' => 'latest', + 'credentials' => ['key' => 'foo', 'secret' => 'bar'], + 'handler' => $handler, + ]); } public function testSesV2LocalConfiguration(): void From 17b8198b22ae3f6c2f5f548dfa1c995927ce3d6c Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:33:25 +0000 Subject: [PATCH 5/8] fix(queue): preserve zero queue names and retry identifiers Only omitted or empty queue options mean no queue filter. Preserve the valid queue name 0, and filter only empty strings from retry job and batch identifiers so nonempty zero identifiers reach repository lookup and not-found diagnostics. Extend the existing regression datasets and convert the affected tests to native Double expectations and real SDK request handling. Preserve exact payloads, failure events and retry range behavior while reconciling Laravel framework PR #61947. Validation: both retry command test classes, all three static-analysis configurations and repository formatting pass. --- src/queue/src/Console/RetryBatchCommand.php | 3 +- src/queue/src/Console/RetryCommand.php | 8 +- tests/Queue/QueueRetryCommandTest.php | 480 ++++++++++---------- tests/Queue/RetryBatchCommandTest.php | 36 +- 4 files changed, 279 insertions(+), 248 deletions(-) diff --git a/src/queue/src/Console/RetryBatchCommand.php b/src/queue/src/Console/RetryBatchCommand.php index 2fef075b2..6c80f6ef2 100644 --- a/src/queue/src/Console/RetryBatchCommand.php +++ b/src/queue/src/Console/RetryBatchCommand.php @@ -85,6 +85,7 @@ protected function getBatchJobIds(): array { $ids = (array) $this->argument('id'); - return array_values(array_filter(array_unique($ids))); + // Nonempty IDs, including "0", must reach the repository for a result or not-found message. + return array_values(array_filter(array_unique($ids), static fn (int|string $id): bool => $id !== '')); } } diff --git a/src/queue/src/Console/RetryCommand.php b/src/queue/src/Console/RetryCommand.php index ef5ec088d..6093888c4 100644 --- a/src/queue/src/Console/RetryCommand.php +++ b/src/queue/src/Console/RetryCommand.php @@ -107,7 +107,10 @@ protected function getJobIds(): array return $failer->ids(); } - if ($queue = $this->option('queue')) { + $queue = $this->option('queue'); + + // A queue named "0" is valid; only an omitted or empty option means no queue. + if ($queue !== null && $queue !== '') { return $this->getJobIdsByQueue($queue); } @@ -115,7 +118,8 @@ protected function getJobIds(): array $ids = array_merge($ids, $this->getJobIdsByRanges($ranges)); } - return array_values(array_filter(array_unique($ids))); + // Nonempty IDs, including "0", must reach the provider for a result or not-found message. + return array_values(array_filter(array_unique($ids), static fn (int|string $id): bool => $id !== '')); } /** diff --git a/tests/Queue/QueueRetryCommandTest.php b/tests/Queue/QueueRetryCommandTest.php index 6775e26ba..34de76a79 100644 --- a/tests/Queue/QueueRetryCommandTest.php +++ b/tests/Queue/QueueRetryCommandTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Queue; +use Aws\MockHandler; use Aws\Result; use Aws\Sqs\SqsClient; use Generator; @@ -21,7 +22,9 @@ use Hypervel\Support\Collection; use Hypervel\Support\LazyCollection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -31,64 +34,67 @@ class QueueRetryCommandTest extends TestCase { + use VerifiesDoubles; + public function testRetriesSingleJobByPushingItsRawPayload(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $job = $this->failedJob(id: '5', connection: 'database', queue: 'default'); - $failer->shouldReceive('find')->once()->with('5')->andReturn($job); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '5'), 'default', []); - $failer->shouldReceive('forget')->once()->with(m::isSame('5')); + $failer->expects('find')->with('5')->returns($job); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '5'), 'default', []); + $failer->expects('forget')->with(Argument::same('5')); $this->runRetryCommand(['id' => ['5']], $failer, ['database' => $queue]); } public function testRetriesSingleJobByPushingItsRawPayloadWithOptions(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(SqsQueue::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(SqsQueue::class); $job = $this->failedJob(id: '5', connection: 'database', queue: 'default'); - $failer->shouldReceive('find')->once()->with('5')->andReturn($job); - $queue->shouldReceive('getQueueableOptions') - ->once() - ->with(m::type(QueueRetryCommandTestJob::class), 'default', $job->payload) - ->andReturn(['MySpecialOption' => 'option-1']); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '5'), 'default', ['MySpecialOption' => 'option-1']); - $failer->shouldReceive('forget')->once()->with('5'); + $failer->expects('find')->with('5')->returns($job); + $queue->expects('getQueueableOptions') + ->with(Argument::type(QueueRetryCommandTestJob::class), 'default', $job->payload) + ->returns(['MySpecialOption' => 'option-1']); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '5'), 'default', ['MySpecialOption' => 'option-1']); + $failer->expects('forget')->with('5'); $this->runRetryCommand(['id' => ['5']], $failer, ['database' => $queue]); } - public function testDisplaysErrorWhenJobIsNotFound(): void + #[TestWith(['123'])] + #[TestWith(['0'])] + public function testDisplaysErrorWhenJobIsNotFound(string $id): void { - $failer = m::mock(FailedJobProviderInterface::class); - $failer->shouldReceive('find')->once()->with('123')->andReturn(null); + $failer = Double::for(FailedJobProviderInterface::class); + $failer->expects('find')->with($id)->returns(null); - $output = $this->runRetryCommand(['id' => ['123']], $failer, []); + $output = $this->runRetryCommand(['id' => [$id]], $failer, []); - $this->assertStringContainsString('Unable to find failed job with ID [123].', $output); + $this->assertStringContainsString("Unable to find failed job with ID [{$id}].", $output); } #[TestWith([['1', '2']])] #[TestWith([[1, 2]])] public function testRetriesAllFailedJobsUsingTheProvidersIds(array $ids): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); - $failer->shouldReceive('ids')->once()->withNoArgs()->andReturn($ids); + $failer->expects('ids')->with()->returns($ids); - $failer->shouldReceive('find')->once()->with(m::isSame($ids[0]))->andReturn($this->failedJob(id: '1', connection: 'database', queue: 'default')); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '1'), 'default', []); - $failer->shouldReceive('forget')->once()->with(m::isSame($ids[0])); + $failer->expects('find')->with(Argument::same($ids[0]))->returns($this->failedJob(id: '1', connection: 'database', queue: 'default')); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '1'), 'default', []); + $failer->expects('forget')->with(Argument::same($ids[0])); - $failer->shouldReceive('find')->once()->with(m::isSame($ids[1]))->andReturn($this->failedJob(id: '2', connection: 'database', queue: 'emails')); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '2'), 'emails', []); - $failer->shouldReceive('forget')->once()->with(m::isSame($ids[1])); + $failer->expects('find')->with(Argument::same($ids[1]))->returns($this->failedJob(id: '2', connection: 'database', queue: 'emails')); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '2'), 'emails', []); + $failer->expects('forget')->with(Argument::same($ids[1])); $output = $this->runRetryCommand(['id' => ['all']], $failer, ['database' => $queue]); @@ -96,23 +102,25 @@ public function testRetriesAllFailedJobsUsingTheProvidersIds(array $ids): void $this->assertStringContainsString('DONE', $output); } - public function testRetriesJobsOnTheSpecifiedQueue(): void + #[TestWith(['emails'])] + #[TestWith(['0'])] + public function testRetriesJobsOnTheSpecifiedQueue(string $queueName): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); - $failer->shouldReceive('ids')->once()->with('emails')->andReturn(['2']); - $failer->shouldReceive('find')->once()->with('2')->andReturn($this->failedJob(id: '2', connection: 'database', queue: 'emails')); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '2'), 'emails', []); - $failer->shouldReceive('forget')->once()->with('2'); + $failer->expects('ids')->with($queueName)->returns(['2']); + $failer->expects('find')->with('2')->returns($this->failedJob(id: '2', connection: 'database', queue: $queueName)); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '2'), $queueName, []); + $failer->expects('forget')->with('2'); - $this->runRetryCommand(['--queue' => 'emails'], $failer, ['database' => $queue]); + $this->runRetryCommand(['--queue' => $queueName], $failer, ['database' => $queue]); } public function testDisplaysErrorWhenTheSpecifiedQueueHasNoFailedJobs(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $failer->shouldReceive('ids')->once()->with('emails')->andReturn([]); + $failer = Double::for(FailedJobProviderInterface::class); + $failer->expects('ids')->with('emails')->returns([]); $output = $this->runRetryCommand(['--queue' => 'emails'], $failer, []); @@ -122,20 +130,20 @@ public function testDisplaysErrorWhenTheSpecifiedQueueHasNoFailedJobs(): void public function testRetriesJobsWithinTheGivenIdRange(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); - $failer->shouldReceive('find')->once()->with(1)->andReturn($this->failedJob(id: '1', connection: 'database', queue: 'default')); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '1'), 'default', []); - $failer->shouldReceive('forget')->once()->with(1); + $failer->expects('find')->with('1')->returns($this->failedJob(id: '1', connection: 'database', queue: 'default')); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '1'), 'default', []); + $failer->expects('forget')->with('1'); - $failer->shouldReceive('find')->once()->with(2)->andReturn($this->failedJob(id: '2', connection: 'database', queue: 'default')); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '2'), 'default', []); - $failer->shouldReceive('forget')->once()->with(2); + $failer->expects('find')->with('2')->returns($this->failedJob(id: '2', connection: 'database', queue: 'default')); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '2'), 'default', []); + $failer->expects('forget')->with('2'); - $failer->shouldReceive('find')->once()->with(3)->andReturn($this->failedJob(id: '3', connection: 'database', queue: 'default')); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '3'), 'default', []); - $failer->shouldReceive('forget')->once()->with(3); + $failer->expects('find')->with('3')->returns($this->failedJob(id: '3', connection: 'database', queue: 'default')); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '3'), 'default', []); + $failer->expects('forget')->with('3'); $this->runRetryCommand(['--range' => ['1-3']], $failer, ['database' => $queue]); } @@ -151,16 +159,16 @@ public function testDisplaysInfoWhenThereAreNoJobsToRetry(): void public function testItResetsAttemptsCountWhenRetryingAJob(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $job = $this->failedJob(id: '1', connection: 'database', queue: 'default', payload: ['attempts' => 5]); - $failer->shouldReceive('find')->once()->with('1')->andReturn($job); - $queue->shouldReceive('pushRaw')->once()->with(m::on(function (string $payload): bool { + $failer->expects('find')->with('1')->returns($job); + $queue->expects('pushRaw')->with(Argument::satisfies(function (string $payload): bool { return json_decode($payload, true)['attempts'] === 0; }), 'default', []); - $failer->shouldReceive('forget')->once()->with('1'); + $failer->expects('forget')->with('1'); $this->runRetryCommand(['id' => ['1']], $failer, ['database' => $queue]); } @@ -169,8 +177,8 @@ public function testItResetsAttemptsCountWhenRetryingAJob(): void #[TestWith([true], 'custom object handler')] public function testRefreshesTheRetryUntilTimestampWhenTheJobDefinesRetryUntil(bool $customHandler): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $job = $this->failedJob( id: '1', @@ -188,74 +196,73 @@ public function testRefreshesTheRetryUntilTimestampWhenTheJobDefinesRetryUntil(b $job->payload = json_encode($payload); } - $failer->shouldReceive('find')->once()->with('1')->andReturn($job); - $queue->shouldReceive('pushRaw')->once()->with(m::on(function (string $payload): bool { + $failer->expects('find')->with('1')->returns($job); + $queue->expects('pushRaw')->with(Argument::satisfies(function (string $payload): bool { return json_decode($payload, true)['retryUntil'] === 1234567890; }), 'default', []); - $failer->shouldReceive('forget')->once()->with('1'); + $failer->expects('forget')->with('1'); $this->runRetryCommand(['id' => ['1']], $failer, ['database' => $queue]); } public function testPassesQueueableOptionsToTheQueueWhenRetryingASingleJob(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(SqsQueue::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(SqsQueue::class); $job = $this->failedJob(id: '1', connection: 'sqs', queue: 'default'); - $failer->shouldReceive('find')->once()->with('1')->andReturn($job); - $queue->shouldReceive('getQueueableOptions') - ->once() - ->with(m::type(QueueRetryCommandTestJob::class), 'default', $job->payload) - ->andReturn(['MySpecialOption' => 'option-1']); - $queue->shouldReceive('pushRaw')->once()->with(m::type('string'), 'default', ['MySpecialOption' => 'option-1']); - $failer->shouldReceive('forget')->once()->with('1'); + $failer->expects('find')->with('1')->returns($job); + $queue->expects('getQueueableOptions') + ->with(Argument::type(QueueRetryCommandTestJob::class), 'default', $job->payload) + ->returns(['MySpecialOption' => 'option-1']); + $queue->expects('pushRaw')->with(Argument::type('string'), 'default', ['MySpecialOption' => 'option-1']); + $failer->expects('forget')->with('1'); $this->runRetryCommand(['id' => ['1']], $failer, ['sqs' => $queue]); } public function testDispatchesRetryRequestedEventWhenRetryingASingleJob(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); - $events = m::mock(Dispatcher::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); + $events = Double::for(Dispatcher::class); $job = $this->failedJob(id: '1', connection: 'database', queue: 'default'); - $failer->shouldReceive('find')->once()->with('1')->andReturn($job); - $events->shouldReceive('dispatch')->once()->with(m::type(JobRetryRequested::class)); - $queue->shouldReceive('pushRaw')->once(); - $failer->shouldReceive('forget')->once()->with('1'); + $failer->expects('find')->with('1')->returns($job); + $events->expects('dispatch')->with(Argument::type(JobRetryRequested::class)); + $queue->expects('pushRaw'); + $failer->expects('forget')->with('1'); $this->runRetryCommand(['id' => ['1']], $failer, ['database' => $queue], $events); } public function testRetriesCollectionOfJobs(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $jobs = new Collection([ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), 'job-2' => $this->failedJob(id: 'job-2', connection: 'database', queue: 'default'), ]); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); + $failer->expects('find')->with('batch')->returns($jobs); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-1'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-1'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-1'), 'default', []); + $failer->expects('forget')->with('job-1'); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-2'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-2'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-2'), 'default', []); + $failer->expects('forget')->with('job-2'); $this->runRetryCommand(['id' => ['batch']], $failer, ['database' => $queue]); } public function testRetriesALazyCollectionOfJobsAndDoesNotResolveThemAllEagerly(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $unresolvedCounts = []; @@ -274,24 +281,24 @@ public function testRetriesALazyCollectionOfJobsAndDoesNotResolveThemAllEagerly( } }); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); + $failer->expects('find')->with('batch')->returns($jobs); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-1'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-1')->andReturnUsing(function () use (&$unresolvedCounts, &$pendingJobs): bool { + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-1'), 'default', []); + $failer->expects('forget')->with('job-1')->resolves(function () use (&$unresolvedCounts, &$pendingJobs): bool { $unresolvedCounts[] = count($pendingJobs); return true; }); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-2'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-2')->andReturnUsing(function () use (&$unresolvedCounts, &$pendingJobs): bool { + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-2'), 'default', []); + $failer->expects('forget')->with('job-2')->resolves(function () use (&$unresolvedCounts, &$pendingJobs): bool { $unresolvedCounts[] = count($pendingJobs); return true; }); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-3'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-3')->andReturnUsing(function () use (&$unresolvedCounts, &$pendingJobs): bool { + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-3'), 'default', []); + $failer->expects('forget')->with('job-3')->resolves(function () use (&$unresolvedCounts, &$pendingJobs): bool { $unresolvedCounts[] = count($pendingJobs); return true; @@ -308,26 +315,26 @@ public function testRetriesALazyCollectionOfJobsAndDoesNotResolveThemAllEagerly( public function testItResetsAttemptsCountWhenRetryingACollectionOfJobs(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $jobs = new Collection([ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default', payload: ['attempts' => 5]), ]); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); - $queue->shouldReceive('pushRaw')->once()->with(m::on(function (string $payload): bool { + $failer->expects('find')->with('batch')->returns($jobs); + $queue->expects('pushRaw')->with(Argument::satisfies(function (string $payload): bool { return json_decode($payload, true)['attempts'] === 0; }), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-1'); + $failer->expects('forget')->with('job-1'); $this->runRetryCommand(['id' => ['batch']], $failer, ['database' => $queue]); } public function testRefreshesTheRetryUntilTimestampWhenRetryingACollectionOfJobs(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $jobs = new Collection([ 'job-1' => $this->failedJob( @@ -339,19 +346,19 @@ public function testRefreshesTheRetryUntilTimestampWhenRetryingACollectionOfJobs ), ]); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); - $queue->shouldReceive('pushRaw')->once()->with(m::on(function (string $payload): bool { + $failer->expects('find')->with('batch')->returns($jobs); + $queue->expects('pushRaw')->with(Argument::satisfies(function (string $payload): bool { return json_decode($payload, true)['retryUntil'] === 1234567890; }), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-1'); + $failer->expects('forget')->with('job-1'); $this->runRetryCommand(['id' => ['batch']], $failer, ['database' => $queue]); } public function testDisplaysErrorWhenTheGivenIdResolvesToAnEmptyCollection(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $failer->shouldReceive('find')->once()->with('batch')->andReturn(new Collection); + $failer = Double::for(FailedJobProviderInterface::class); + $failer->expects('find')->with('batch')->returns(new Collection); $output = $this->runRetryCommand(['id' => ['batch']], $failer, []); @@ -362,7 +369,7 @@ public function testDisplaysErrorWhenTheGivenIdResolvesToAnEmptyCollection(): vo public function testDisplaysErrorWhenTheGivenIdResolvesToAnEmptyLazyCollection(): void { - $failer = m::mock(FailedJobProviderInterface::class); + $failer = Double::for(FailedJobProviderInterface::class); $resolved = false; @@ -372,7 +379,7 @@ public function testDisplaysErrorWhenTheGivenIdResolvesToAnEmptyLazyCollection() yield from []; }); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); + $failer->expects('find')->with('batch')->returns($jobs); $output = $this->runRetryCommand(['id' => ['batch']], $failer, []); @@ -383,14 +390,14 @@ public function testDisplaysErrorWhenTheGivenIdResolvesToAnEmptyLazyCollection() public function testContinuesRetryingRemainingJobsAfterAJobIsNotFound(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); - $failer->shouldReceive('find')->once()->with('1')->andReturn(null); + $failer->expects('find')->with('1')->returns(null); - $failer->shouldReceive('find')->once()->with('2')->andReturn($this->failedJob(id: '2', connection: 'database', queue: 'default')); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '2'), 'default', []); - $failer->shouldReceive('forget')->once()->with('2'); + $failer->expects('find')->with('2')->returns($this->failedJob(id: '2', connection: 'database', queue: 'default')); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '2'), 'default', []); + $failer->expects('forget')->with('2'); $output = $this->runRetryCommand(['id' => ['1', '2']], $failer, ['database' => $queue]); @@ -400,14 +407,14 @@ public function testContinuesRetryingRemainingJobsAfterAJobIsNotFound(): void public function testContinuesRetryingRemainingJobsAfterAnIdResolvesToAnEmptyCollection(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); - $failer->shouldReceive('find')->once()->with('batch')->andReturn(new Collection); + $failer->expects('find')->with('batch')->returns(new Collection); - $failer->shouldReceive('find')->once()->with('2')->andReturn($this->failedJob(id: '2', connection: 'database', queue: 'default')); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '2'), 'default', []); - $failer->shouldReceive('forget')->once()->with('2'); + $failer->expects('find')->with('2')->returns($this->failedJob(id: '2', connection: 'database', queue: 'default')); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '2'), 'default', []); + $failer->expects('forget')->with('2'); $output = $this->runRetryCommand(['id' => ['batch', '2']], $failer, ['database' => $queue]); @@ -417,41 +424,41 @@ public function testContinuesRetryingRemainingJobsAfterAnIdResolvesToAnEmptyColl public function testRetriesAMixtureOfSingleJobsAndCollectionsOfJobs(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); - $failer->shouldReceive('find')->once()->with('batch')->andReturn(new Collection([ + $failer->expects('find')->with('batch')->returns(new Collection([ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), 'job-2' => $this->failedJob(id: 'job-2', connection: 'database', queue: 'default'), ])); - $failer->shouldReceive('find')->once()->with('9')->andReturn($this->failedJob(id: '9', connection: 'database', queue: 'default')); + $failer->expects('find')->with('9')->returns($this->failedJob(id: '9', connection: 'database', queue: 'default')); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-1'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-1'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-1'), 'default', []); + $failer->expects('forget')->with('job-1'); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-2'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-2'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-2'), 'default', []); + $failer->expects('forget')->with('job-2'); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: '9'), 'default', []); - $failer->shouldReceive('forget')->once()->with('9'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: '9'), 'default', []); + $failer->expects('forget')->with('9'); $this->runRetryCommand(['id' => ['batch', '9']], $failer, ['database' => $queue]); } public function testForgetsJobsUsingTheCollectionKeyRatherThanTheJobId(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $key = 'https://cloud.test/failed-jobs/batch-1:job-1'; - $failer->shouldReceive('find')->once()->with('batch')->andReturn(new Collection([ + $failer->expects('find')->with('batch')->returns(new Collection([ $key => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), ])); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-1'), 'default', []); - $failer->shouldReceive('forget')->once()->with($key); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-1'), 'default', []); + $failer->expects('forget')->with($key); $output = $this->runRetryCommand(['id' => ['batch']], $failer, ['database' => $queue]); @@ -460,45 +467,45 @@ public function testForgetsJobsUsingTheCollectionKeyRatherThanTheJobId(): void public function testForgetsJobsUsingTheCollectionKeyWhenTheCollectionIsNotKeyed(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); - $failer->shouldReceive('find')->once()->with('batch')->andReturn(new Collection([ + $failer->expects('find')->with('batch')->returns(new Collection([ $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), $this->failedJob(id: 'job-2', connection: 'database', queue: 'default'), ])); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-1'), 'default', []); - $failer->shouldReceive('forget')->once()->with(0); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-1'), 'default', []); + $failer->expects('forget')->with(0); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-2'), 'default', []); - $failer->shouldReceive('forget')->once()->with(1); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-2'), 'default', []); + $failer->expects('forget')->with(1); $this->runRetryCommand(['id' => ['batch']], $failer, ['database' => $queue]); } public function testDispatchesRetryRequestedEventForEveryJobInACollection(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); - $events = m::mock(Dispatcher::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); + $events = Double::for(Dispatcher::class); $jobs = new Collection([ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), 'job-2' => $this->failedJob(id: 'job-2', connection: 'database', queue: 'default'), ]); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); + $failer->expects('find')->with('batch')->returns($jobs); $dispatched = []; - $events->shouldReceive('dispatch')->twice()->with(m::type(JobRetryRequested::class))->andReturnUsing(function (JobRetryRequested $event) use (&$dispatched): void { + $events->expects('dispatch')->times(2)->with(Argument::type(JobRetryRequested::class))->resolves(function (JobRetryRequested $event) use (&$dispatched): void { $dispatched[] = $event->job->id; }); - $queue->shouldReceive('pushRaw')->twice(); - $failer->shouldReceive('forget')->once()->with('job-1'); - $failer->shouldReceive('forget')->once()->with('job-2'); + $queue->expects('pushRaw')->times(2); + $failer->expects('forget')->with('job-1'); + $failer->expects('forget')->with('job-2'); $this->runRetryCommand(['id' => ['batch']], $failer, ['database' => $queue], $events); @@ -507,8 +514,8 @@ public function testDispatchesRetryRequestedEventForEveryJobInACollection(): voi public function testStopsRetryingWhenAJobInACollectionFailsToBePushed(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $pendingJobs = [ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), @@ -526,16 +533,16 @@ public function testStopsRetryingWhenAJobInACollectionFailsToBePushed(): void $jobs = new LazyCollection(fn (): Generator => yield from $iterator); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); + $failer->expects('find')->with('batch')->returns($jobs); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-1'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-1'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-1'), 'default', []); + $failer->expects('forget')->with('job-1'); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-2'), 'default', [])->andThrow(new RuntimeException('Unable to push job.')); - $failer->shouldNotReceive('forget')->with('job-2'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-2'), 'default', [])->throws(new RuntimeException('Unable to push job.')); + $failer->expects('forget')->never()->with('job-2'); - $queue->shouldNotReceive('pushRaw')->with($this->retriedPayload(id: 'job-3'), 'default', []); - $failer->shouldNotReceive('forget')->with('job-3'); + $queue->expects('pushRaw')->never()->with($this->retriedPayload(id: 'job-3'), 'default', []); + $failer->expects('forget')->never()->with('job-3'); try { $this->runRetryCommand(['id' => ['batch']], $failer, ['database' => $queue]); @@ -550,8 +557,8 @@ public function testStopsRetryingWhenAJobInACollectionFailsToBePushed(): void public function testRetriesRemainingJobsWhenAJobsModelNoLongerExists(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $missing = $this->failedJob(id: 'job-1', connection: 'database', queue: 'default', job: new QueueRetryCommandTestJobWithMissingModel); @@ -560,55 +567,58 @@ public function testRetriesRemainingJobsWhenAJobsModelNoLongerExists(): void 'job-2' => $this->failedJob(id: 'job-2', connection: 'database', queue: 'default'), ]); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); + $failer->expects('find')->with('batch')->returns($jobs); - $queue->shouldReceive('pushRaw')->once()->with($missing->payload, 'default', []); - $failer->shouldReceive('forget')->once()->with('job-1'); + $queue->expects('pushRaw')->with($missing->payload, 'default', []); + $failer->expects('forget')->with('job-1'); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-2'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-2'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-2'), 'default', []); + $failer->expects('forget')->with('job-2'); $this->runRetryCommand(['id' => ['batch']], $failer, ['database' => $queue]); } public function testRetriesStringJobsWithoutInterpretingTheirCommandData(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $data = ['command' => 'backup:run', 'commandName' => 'backup:run']; $job = $this->failedJob(id: '1', connection: 'database', queue: 'default'); $job->payload = (new QueueRetryCommandCustomQueue)->payloadFor('RunCommand@handle', $data); - $failer->shouldReceive('find')->once()->with('1')->andReturn($job); - $queue->shouldReceive('pushRaw')->once()->with($job->payload, 'default', []); - $failer->shouldReceive('forget')->once()->with('1'); + $failer->expects('find')->with('1')->returns($job); + $queue->expects('pushRaw')->with($job->payload, 'default', []); + $failer->expects('forget')->with('1'); $this->runRetryCommand(['id' => ['1']], $failer, ['database' => $queue]); } public function testRetriesJobWithoutQueueableOptionsWhenItsModelNoLongerExists(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $sqs = m::mock(SqsClient::class); + $failer = Double::for(FailedJobProviderInterface::class); + $handler = new MockHandler([new Result(['MessageId' => 'message-1'])]); + $sqs = $this->sqsClient($handler); $queue = new SqsQueue($sqs, 'default', 'https://sqs.example.test'); $job = $this->failedJob(id: '1', connection: 'sqs', queue: 'default', job: new QueueRetryCommandTestJobWithMissingModel); - $failer->shouldReceive('find')->once()->with('1')->andReturn($job); - $sqs->shouldReceive('sendMessage')->once()->with([ - 'QueueUrl' => 'https://sqs.example.test/default', - 'MessageBody' => $job->payload, - ])->andReturn(new Result(['MessageId' => 'message-1'])); - $failer->shouldReceive('forget')->once()->with('1'); + $failer->expects('find')->with('1')->returns($job); + $failer->expects('forget')->with('1'); $this->runRetryCommand(['id' => ['1']], $failer, ['sqs' => $queue]); + + $this->assertSame([ + 'QueueUrl' => 'https://sqs.example.test/default', + 'MessageBody' => $job->payload, + ], json_decode((string) $handler->getLastRequest()->getBody(), true)); } #[DataProvider('jobsWithoutRestorableObjects')] public function testRetriesSqsJobsWithDefaultOptionsWhenNoObjectCanBeRestored(string $queueName, array $payload): void { - $failer = m::mock(FailedJobProviderInterface::class); - $sqs = m::mock(SqsClient::class); + $failer = Double::for(FailedJobProviderInterface::class); + $handler = new MockHandler([new Result(['MessageId' => 'message-1'])]); + $sqs = $this->sqsClient($handler); $queue = new SqsQueue($sqs, $queueName, 'https://sqs.example.test'); $job = $this->failedJob( id: '1', @@ -618,26 +628,24 @@ public function testRetriesSqsJobsWithDefaultOptionsWhenNoObjectCanBeRestored(st job: new QueueRetryCommandTestJobWithMissingModel, ); - $failer->shouldReceive('find')->once()->with('1')->andReturn($job); - $sqs->shouldReceive('sendMessage')->once()->with(m::on(function (array $message) use ($queueName, $job): bool { - $expected = [ - 'QueueUrl' => 'https://sqs.example.test/' . $queueName, - 'MessageBody' => $job->payload, - ]; - - if (str_ends_with($queueName, '.fifo')) { - $this->assertIsString($message['MessageDeduplicationId']); - unset($message['MessageDeduplicationId']); - $expected['MessageGroupId'] = $queueName; - } + $failer->expects('find')->with('1')->returns($job); + $failer->expects('forget')->with('1'); - $this->assertSame($expected, $message); + $this->runRetryCommand(['id' => ['1']], $failer, ['sqs' => $queue]); - return true; - }))->andReturn(new Result(['MessageId' => 'message-1'])); - $failer->shouldReceive('forget')->once()->with('1'); + $message = json_decode((string) $handler->getLastRequest()->getBody(), true); + $expected = [ + 'QueueUrl' => 'https://sqs.example.test/' . $queueName, + 'MessageBody' => $job->payload, + ]; - $this->runRetryCommand(['id' => ['1']], $failer, ['sqs' => $queue]); + if (str_ends_with($queueName, '.fifo')) { + $this->assertIsString($message['MessageDeduplicationId']); + unset($message['MessageDeduplicationId']); + $expected['MessageGroupId'] = $queueName; + } + + $this->assertSame($expected, $message); } /** @@ -663,27 +671,27 @@ public static function jobsWithoutRestorableObjects(): iterable public function testDispatchesTheEventBeforePushingAndForgetsTheJobAfterwards(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); - $events = m::mock(Dispatcher::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); + $events = Double::for(Dispatcher::class); $jobs = new Collection([ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), ]); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); + $failer->expects('find')->with('batch')->returns($jobs); $sequence = []; - $events->shouldReceive('dispatch')->once()->with(m::type(JobRetryRequested::class))->andReturnUsing(function () use (&$sequence): void { + $events->expects('dispatch')->with(Argument::type(JobRetryRequested::class))->resolves(function () use (&$sequence): void { $sequence[] = 'dispatch'; }); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-1'), 'default', [])->andReturnUsing(function () use (&$sequence): void { + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-1'), 'default', [])->resolves(function () use (&$sequence): void { $sequence[] = 'push'; }); - $failer->shouldReceive('forget')->once()->with('job-1')->andReturnUsing(function () use (&$sequence): bool { + $failer->expects('forget')->with('job-1')->resolves(function () use (&$sequence): bool { $sequence[] = 'forget'; return true; @@ -696,19 +704,19 @@ public function testDispatchesTheEventBeforePushingAndForgetsTheJobAfterwards(): public function testOutputsAnEntryForEveryJobInACollection(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); $jobs = new Collection([ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), 'job-2' => $this->failedJob(id: 'job-2', connection: 'database', queue: 'default'), ]); - $failer->shouldReceive('find')->once()->with('batch')->andReturn($jobs); + $failer->expects('find')->with('batch')->returns($jobs); - $queue->shouldReceive('pushRaw')->twice(); - $failer->shouldReceive('forget')->once()->with('job-1'); - $failer->shouldReceive('forget')->once()->with('job-2'); + $queue->expects('pushRaw')->times(2); + $failer->expects('forget')->with('job-1'); + $failer->expects('forget')->with('job-2'); $output = $this->runRetryCommand(['id' => ['batch']], $failer, ['database' => $queue]); @@ -720,43 +728,43 @@ public function testOutputsAnEntryForEveryJobInACollection(): void public function testRetriesCollectionsOfJobsWhenRetryingAllFailedJobs(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); - $failer->shouldReceive('ids')->once()->withNoArgs()->andReturn(['batch-1', 'batch-2']); + $failer->expects('ids')->with()->returns(['batch-1', 'batch-2']); - $failer->shouldReceive('find')->once()->with('batch-1')->andReturn(new Collection([ + $failer->expects('find')->with('batch-1')->returns(new Collection([ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), ])); - $failer->shouldReceive('find')->once()->with('batch-2')->andReturn(new Collection([ + $failer->expects('find')->with('batch-2')->returns(new Collection([ 'job-2' => $this->failedJob(id: 'job-2', connection: 'database', queue: 'emails'), ])); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-1'), 'default', []); - $failer->shouldReceive('forget')->once()->with('job-1'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-1'), 'default', []); + $failer->expects('forget')->with('job-1'); - $queue->shouldReceive('pushRaw')->once()->with($this->retriedPayload(id: 'job-2'), 'emails', []); - $failer->shouldReceive('forget')->once()->with('job-2'); + $queue->expects('pushRaw')->with($this->retriedPayload(id: 'job-2'), 'emails', []); + $failer->expects('forget')->with('job-2'); $this->runRetryCommand(['id' => ['all']], $failer, ['database' => $queue]); } public function testRetriesTheSameJobTwiceWhenItAppearsInTwoCollections(): void { - $failer = m::mock(FailedJobProviderInterface::class); - $queue = m::mock(QueueContract::class); + $failer = Double::for(FailedJobProviderInterface::class); + $queue = Double::for(QueueContract::class); - $failer->shouldReceive('find')->once()->with('batch-1')->andReturn(new Collection([ + $failer->expects('find')->with('batch-1')->returns(new Collection([ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), ])); - $failer->shouldReceive('find')->once()->with('batch-2')->andReturn(new Collection([ + $failer->expects('find')->with('batch-2')->returns(new Collection([ 'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'), ])); - $queue->shouldReceive('pushRaw')->twice()->with($this->retriedPayload(id: 'job-1'), 'default', []); - $failer->shouldReceive('forget')->twice()->with('job-1'); + $queue->expects('pushRaw')->times(2)->with($this->retriedPayload(id: 'job-1'), 'default', []); + $failer->expects('forget')->times(2)->with('job-1'); $this->runRetryCommand(['id' => ['batch-1', 'batch-2']], $failer, ['database' => $queue]); } @@ -802,6 +810,19 @@ private function retriedPayload(string $id, object $job = new QueueRetryCommandT ]); } + /** + * Create an SQS client that records requests without contacting AWS. + */ + private function sqsClient(MockHandler $handler): SqsClient + { + return new SqsClient([ + 'version' => 'latest', + 'region' => 'us-east-1', + 'credentials' => ['key' => 'test', 'secret' => 'test'], + 'handler' => $handler, + ]); + } + /** * Run the retry command with the given provider and connections. */ @@ -811,21 +832,20 @@ private function runRetryCommand(array $input, FailedJobProviderInterface $faile $container->instance('queue.failer', $failer); - $manager = m::mock(QueueManager::class); + $manager = Double::for(QueueManager::class); foreach ($connections as $name => $queue) { - $manager->shouldReceive('connection')->with($name)->andReturn($queue); + $manager->allows('connection')->with($name)->returns($queue); } $container->instance('queue', $manager); if (is_null($events)) { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->allows('dispatch'); } - $events->shouldReceive('hasListeners')->andReturnFalse()->byDefault(); - $events->shouldReceive('hasListeners')->with(JobRetryRequested::class)->andReturnTrue(); + $events->allows('hasListeners')->with(JobRetryRequested::class)->returns(true); $container->instance('events', $events); diff --git a/tests/Queue/RetryBatchCommandTest.php b/tests/Queue/RetryBatchCommandTest.php index 38242963b..dd4e4beff 100644 --- a/tests/Queue/RetryBatchCommandTest.php +++ b/tests/Queue/RetryBatchCommandTest.php @@ -12,16 +12,22 @@ use Hypervel\Queue\Console\RetryBatchCommand; use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use PHPUnit\Framework\Attributes\TestWith; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; class RetryBatchCommandTest extends TestCase { - public function testItFailsWhenTheBatchCannotBeFound(): void + use VerifiesDoubles; + + #[TestWith(['missing-batch'])] + #[TestWith(['0'])] + public function testItFailsWhenTheBatchCannotBeFound(string $id): void { - $repo = m::mock(BatchRepository::class); - $repo->shouldReceive('find')->once()->with('missing-batch')->andReturn(null); + $repo = Double::for(BatchRepository::class); + $repo->expects('find')->with($id)->returns(null); $this->app->instance(BatchRepository::class, $repo); @@ -30,17 +36,17 @@ public function testItFailsWhenTheBatchCannotBeFound(): void $output = new BufferedOutput; - $exitCode = $command->run(new ArrayInput(['id' => ['missing-batch']]), $output); + $exitCode = $command->run(new ArrayInput(['id' => [$id]]), $output); $this->assertSame(Command::FAILURE, $exitCode); - $this->assertStringContainsString('Unable to find a batch with ID [missing-batch].', $output->fetch()); + $this->assertStringContainsString("Unable to find a batch with ID [{$id}].", $output->fetch()); } public function testItFailsWhenTheBatchHasNoFailedJobs(): void { $batch = new Batch( - m::mock(QueueFactory::class), - m::mock(BatchRepository::class), + Double::for(QueueFactory::class), + Double::for(BatchRepository::class), 'empty-batch', 'Empty Batch', 0, @@ -51,8 +57,8 @@ public function testItFailsWhenTheBatchHasNoFailedJobs(): void CarbonImmutable::now(), ); - $repo = m::mock(BatchRepository::class); - $repo->shouldReceive('find')->once()->with('empty-batch')->andReturn($batch); + $repo = Double::for(BatchRepository::class); + $repo->expects('find')->with('empty-batch')->returns($batch); $this->app->instance(BatchRepository::class, $repo); @@ -73,14 +79,14 @@ public function testItFailsWhenTheBatchHasNoFailedJobs(): void public function testItCanBeRunInIsolation(): void { - $repo = m::mock(BatchRepository::class); - $repo->shouldReceive('find')->once()->with('batch-id')->andReturn(null); + $repo = Double::for(BatchRepository::class); + $repo->expects('find')->with('batch-id')->returns(null); $this->app->instance(BatchRepository::class, $repo); - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->once()->andReturnTrue(); - $mutex->shouldReceive('forget')->once()->andReturnTrue(); + $mutex = Double::for(CommandMutex::class); + $mutex->expects('create')->returns(true); + $mutex->expects('forget')->returns(true); $this->app->instance(CommandMutex::class, $mutex); From 2850224e895f9c255dc3b753bdf4cf863a12d4c5 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:33:34 +0000 Subject: [PATCH 6/8] fix(contracts): declare effective rendering data on views Response assertions consume gatherData through the View contract to inspect effective rendering data, including shared values. Declare gatherData(): array on that contract instead of relying on an undeclared concrete capability. The standard View already implements it. Adapt the handwritten Markdown view fixture, document the requirement for custom implementations, and retain a source explanation of the deliberate Laravel contract difference. Convert TestResponse collaborators to native Double contracts while preserving streaming, JSON, session and model-identity coverage. Validation: TestResponseTest and MarkdownCoroutineSafetyTest pass, as do all three static-analysis configurations and repository formatting. --- src/contracts/README.md | 2 ++ src/contracts/src/View/View.php | 8 ++++++++ src/docs/porting-from-laravel.md | 2 ++ tests/Mail/MarkdownCoroutineSafetyTest.php | 8 ++++++++ tests/Testing/TestResponseTest.php | 15 ++++++++++++--- 5 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/contracts/README.md b/src/contracts/README.md index f1136741f..3e768426a 100644 --- a/src/contracts/README.md +++ b/src/contracts/README.md @@ -9,4 +9,6 @@ Documentation: https://hypervel.org/docs/contracts The `Container` contract also requires `isScoped()`, `isScopedInstance()`, `resolvedShared()`, `forgetInstance()`, `makeTransient()`, `build()`, `buildWith()`, `resolveContextualParameters()`, and `rebinding()`. Custom implementations must provide these methods; extending `Hypervel\Container\Container` supplies them. Lifetime inspection lets consumers cache only the instances the container shares for the worker, instead of caching scoped or fresh services across requests. +The `View` contract also requires `gatherData(): array`, which exposes the data used to render the view, including shared values, for response assertions. The standard `Hypervel\View\View` already provides it. + Ported from: https://github.com/laravel/framework/tree/13.x/src/Illuminate/Contracts diff --git a/src/contracts/src/View/View.php b/src/contracts/src/View/View.php index 61e4b3174..c09b7c610 100644 --- a/src/contracts/src/View/View.php +++ b/src/contracts/src/View/View.php @@ -25,6 +25,14 @@ public function with(string|array $key, mixed $value = null): static; */ public function getData(): array; + /** + * Get the data used to render the view. + * + * Unlike Laravel, the contract declares this method because response assertions + * inspect rendering data, including shared values, through the view contract. + */ + public function gatherData(): array; + /** * Get the path to the view file. */ diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index dd65b9a87..dc4342826 100644 --- a/src/docs/porting-from-laravel.md +++ b/src/docs/porting-from-laravel.md @@ -180,6 +180,8 @@ Some packages also define package-local contracts, such as `Hypervel\Permission\ `Hypervel\Contracts\Support\MessageBag` extends `Stringable`, so a custom message bag without `__toString()` fails at class declaration rather than later when `ViewErrorBag` renders it. +Custom `Hypervel\Contracts\View\View` implementations must provide `gatherData(): array`, returning the data used to render the view, including any shared values. Extending `Hypervel\View\View` supplies it. + ### Missing Equivalents diff --git a/tests/Mail/MarkdownCoroutineSafetyTest.php b/tests/Mail/MarkdownCoroutineSafetyTest.php index 4cf457de2..25acbd360 100644 --- a/tests/Mail/MarkdownCoroutineSafetyTest.php +++ b/tests/Mail/MarkdownCoroutineSafetyTest.php @@ -436,6 +436,14 @@ public function getData(): array return []; } + /** + * Get the data used to render the view. + */ + public function gatherData(): array + { + return $this->getData(); + } + public function getPath(): string { return __FILE__; diff --git a/tests/Testing/TestResponseTest.php b/tests/Testing/TestResponseTest.php index 6c7bec992..329ac0ebe 100644 --- a/tests/Testing/TestResponseTest.php +++ b/tests/Testing/TestResponseTest.php @@ -29,8 +29,9 @@ use Hypervel\Testing\Fluent\AssertableJson; use Hypervel\Testing\TestResponse; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonSerializable; -use Mockery as m; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\ExpectationFailedException; @@ -44,6 +45,8 @@ class TestResponseTest extends TestCase { + use VerifiesDoubles; + public function testAssertViewIs(): void { $response = $this->makeMockResponse([ @@ -3856,8 +3859,14 @@ public function testUnsupportedLoggedContextFallsThroughToJsonErrors(): void */ private function makeMockResponse(array $content): TestResponse { - $baseResponse = tap(new Response, function ($response) use ($content) { - $response->setContent(m::mock(View::class, $content)); + $view = Double::for(View::class); + + foreach ($content as $method => $value) { + $view->allows($method)->returns($value); + } + + $baseResponse = tap(new Response, function ($response) use ($view) { + $response->setContent($view); }); return TestResponse::fromBaseResponse($baseResponse); From 680e89aa6fcccd8c702a66d84159306292ee147b Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:34:00 +0000 Subject: [PATCH 7/8] test: adopt Double and replace implementation mocks with real behavior Reconcile Laravel framework PR #61947 against c980cb5827c6512c12ac44493d172a593b41299a. Use native Double collaborators with per-test verification, preserving meaningful argument, identity, ordering, required-call and forbidden-call assertions. Replace query and session plumbing mocks with real SQLite rows, HTTP requests and session state. Move Redis behavior into service integration coverage and exercise actual SDK command serialization. Remove obsolete database mock suites only after retaining their distinct coverage in integration tests. Preserve Hypervel coroutine ownership, cancellation, pooling, immutable dates, atomic publication, typed validation and cache behavior. Keep real fixtures for native static return types, explicit container collision handling, established unsupported-driver exclusions and framework-owned state cleanup. Mockery-backed framework testing APIs and their dedicated tests remain supported. Validation: every changed test class was run individually, including isolated Redis integration coverage. All three static-analysis configurations and repository formatting pass. The Redis SCAN_PREFIX regression runs in the existing Cluster CI job without a topology skip. --- tests/Auth/AuthDatabaseUserProviderTest.php | 87 +- tests/Auth/AuthEloquentUserProviderTest.php | 24 +- tests/Auth/AuthGuardTest.php | 631 ++++--- tests/Auth/AuthPasswordBrokerManagerTest.php | 103 +- tests/Auth/AuthPasswordBrokerTest.php | 132 +- tests/Auth/AuthTokenGuardTest.php | 181 +- tests/Auth/AuthenticateMiddlewareTest.php | 15 +- tests/Broadcasting/Ably2BroadcasterTest.php | 19 +- tests/Broadcasting/AblyBroadcasterTest.php | 82 +- tests/Broadcasting/BroadcastEventTest.php | 58 +- tests/Broadcasting/BroadcasterTest.php | 142 +- tests/Broadcasting/MercureBroadcasterTest.php | 137 +- tests/Broadcasting/PusherBroadcasterTest.php | 121 +- tests/Broadcasting/RedisBroadcasterTest.php | 157 +- tests/Bus/BusBatchTest.php | 151 +- tests/Bus/BusBatchableTest.php | 17 +- tests/Bus/BusDispatcherTest.php | 52 +- tests/Bus/BusPendingBatchTest.php | 145 +- tests/Bus/BusPendingDispatchTest.php | 109 +- tests/Cache/CacheDatabaseStoreTest.php | 255 ++- tests/Cache/CacheEventsTest.php | 75 +- tests/Cache/CacheFailoverStoreTest.php | 237 +-- tests/Cache/CacheFileStoreTest.php | 36 +- tests/Cache/CacheManagerTest.php | 106 +- tests/Cache/CacheRedisStoreTest.php | 259 +-- tests/Cache/CacheRepositoryTest.php | 476 +++--- tests/Cache/ClearCommandTest.php | 131 +- tests/Cache/Redis/Operations/PutManyTest.php | 2 +- tests/Cache/Redis/RedisStoreTest.php | 55 +- tests/Console/CacheCommandMutexTest.php | 62 +- tests/Console/CommandMutexTest.php | 47 +- tests/Console/CommandTest.php | 84 +- tests/Console/ConsoleApplicationTest.php | 15 +- tests/Console/Scheduling/EventTest.php | 281 ++-- tests/Console/Scheduling/ScheduleTest.php | 77 +- .../ContextualAttributeBindingTest.php | 157 +- .../DatabaseConcernsHasAttributesTest.php | 17 +- ...eConcernsPreventsCircularRecursionTest.php | 18 +- .../DatabaseConnectionFactoryTest.php | 35 +- tests/Database/DatabaseConnectionTest.php | 458 ++--- tests/Database/DatabaseConnectorTest.php | 79 +- .../DatabaseEloquentAsVectorCastTest.php | 13 +- ...EloquentBelongsToManyCreateOrFirstTest.php | 620 +++---- ...tBelongsToManyWithCastedAttributesTest.php | 121 -- ...BelongsToManyWithDefaultAttributesTest.php | 83 - .../DatabaseEloquentBelongsToTest.php | 47 +- ...tabaseEloquentBuilderCreateOrFirstTest.php | 748 +++------ .../Database/DatabaseEloquentBuilderTest.php | 903 ++++------ ...atabaseEloquentCollectionQueueableTest.php | 25 +- .../DatabaseEloquentCollectionTest.php | 41 +- .../Database/DatabaseEloquentFactoryTest.php | 23 +- ...tabaseEloquentHasManyCreateOrFirstTest.php | 526 +++--- .../Database/DatabaseEloquentHasManyTest.php | 64 +- ...loquentHasManyThroughCreateOrFirstTest.php | 408 ++--- tests/Database/DatabaseEloquentHasOneTest.php | 108 +- .../DatabaseEloquentIntegrationTest.php | 720 +++++++- .../DatabaseEloquentInverseRelationTest.php | 132 +- tests/Database/DatabaseEloquentModelTest.php | 929 ++--------- tests/Database/DatabaseEloquentMorphTest.php | 53 - .../DatabaseEloquentMorphToManyTest.php | 164 -- .../Database/DatabaseEloquentMorphToTest.php | 76 +- tests/Database/DatabaseEloquentPivotTest.php | 59 +- ...entPolymorphicRelationsIntegrationTest.php | 9 +- .../DatabaseEloquentRelationshipsTest.php | 28 +- ...baseEloquentSoftDeletesIntegrationTest.php | 117 +- tests/Database/DatabaseManagerTest.php | 19 +- tests/Database/DatabaseMariaDbBuilderTest.php | 21 +- .../DatabaseMariaDbQueryGrammarTest.php | 19 +- .../DatabaseMariaDbSchemaBuilderTest.php | 27 +- .../DatabaseMariaDbSchemaGrammarTest.php | 122 +- .../Database/DatabaseMigrationCreatorTest.php | 57 +- .../DatabaseMigrationInstallCommandTest.php | 38 +- .../DatabaseMigrationMakeCommandTest.php | 30 +- .../DatabaseMigrationMigrateCommandTest.php | 169 +- .../DatabaseMigrationRefreshCommandTest.php | 117 +- .../DatabaseMigrationRepositoryTest.php | 85 +- .../DatabaseMigrationResetCommandTest.php | 35 +- .../DatabaseMigrationRollbackCommandTest.php | 50 +- .../DatabaseMigrationStatusCommandTest.php | 5 - .../DatabaseMigratorIntegrationTest.php | 13 +- tests/Database/DatabaseMigratorTest.php | 125 +- .../DatabaseMySQLSchemaBuilderTest.php | 27 +- tests/Database/DatabaseMySqlBuilderTest.php | 113 +- .../DatabaseMySqlQueryGrammarTest.php | 25 +- .../DatabaseMySqlSchemaGrammarTest.php | 133 +- tests/Database/DatabasePdoConnectionTest.php | 111 +- .../Database/DatabasePostgresBuilderTest.php | 344 ++-- .../DatabasePostgresQueryGrammarTest.php | 23 +- .../DatabasePostgresSchemaBuilderTest.php | 27 +- .../DatabasePostgresSchemaGrammarTest.php | 54 +- tests/Database/DatabaseProcessorTest.php | 23 +- tests/Database/DatabaseQueryBuilderTest.php | 878 +++++----- tests/Database/DatabaseQueryExceptionTest.php | 31 +- .../DatabaseSQLiteSchemaGrammarTest.php | 82 +- .../Database/DatabaseSchemaBlueprintTest.php | 68 +- tests/Database/DatabaseSchemaBuilderTest.php | 199 +-- tests/Database/DatabaseSeederTest.php | 39 +- .../DatabaseSoftDeletingScopeTest.php | 53 - .../DatabaseSoftDeletingTraitTest.php | 145 -- .../DatabaseSqliteSchemaStateTest.php | 42 +- tests/Database/DatabaseTransactionsTest.php | 59 +- tests/Database/DatabaseWipeCommandTest.php | 5 - tests/Database/MigratorTest.php | 93 +- tests/Database/PruneCommandTest.php | 21 +- tests/Database/SeedCommandTest.php | 95 +- tests/Events/BroadcastedEventsTest.php | 65 +- tests/Events/EventsSubscriberTest.php | 10 +- tests/Events/QueuedEventsTest.php | 201 +-- tests/Filesystem/FilesystemAdapterTest.php | 171 +- tests/Filesystem/FilesystemTest.php | 9 +- .../Bootstrap/HandleExceptionsTest.php | 82 +- .../Exceptions/Renderer/ListenerTest.php | 17 +- .../FoundationAuthenticationTest.php | 31 +- ...oundationCacheBasedMaintenanceModeTest.php | 48 +- .../FoundationExceptionsHandlerTest.php | 177 +- .../Foundation/FoundationFormRequestTest.php | 33 +- .../FoundationInteractsWithDatabaseTest.php | 132 +- .../Concerns/InteractsWithDatabaseTest.php | 20 +- .../Testing/DatabaseTruncationTest.php | 105 +- .../Testing/LazilyRefreshDatabaseTest.php | 8 +- tests/Http/HttpRedirectResponseTest.php | 13 +- tests/Http/HttpResponseTest.php | 9 +- tests/Http/JsonResourceTest.php | 8 +- .../Middleware/PreventRequestForgeryTest.php | 5 +- tests/Image/ImageManagerTest.php | 96 +- .../Cache/Redis/RedisStoreTest.php | 142 +- .../Integration/Database/DatabaseLockTest.php | 96 +- tests/Integration/Events/ListenerTest.php | 11 + .../Console/ConfigCacheCommandTest.php | 22 +- .../Console/EventCacheCommandTest.php | 21 +- .../Console/RouteCacheCommandTest.php | 22 +- .../Foundation/MaintenanceModeTest.php | 56 +- .../Queue/CallQueuedHandlerTest.php | 119 +- .../Integration/Queue/QueueConnectionTest.php | 57 +- .../Queue/Redis/RedisQueueTest.php | 137 +- .../Queue/SkipIfBatchCancelledTest.php | 15 +- tests/Integration/Queue/WorkCommandTest.php | 17 +- .../Session/AuthenticateSessionTest.php | 294 ++++ tests/Mail/MailMailableTest.php | 128 +- tests/Mail/MailMailerTest.php | 44 +- tests/Mail/MailResendTransportTest.php | 48 +- tests/Mail/MailableQueuedTest.php | 17 +- .../NotificationBroadcastChannelTest.php | 14 +- .../NotificationChannelManagerTest.php | 61 +- .../NotificationDatabaseChannelTest.php | 29 +- .../NotificationRoutesNotificationsTest.php | 9 +- ...NotificationSendQueuedNotificationTest.php | 12 +- .../Notifications/NotificationSenderTest.php | 270 +-- .../CursorPaginatorLoadMorphCountTest.php | 7 +- .../CursorPaginatorLoadMorphTest.php | 7 +- .../PaginatorLoadMorphCountTest.php | 7 +- tests/Pagination/PaginatorLoadMorphTest.php | 7 +- tests/Queue/FailoverQueueTest.php | 179 +- .../Fixtures/FakeSqsJobWithMessageGroup.php | 23 +- tests/Queue/InteractsWithQueueTest.php | 14 +- tests/Queue/ListFailedCommandTest.php | 9 +- tests/Queue/PruneBatchesCommandTest.php | 13 +- tests/Queue/QueueBeanstalkdJobTest.php | 124 +- tests/Queue/QueueBeanstalkdQueueTest.php | 75 +- tests/Queue/QueueClearCommandTest.php | 19 +- .../QueueDatabaseQueueIntegrationTest.php | 423 ++++- tests/Queue/QueueDatabaseQueueUnitTest.php | 801 ++------- tests/Queue/QueueForgetFailedCommandTest.php | 27 +- tests/Queue/QueueListFailedCommandTest.php | 9 +- tests/Queue/QueueListenerTest.php | 23 +- tests/Queue/QueuePauseResumeTest.php | 34 +- tests/Queue/QueueRedisJobTest.php | 32 +- tests/Queue/QueueRedisQueueTest.php | 598 +++---- tests/Queue/QueueSqsJobTest.php | 287 ++-- tests/Queue/QueueSqsQueueTest.php | 1476 ++++++++--------- tests/Queue/QueueSyncQueueTest.php | 92 +- tests/Queue/QueueWorkerTest.php | 417 ++--- tests/Redis/ConcurrencyLimiterTest.php | 135 +- .../Redis/Fixtures/FakeRedisClusterClient.php | 32 +- tests/Redis/PhpRedisClusterConnectionTest.php | 381 ++--- tests/Redis/RedisEventsTest.php | 97 +- tests/Routing/RoutingRedirectorTest.php | 51 +- tests/Routing/RoutingResponseFactoryTest.php | 13 +- tests/Session/EncryptedSessionStoreTest.php | 17 +- tests/Session/FileSessionHandlerTest.php | 46 +- .../Middleware/AuthenticateSessionTest.php | 471 +----- tests/Session/SessionManagerTest.php | 27 +- tests/Session/SessionStoreTest.php | 125 +- tests/Support/SupportCollectionTest.php | 21 +- tests/Support/SupportComposerTest.php | 11 +- tests/Support/SupportFacadeTest.php | 32 +- tests/Support/SupportFacadesEventTest.php | 13 +- tests/Support/SupportFacadesQueueTest.php | 22 +- .../SupportLazyCollectionIsLazyTest.php | 72 +- tests/Support/SupportLazyCollectionTest.php | 22 +- tests/Support/SupportServiceProviderTest.php | 134 +- tests/Support/SupportTestingBusFakeTest.php | 60 +- tests/Support/SupportTestingMailFakeTest.php | 46 +- tests/Support/SupportTestingQueueFakeTest.php | 138 +- tests/Support/SupportTimeboxTest.php | 29 +- tests/Testing/Concerns/TestDatabasesTest.php | 18 +- tests/Testing/Concerns/TestViewsTest.php | 3 +- .../Translation/TranslationFileLoaderTest.php | 215 +-- .../Translation/TranslationTranslatorTest.php | 207 +-- ...ValidationDatabasePresenceVerifierTest.php | 114 +- tests/Validation/ValidationValidatorTest.php | 248 +-- tests/View/Blade/AbstractBladeTestCase.php | 10 +- .../Blade/BladeComponentTagCompilerTest.php | 228 +-- tests/View/Blade/BladeComponentsTest.php | 17 +- tests/View/ComponentTest.php | 102 +- tests/View/ViewBladeCompilerTest.php | 132 +- tests/View/ViewCompilerEngineTest.php | 170 +- tests/View/ViewFactoryTest.php | 302 ++-- tests/View/ViewFileViewFinderTest.php | 47 +- tests/View/ViewTest.php | 229 +-- 210 files changed, 12570 insertions(+), 14015 deletions(-) delete mode 100644 tests/Database/DatabaseEloquentBelongsToManyWithCastedAttributesTest.php delete mode 100644 tests/Database/DatabaseEloquentBelongsToManyWithDefaultAttributesTest.php delete mode 100644 tests/Database/DatabaseEloquentMorphToManyTest.php delete mode 100644 tests/Database/DatabaseSoftDeletingTraitTest.php create mode 100644 tests/Integration/Session/AuthenticateSessionTest.php diff --git a/tests/Auth/AuthDatabaseUserProviderTest.php b/tests/Auth/AuthDatabaseUserProviderTest.php index e6c81c150..464e0e1d7 100755 --- a/tests/Auth/AuthDatabaseUserProviderTest.php +++ b/tests/Auth/AuthDatabaseUserProviderTest.php @@ -16,13 +16,16 @@ use Hypervel\Database\SQLiteConnection; use Hypervel\Hashing\BcryptHasher; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use function Hypervel\Coroutine\parallel; class AuthDatabaseUserProviderTest extends TestCase { + use VerifiesDoubles; + public function testRetrieveByIDReturnsUserWhenUserIsFound(): void { $provider = $this->newProvider(); @@ -43,20 +46,20 @@ public function testRetrieveByIDReturnsNullWhenUserIsNotFound(): void public function testResolverBackedProviderResolvesTheConfiguredConnectionForEveryOperation(): void { - $firstConnection = m::mock(Connection::class); - $firstQuery = m::mock(Builder::class); - $firstConnection->shouldReceive('table')->once()->with('foo')->andReturn($firstQuery); - $firstQuery->shouldReceive('find')->once()->with(1)->andReturn(['id' => 1, 'name' => 'First']); + $firstConnection = Double::for(Connection::class); + $firstQuery = Double::for(Builder::class); + $firstConnection->expects('table')->with('foo')->returns($firstQuery); + $firstQuery->expects('find')->with(1)->returns(['id' => 1, 'name' => 'First']); - $secondConnection = m::mock(Connection::class); - $secondQuery = m::mock(Builder::class); - $secondConnection->shouldReceive('table')->once()->with('foo')->andReturn($secondQuery); - $secondQuery->shouldReceive('find')->once()->with(2)->andReturn(['id' => 2, 'name' => 'Second']); + $secondConnection = Double::for(Connection::class); + $secondQuery = Double::for(Builder::class); + $secondConnection->expects('table')->with('foo')->returns($secondQuery); + $secondQuery->expects('find')->with(2)->returns(['id' => 2, 'name' => 'Second']); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->twice()->with('auth')->andReturn($firstConnection, $secondConnection); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->times(2)->with('auth')->returns($firstConnection, $secondConnection); - $provider = new DatabaseUserProvider($resolver, m::mock(Hasher::class), 'foo', 'auth'); + $provider = new DatabaseUserProvider($resolver, Double::for(Hasher::class), 'foo', 'auth'); $this->assertSame('First', $provider->retrieveById(1)?->name); $this->assertSame('Second', $provider->retrieveById(2)?->name); @@ -64,19 +67,19 @@ public function testResolverBackedProviderResolvesTheConfiguredConnectionForEver public function testResolverBackedProviderDoesNotRetainConnectionsAcrossExecutions(): void { - $firstConnection = m::mock(Connection::class); - $firstQuery = m::mock(Builder::class); - $firstConnection->shouldReceive('table')->once()->with('foo')->andReturn($firstQuery); - $firstQuery->shouldReceive('find')->once()->andReturn(['id' => 1, 'name' => 'First']); + $firstConnection = Double::for(Connection::class); + $firstQuery = Double::for(Builder::class); + $firstConnection->expects('table')->with('foo')->returns($firstQuery); + $firstQuery->expects('find')->returns(['id' => 1, 'name' => 'First']); - $secondConnection = m::mock(Connection::class); - $secondQuery = m::mock(Builder::class); - $secondConnection->shouldReceive('table')->once()->with('foo')->andReturn($secondQuery); - $secondQuery->shouldReceive('find')->once()->andReturn(['id' => 2, 'name' => 'Second']); + $secondConnection = Double::for(Connection::class); + $secondQuery = Double::for(Builder::class); + $secondConnection->expects('table')->with('foo')->returns($secondQuery); + $secondQuery->expects('find')->returns(['id' => 2, 'name' => 'Second']); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->twice()->with('auth')->andReturn($firstConnection, $secondConnection); - $provider = new DatabaseUserProvider($resolver, m::mock(Hasher::class), 'foo', 'auth'); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->times(2)->with('auth')->returns($firstConnection, $secondConnection); + $provider = new DatabaseUserProvider($resolver, Double::for(Hasher::class), 'foo', 'auth'); $names = parallel([ fn () => $provider->retrieveById(1)?->name, @@ -89,31 +92,31 @@ public function testResolverBackedProviderDoesNotRetainConnectionsAcrossExecutio public function testResolverBackedProviderUsesTheDefaultConnectionWhenNoNameIsConfigured(): void { - $connection = m::mock(Connection::class); - $query = m::mock(Builder::class); - $connection->shouldReceive('table')->once()->with('foo')->andReturn($query); - $query->shouldReceive('find')->once()->with(1)->andReturn(null); + $connection = Double::for(Connection::class); + $query = Double::for(Builder::class); + $connection->expects('table')->with('foo')->returns($query); + $query->expects('find')->with(1)->returns(null); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->once()->with(null)->andReturn($connection); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->with(null)->returns($connection); - $provider = new DatabaseUserProvider($resolver, m::mock(Hasher::class), 'foo'); + $provider = new DatabaseUserProvider($resolver, Double::for(Hasher::class), 'foo'); $this->assertNull($provider->retrieveById(1)); } public function testResolverContractTakesPrecedenceForObjectsImplementingBothConnectionContracts(): void { - $resolvedConnection = m::mock(Connection::class); - $query = m::mock(Builder::class); - $resolvedConnection->shouldReceive('table')->once()->with('foo')->andReturn($query); - $query->shouldReceive('find')->once()->with(1)->andReturn(null); + $resolvedConnection = Double::for(Connection::class); + $query = Double::for(Builder::class); + $resolvedConnection->expects('table')->with('foo')->returns($query); + $query->expects('find')->with(1)->returns(null); - $connectionResolver = m::mock(ConnectionInterface::class . ', ' . ConnectionResolverInterface::class); - $connectionResolver->shouldReceive('connection')->once()->with('auth')->andReturn($resolvedConnection); - $connectionResolver->shouldNotReceive('table'); + $connectionResolver = Double::for(ConnectionInterface::class, ConnectionResolverInterface::class); + $connectionResolver->expects('connection')->with('auth')->returns($resolvedConnection); + $connectionResolver->expects('table')->never(); - $provider = new DatabaseUserProvider($connectionResolver, m::mock(Hasher::class), 'foo', 'auth'); + $provider = new DatabaseUserProvider($connectionResolver, Double::for(Hasher::class), 'foo', 'auth'); $this->assertNull($provider->retrieveById(1)); } @@ -213,11 +216,11 @@ public function testCredentialValidationFails(): void public function testCredentialValidationFailsGracefullyWithNullPassword(): void { $conn = new PdoConnection(new PDO('sqlite::memory:')); - $hasher = m::mock(Hasher::class); - $hasher->shouldReceive('check')->never(); + $hasher = Double::for(Hasher::class); + $hasher->expects('check')->never(); $provider = new DatabaseUserProvider($conn, $hasher, 'foo'); - $user = m::mock(Authenticatable::class); - $user->expects('getAuthPassword')->andReturn(null); + $user = Double::for(Authenticatable::class); + $user->expects('getAuthPassword')->returns(null); $result = $provider->validateCredentials($user, ['password' => 'plain']); $this->assertFalse($result); diff --git a/tests/Auth/AuthEloquentUserProviderTest.php b/tests/Auth/AuthEloquentUserProviderTest.php index 8fcc04502..b693bad39 100755 --- a/tests/Auth/AuthEloquentUserProviderTest.php +++ b/tests/Auth/AuthEloquentUserProviderTest.php @@ -15,12 +15,14 @@ use Hypervel\Hashing\BcryptHasher; use Hypervel\Tests\Database\Concerns\InteractsWithInMemoryConnection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class AuthEloquentUserProviderTest extends TestCase { use InteractsWithInMemoryConnection; + use VerifiesDoubles; public function testRetrieveByIDReturnsUser(): void { @@ -61,7 +63,7 @@ public function testRetrieveByBadTokenReturnsNull(): void public function testUpdateRememberTokenRestoresTimestampsAfterSaving(): void { $user = new EloquentProviderRememberUserStub; - $provider = new EloquentUserProvider(m::mock(Hasher::class), $user::class); + $provider = new EloquentUserProvider(Double::for(Hasher::class), $user::class); $provider->updateRememberToken($user, 'remember-token'); @@ -74,7 +76,7 @@ public function testUpdateRememberTokenPreservesInitiallyDisabledTimestamps(): v { $user = new EloquentProviderRememberUserStub; $user->timestamps = false; - $provider = new EloquentUserProvider(m::mock(Hasher::class), $user::class); + $provider = new EloquentUserProvider(Double::for(Hasher::class), $user::class); $provider->updateRememberToken($user, 'remember-token'); @@ -87,7 +89,7 @@ public function testUpdateRememberTokenRestoresTimestampsAfterSaveFailure(): voi $exception = new RuntimeException('Save failed.'); $user = new EloquentProviderRememberUserStub; $user->saveException = $exception; - $provider = new EloquentUserProvider(m::mock(Hasher::class), $user::class); + $provider = new EloquentUserProvider(Double::for(Hasher::class), $user::class); try { $provider->updateRememberToken($user, 'remember-token'); @@ -151,11 +153,11 @@ public function testCredentialValidationFailed(): void public function testCredentialValidationFailsGracefullyWithNullPassword(): void { - $hasher = m::mock(Hasher::class); - $hasher->shouldReceive('check')->never(); + $hasher = Double::for(Hasher::class); + $hasher->expects('check')->never(); $provider = new EloquentUserProvider($hasher, 'foo'); - $user = m::mock(Authenticatable::class); - $user->expects('getAuthPassword')->andReturn(null); + $user = Double::for(Authenticatable::class); + $user->expects('getAuthPassword')->returns(null); $result = $provider->validateCredentials($user, ['password' => 'plain']); $this->assertFalse($result); @@ -192,9 +194,9 @@ public function testRehashPasswordIfRequiredWithCustomPasswordColumn(): void public function testDontRehashPasswordIfNotRequired(): void { - $hasher = m::mock(Hasher::class); - $hasher->expects('needsRehash')->with('hash')->andReturn(false); - $hasher->shouldNotReceive('make'); + $hasher = Double::for(Hasher::class); + $hasher->expects('needsRehash')->with('hash')->returns(false); + $hasher->expects('make')->never(); $provider = $this->newProvider($hasher); $user = EloquentProviderUserStub::find(3); diff --git a/tests/Auth/AuthGuardTest.php b/tests/Auth/AuthGuardTest.php index 5dcf23f6b..d98729253 100755 --- a/tests/Auth/AuthGuardTest.php +++ b/tests/Auth/AuthGuardTest.php @@ -14,7 +14,6 @@ use Hypervel\Auth\Events\Logout; use Hypervel\Auth\Events\Validated; use Hypervel\Auth\GenericUser; -use Hypervel\Auth\Recaller; use Hypervel\Auth\SessionGuard; use Hypervel\Container\Container; use Hypervel\Contracts\Auth\Authenticatable; @@ -29,7 +28,9 @@ use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Support\Timebox; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\HttpFoundation\Cookie; @@ -38,14 +39,16 @@ class AuthGuardTest extends TestCase { + use VerifiesDoubles; + public function testBasicReturnsNullOnValidAttempt(): void { [$guard, $provider, $session] = $this->getRealGuard(Request::create('/', 'GET', [], [], [], ['PHP_AUTH_USER' => 'foo@bar.com', 'PHP_AUTH_PW' => 'secret'])); $user = new GenericUser(['id' => 10, 'password' => 'secret']); $credentials = ['email' => 'foo@bar.com', 'password' => 'secret']; - $provider->expects('retrieveByCredentials')->with($credentials)->andReturn($user); - $provider->expects('validateCredentials')->with($user, $credentials)->andReturn(true); + $provider->expects('retrieveByCredentials')->with($credentials)->returns($user); + $provider->expects('validateCredentials')->with($user, $credentials)->returns(true); $provider->expects('rehashPasswordIfRequired')->with($user, $credentials); $this->assertNull($guard->basic('email')); @@ -59,7 +62,7 @@ public function testBasicReturnsNullWhenAlreadyLoggedIn(): void $user = new GenericUser(['id' => 10, 'password' => 'secret']); $guard->setUser($user); - $provider->shouldNotReceive('retrieveByCredentials'); + $provider->expects('retrieveByCredentials')->never(); $this->assertNull($guard->basic('email')); $this->assertSame($user, $guard->user()); @@ -73,9 +76,9 @@ public function testBasicReturnsResponseOnFailure(): void $user = new GenericUser(['id' => 10, 'password' => 'secret']); $credentials = ['email' => 'foo@bar.com', 'password' => 'secret']; - $provider->expects('retrieveByCredentials')->with($credentials)->andReturn($user); - $provider->expects('validateCredentials')->with($user, $credentials)->andReturn(false); - $provider->shouldNotReceive('rehashPasswordIfRequired'); + $provider->expects('retrieveByCredentials')->with($credentials)->returns($user); + $provider->expects('validateCredentials')->with($user, $credentials)->returns(false); + $provider->expects('rehashPasswordIfRequired')->never(); $guard->basic('email'); } @@ -86,8 +89,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)->andReturn($user); - $provider->expects('validateCredentials')->with($user, $credentials)->andReturn(true); + $provider->expects('retrieveByCredentials')->with($credentials)->returns($user); + $provider->expects('validateCredentials')->with($user, $credentials)->returns(true); $provider->expects('rehashPasswordIfRequired')->with($user, $credentials); $this->assertNull($guard->basic('email', ['active' => 1])); @@ -101,8 +104,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)->andReturn($user); - $provider->expects('validateCredentials')->with($user, $credentials)->andReturn(true); + $provider->expects('retrieveByCredentials')->with($credentials)->returns($user); + $provider->expects('validateCredentials')->with($user, $credentials)->returns(true); $provider->expects('rehashPasswordIfRequired')->with($user, $credentials); $this->assertNull($guard->basic('email', ['active' => 1, 'type' => [1, 2, 3]])); @@ -116,11 +119,11 @@ public function testAttemptCallsRetrieveByCredentials(): void $events = new EventFake(new Dispatcher); $guard->setDispatcher($events); $timebox = $guard->getTimebox(); - $timebox->expects('call')->andReturnUsing(function (Closure $callback) use ($timebox): bool { + $timebox->expects('call')->resolves(function (Closure $callback) use ($timebox): bool { return $callback($timebox); }); $guard->getProvider()->expects('retrieveByCredentials')->with(['foo']); - $guard->getProvider()->shouldNotReceive('rehashPasswordIfRequired'); + $guard->getProvider()->expects('rehashPasswordIfRequired')->never(); $guard->attempt(['foo']); $events->assertDispatchedOnce(Attempting::class); @@ -130,19 +133,15 @@ public function testAttemptCallsRetrieveByCredentials(): void public function testAttemptReturnsUserInterface(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $guard = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['login'])->setConstructorArgs(['default', $provider, $session, $app, $timebox])->getMock(); + [$guard, $provider] = $this->getRealGuard(); $events = new EventFake(new Dispatcher); $guard->setDispatcher($events); - $timebox->expects('call')->andReturnUsing(function (Closure $callback, int $microseconds) use ($timebox): bool { - return $callback($timebox->expects('returnEarly')->getMock()); - }); - $user = $this->createStub(Authenticatable::class); - $guard->getProvider()->expects('retrieveByCredentials')->andReturn($user); - $guard->getProvider()->expects('validateCredentials')->with($user, ['foo'])->andReturn(true); - $guard->getProvider()->expects('rehashPasswordIfRequired')->with($user, ['foo']); - $guard->expects($this->once())->method('login')->with($user); + $user = new GenericUser(['id' => 10]); + $provider->expects('retrieveByCredentials')->returns($user); + $provider->expects('validateCredentials')->with($user, ['foo'])->returns(true); + $provider->expects('rehashPasswordIfRequired')->with($user, ['foo']); $this->assertTrue($guard->attempt(['foo'])); + $this->assertSame($user, $guard->getUser()); $events->assertDispatchedOnce(Attempting::class); $events->assertDispatchedOnce(Validated::class); @@ -154,11 +153,11 @@ public function testAttemptReturnsFalseIfUserNotGiven(): void $events = new EventFake(new Dispatcher); $mock->setDispatcher($events); $timebox = $mock->getTimebox(); - $timebox->expects('call')->andReturnUsing(function (Closure $callback, int $microseconds) use ($timebox): bool { + $timebox->expects('call')->resolves(function (Closure $callback, int $microseconds) use ($timebox): bool { return $callback($timebox); }); - $mock->getProvider()->expects('retrieveByCredentials')->andReturn(null); - $mock->getProvider()->shouldNotReceive('rehashPasswordIfRequired'); + $mock->getProvider()->expects('retrieveByCredentials')->returns(null); + $mock->getProvider()->expects('rehashPasswordIfRequired')->never(); $this->assertFalse($mock->attempt(['foo'])); $events->assertDispatchedOnce(Attempting::class); @@ -168,24 +167,13 @@ public function testAttemptReturnsFalseIfUserNotGiven(): void public function testAttemptAndWithCallbacks(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['getName'])->setConstructorArgs(['default', $provider, $session, $app, $timebox])->getMock(); + [$mock, $provider, $session] = $this->getRealGuard(); $events = new EventFake(new Dispatcher); $mock->setDispatcher($events); - $timebox->shouldReceive('call')->andReturnUsing(function (Closure $callback) use ($timebox): bool { - return $callback($timebox->shouldReceive('returnEarly')->getMock()); - }); - $user = m::mock(Authenticatable::class); - $mock->expects($this->once())->method('getName')->willReturn('foo'); - $user->expects('getAuthIdentifier')->andReturn('bar'); - $user->expects('getAuthPassword')->andReturn(null); - $mock->getSession()->expects('put')->with('foo', 'bar'); - $mock->getSession()->expects('remove')->with('password_hash_default'); - $session->expects('regenerate'); - $mock->getProvider()->expects('retrieveByCredentials')->times(3)->with(['foo'])->andReturn($user); - $mock->getProvider()->expects('validateCredentials')->times(2)->andReturnTrue(); - $mock->getProvider()->expects('validateCredentials')->andReturnFalse(); - $mock->getProvider()->expects('rehashPasswordIfRequired')->with($user, ['foo']); + $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']); $this->assertTrue($mock->attemptWhen(['foo'], function (Authenticatable $user, SessionGuard $guard): bool { $this->assertInstanceOf(Authenticatable::class, $user); @@ -208,6 +196,7 @@ public function testAttemptAndWithCallbacks(): void })); $this->assertFalse($executed); + $this->assertSame('bar', $session->get($mock->getName())); $events->assertDispatchedTimes(Attempting::class, 3); $events->assertDispatchedOnce(Login::class); @@ -218,19 +207,15 @@ public function testAttemptAndWithCallbacks(): void public function testAttemptRehashesPasswordWhenRequired(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $guard = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['login'])->setConstructorArgs(['default', $provider, $session, $app, $timebox])->getMock(); + [$guard, $provider] = $this->getRealGuard(); $events = new EventFake(new Dispatcher); $guard->setDispatcher($events); - $timebox->expects('call')->andReturnUsing(function (Closure $callback, int $microseconds) use ($timebox): bool { - return $callback($timebox->expects('returnEarly')->getMock()); - }); - $user = $this->createStub(Authenticatable::class); - $guard->getProvider()->expects('retrieveByCredentials')->andReturn($user); - $guard->getProvider()->expects('validateCredentials')->with($user, ['foo'])->andReturn(true); - $guard->getProvider()->expects('rehashPasswordIfRequired')->with($user, ['foo']); - $guard->expects($this->once())->method('login')->with($user); + $user = new GenericUser(['id' => 10]); + $provider->expects('retrieveByCredentials')->returns($user); + $provider->expects('validateCredentials')->with($user, ['foo'])->returns(true); + $provider->expects('rehashPasswordIfRequired')->with($user, ['foo']); $this->assertTrue($guard->attempt(['foo'])); + $this->assertSame($user, $guard->getUser()); $events->assertDispatchedOnce(Attempting::class); $events->assertDispatchedOnce(Validated::class); @@ -238,21 +223,16 @@ public function testAttemptRehashesPasswordWhenRequired(): void public function testAttemptDoesntRehashPasswordWhenDisabled(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $guard = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['login']) - ->setConstructorArgs(['default', $provider, $session, $app, $timebox, false]) - ->getMock(); + $provider = Double::for(UserProvider::class); + $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); - $timebox->expects('call')->andReturnUsing(function (Closure $callback, int $microseconds) use ($timebox): bool { - return $callback($timebox->expects('returnEarly')->getMock()); - }); - $user = $this->createStub(Authenticatable::class); - $guard->getProvider()->expects('retrieveByCredentials')->andReturn($user); - $guard->getProvider()->expects('validateCredentials')->with($user, ['foo'])->andReturn(true); - $guard->getProvider()->shouldNotReceive('rehashPasswordIfRequired'); - $guard->expects($this->once())->method('login')->with($user); + $user = new GenericUser(['id' => 10]); + $provider->expects('retrieveByCredentials')->returns($user); + $provider->expects('validateCredentials')->with($user, ['foo'])->returns(true); + $provider->expects('rehashPasswordIfRequired')->never(); $this->assertTrue($guard->attempt(['foo'])); + $this->assertSame($user, $guard->getUser()); $events->assertDispatchedOnce(Attempting::class); $events->assertDispatchedOnce(Validated::class); @@ -260,16 +240,11 @@ public function testAttemptDoesntRehashPasswordWhenDisabled(): void public function testLoginStoresIdentifierInSession(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['getName'])->setConstructorArgs(['default', $provider, $session, $app])->getMock(); - $user = m::mock(Authenticatable::class); - $mock->expects($this->once())->method('getName')->willReturn('foo'); - $user->expects('getAuthIdentifier')->andReturn('bar'); - $user->expects('getAuthPassword')->andReturn(null); - $mock->getSession()->expects('put')->with('foo', 'bar'); - $mock->getSession()->expects('remove')->with('password_hash_default'); - $session->expects('regenerate'); - $mock->login($user); + [$guard, , $session] = $this->getRealGuard(); + $sessionId = $session->getId(); + $guard->login(new GenericUser(['id' => 'bar'])); + $this->assertSame('bar', $session->get($guard->getName())); + $this->assertNotSame($sessionId, $session->getId()); } public function testLoginStoresPasswordHashInSession(): void @@ -327,18 +302,10 @@ public function testSessionGuardIsMacroable(): void public function testLoginFiresLoginAndAuthenticatedEvents(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['getName'])->setConstructorArgs(['default', $provider, $session, $app])->getMock(); + [$guard] = $this->getRealGuard(); $events = new EventFake(new Dispatcher); - $mock->setDispatcher($events); - $user = m::mock(Authenticatable::class); - $mock->expects($this->once())->method('getName')->willReturn('foo'); - $user->expects('getAuthIdentifier')->andReturn('bar'); - $user->expects('getAuthPassword')->andReturn(null); - $mock->getSession()->expects('put')->with('foo', 'bar'); - $mock->getSession()->expects('remove')->with('password_hash_default'); - $session->expects('regenerate'); - $mock->login($user); + $guard->setDispatcher($events); + $guard->login(new GenericUser(['id' => 'bar'])); $events->assertDispatchedOnce(Login::class); $events->assertDispatchedOnce(Authenticated::class); @@ -350,11 +317,11 @@ public function testFailedAttemptFiresFailedEvent(): void $events = new EventFake(new Dispatcher); $guard->setDispatcher($events); $timebox = $guard->getTimebox(); - $timebox->expects('call')->andReturnUsing(function (Closure $callback, int $microseconds) use ($timebox): bool { + $timebox->expects('call')->resolves(function (Closure $callback, int $microseconds) use ($timebox): bool { return $callback($timebox); }); - $guard->getProvider()->expects('retrieveByCredentials')->with(['foo'])->andReturn(null); - $guard->getProvider()->shouldNotReceive('rehashPasswordIfRequired'); + $guard->getProvider()->expects('retrieveByCredentials')->with(['foo'])->returns(null); + $guard->getProvider()->expects('rehashPasswordIfRequired')->never(); $guard->attempt(['foo']); $events->assertDispatchedOnce(Attempting::class); @@ -403,7 +370,7 @@ public function testHasUserReturnsTrueWhenUserIsNotNull(): void public function testHasUserReturnsFalseWhenUserIsNull(): void { $guard = $this->getGuard(); - $guard->getSession()->shouldNotReceive('get'); + $guard->getSession()->expects('get')->never(); $this->assertFalse($guard->hasUser()); $this->assertNull($guard->getUser()); @@ -439,8 +406,8 @@ public function testUserMethodReturnsCachedUser(): void public function testNullIsReturnedForUserIfNoUserFound(bool $sessionStarted): void { $mock = $this->getGuard(); - $mock->getSession()->shouldReceive('isStarted')->andReturn($sessionStarted); - $mock->getSession()->expects('get')->andReturn(null); + $mock->getSession()->allows('isStarted')->returns($sessionStarted); + $mock->getSession()->expects('get')->returns(null); $this->assertNull($mock->user()); $this->assertNull($mock->getUser()); $this->assertFalse($mock->hasUser()); @@ -463,7 +430,7 @@ public function testUserIsSetToRetrievedUser(): void [$guard, $provider, $session] = $this->getRealGuard(); $session->put($guard->getName(), 1); $user = new GenericUser([]); - $provider->expects('retrieveById')->with(1)->andReturn($user); + $provider->expects('retrieveById')->with(1)->returns($user); $this->assertSame($user, $guard->user()); $this->assertSame($user, $guard->getUser()); @@ -471,46 +438,35 @@ public function testUserIsSetToRetrievedUser(): void public function testLogoutRemovesSessionTokenAndRememberMeCookie(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['getName', 'getRecallerName', 'recaller'])->setConstructorArgs(['default', $provider, $session, $app])->getMock(); - $cookies = m::mock(CookieJar::class); - $mock->setCookieJar($cookies); - $user = m::mock(Authenticatable::class); - $user->expects('getRememberToken')->andReturn('a'); - $user->expects('setRememberToken'); - $mock->expects($this->once())->method('getName')->willReturn('foo'); - $mock->expects($this->exactly(2))->method('getRecallerName')->willReturn($recallerName = 'bar'); - $mock->expects($this->once())->method('recaller')->willReturn(new Recaller('id|token|hash')); + [$guard, $provider, $session] = $this->getRealGuard(); + $guard->setCookieJar($cookies = new CookieJar); + $guard->getRequest()->cookies->set($guard->getRecallerName(), '10|a|hash'); + $user = new GenericUser(['id' => 10, 'remember_token' => 'a']); $provider->expects('updateRememberToken'); - - $cookie = new Cookie('bar'); - $cookies->expects('forget')->with('bar')->andReturn($cookie); - $cookies->expects('queue')->with($cookie); - $cookies->expects('unqueue')->with($recallerName); - $mock->getSession()->expects('remove')->with('foo'); - $mock->setUser($user); - $mock->logout(); - $this->assertNull($mock->getUser()); + $session->put($guard->getName(), 10); + // A cookie queued earlier in the request is replaced by the one that forgets it... + $cookies->queue($cookies->make($guard->getRecallerName(), 'stale')); + $guard->setUser($user); + $guard->logout(); + $this->assertNull($guard->getUser()); + $this->assertNull($session->get($guard->getName())); + $this->assertNotSame('a', $user->getRememberToken()); + $this->assertLessThan(time(), $cookies->queued($guard->getRecallerName())->getExpiresTime()); + $this->assertSame('', (string) $cookies->queued($guard->getRecallerName())->getValue()); } public function testLogoutDoesNotEnqueueRememberMeCookieForDeletionIfCookieDoesntExist(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['getName', 'getRecallerName', 'recaller'])->setConstructorArgs(['default', $provider, $session, $app])->getMock(); - $cookies = m::mock(CookieJar::class); - $mock->setCookieJar($cookies); - $user = m::mock(Authenticatable::class); - $user->expects('getRememberToken')->andReturn(null); - $mock->expects($this->once())->method('getRecallerName')->willReturn($recallerName = 'bar'); - $mock->expects($this->once())->method('getName')->willReturn('foo'); - $mock->expects($this->once())->method('recaller')->willReturn(null); - - $cookies->expects('unqueue')->with($recallerName); - - $mock->getSession()->expects('remove')->with('foo'); - $mock->setUser($user); - $mock->logout(); - $this->assertNull($mock->getUser()); + [$guard, , $session] = $this->getRealGuard(); + $guard->setCookieJar($cookies = new CookieJar); + $user = new GenericUser(['id' => 10, 'remember_token' => null]); + $session->put($guard->getName(), 10); + $cookies->queue($cookies->make($guard->getRecallerName(), 'stale')); + $guard->setUser($user); + $guard->logout(); + $this->assertNull($guard->getUser()); + $this->assertNull($session->get($guard->getName())); + $this->assertFalse($cookies->hasQueued($guard->getRecallerName())); } public function testLogoutFiresLogoutEvent(): void @@ -531,56 +487,47 @@ public function testLogoutFiresLogoutEvent(): void public function testLogoutDoesNotSetRememberTokenIfNotPreviouslySet(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['clearUserDataFromStorage'])->setConstructorArgs(['default', $provider, $session, $app])->getMock(); - $mock->expects($this->once())->method('clearUserDataFromStorage'); - $user = m::mock(Authenticatable::class); + [$guard, $provider] = $this->getRealGuard(); + $guard->setCookieJar(new CookieJar); + $user = new GenericUser(['id' => 10, 'remember_token' => null]); - $user->expects('getRememberToken')->andReturn(null); - $user->shouldNotReceive('setRememberToken'); - $provider->shouldNotReceive('updateRememberToken'); + $provider->expects('updateRememberToken')->never(); - $mock->setUser($user); - $mock->logout(); + $guard->setUser($user); + $guard->logout(); + + $this->assertNull($user->getRememberToken()); } public function testLogoutCurrentDeviceRemovesRememberMeCookie(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['getName', 'getRecallerName', 'recaller'])->setConstructorArgs(['default', $provider, $session, $app])->getMock(); - $cookies = m::mock(CookieJar::class); - $mock->setCookieJar($cookies); - $user = new GenericUser([]); - $mock->expects($this->once())->method('getName')->willReturn('foo'); - $mock->expects($this->exactly(2))->method('getRecallerName')->willReturn($recallerName = 'bar'); - $mock->expects($this->once())->method('recaller')->willReturn(new Recaller('id|token|hash')); - - $cookie = new Cookie('bar'); - $cookies->expects('forget')->with('bar')->andReturn($cookie); - $cookies->expects('queue')->with($cookie); - $cookies->expects('unqueue')->with($recallerName); - $mock->getSession()->expects('remove')->with('foo'); - $mock->setUser($user); - $mock->logoutCurrentDevice(); - $this->assertNull($mock->getUser()); + [$guard, , $session] = $this->getRealGuard(); + $guard->setCookieJar($cookies = new CookieJar); + $guard->getRequest()->cookies->set($guard->getRecallerName(), '10|a|hash'); + $user = new GenericUser(['id' => 10, 'remember_token' => 'a']); + $session->put($guard->getName(), 10); + $cookies->queue($cookies->make($guard->getRecallerName(), 'stale')); + $guard->setUser($user); + $guard->logoutCurrentDevice(); + $this->assertNull($guard->getUser()); + $this->assertNull($session->get($guard->getName())); + $this->assertSame('a', $user->getRememberToken()); + $this->assertLessThan(time(), $cookies->queued($guard->getRecallerName())->getExpiresTime()); + $this->assertSame('', (string) $cookies->queued($guard->getRecallerName())->getValue()); } public function testLogoutCurrentDeviceDoesNotEnqueueRememberMeCookieForDeletionIfCookieDoesntExist(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class)->onlyMethods(['getName', 'getRecallerName', 'recaller'])->setConstructorArgs(['default', $provider, $session, $app])->getMock(); - $cookies = m::mock(CookieJar::class); - $mock->setCookieJar($cookies); - $user = new GenericUser([]); - $mock->expects($this->once())->method('getName')->willReturn('foo'); - $mock->expects($this->once())->method('getRecallerName')->willReturn($recallerName = 'bar'); - $mock->expects($this->once())->method('recaller')->willReturn(null); - $cookies->expects('unqueue')->with($recallerName); - - $mock->getSession()->expects('remove')->with('foo'); - $mock->setUser($user); - $mock->logoutCurrentDevice(); - $this->assertNull($mock->getUser()); + [$guard, , $session] = $this->getRealGuard(); + $guard->setCookieJar($cookies = new CookieJar); + $user = new GenericUser(['id' => 10]); + $session->put($guard->getName(), 10); + $cookies->queue($cookies->make($guard->getRecallerName(), 'stale')); + $guard->setUser($user); + $guard->logoutCurrentDevice(); + $this->assertNull($guard->getUser()); + $this->assertNull($session->get($guard->getName())); + $this->assertFalse($cookies->hasQueued($guard->getRecallerName())); } public function testLogoutCurrentDeviceFiresLogoutEvent(): void @@ -604,23 +551,19 @@ public function testLogoutCurrentDeviceFiresLogoutEvent(): void public function testLoginMethodQueuesCookieWhenRemembering(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $guard = new SessionGuard('default', $provider, $session, $app); - $guard->setCookieJar($cookie); - $foreverCookie = new Cookie($guard->getRecallerName(), 'foo'); + [$guard, $provider, $session] = $this->getRealGuard(); + $guard->setCookieJar($cookies = new CookieJar); $expectedHash = hash_hmac('sha256', 'bar', 'base-key-for-password-hash-mac'); - $cookie->expects('make')->with($guard->getRecallerName(), 'foo|recaller|' . $expectedHash, 576000)->andReturn($foreverCookie); - $cookie->expects('queue')->with($foreverCookie); - $guard->getSession()->expects('put')->with($guard->getName(), 'foo'); - $guard->getSession()->expects('put')->with('password_hash_default', $expectedHash); - $session->expects('regenerate'); - $user = m::mock(Authenticatable::class); - $user->expects('getAuthIdentifier')->times(2)->andReturn('foo'); - $user->expects('getAuthPassword')->times(2)->andReturn('bar'); - $user->expects('getRememberToken')->times(2)->andReturn('recaller'); - $user->shouldReceive('setRememberToken')->never(); - $provider->shouldReceive('updateRememberToken')->never(); + $user = new GenericUser(['id' => 'foo', 'password' => 'bar', 'remember_token' => 'recaller']); + $provider->expects('updateRememberToken')->never(); $guard->login($user, true); + + $cookie = $cookies->queued($guard->getRecallerName()); + $this->assertSame('foo|recaller|' . $expectedHash, $cookie->getValue()); + $this->assertEqualsWithDelta(time() + 576000 * 60, $cookie->getExpiresTime(), 5); + $this->assertSame('foo', $session->get($guard->getName())); + $this->assertSame($expectedHash, $session->get('password_hash_default')); + $this->assertSame('recaller', $user->getRememberToken()); } public function testLoginMethodQueuesCookieWhenRememberingPasswordlessUser(): void @@ -630,60 +573,51 @@ public function testLoginMethodQueuesCookieWhenRememberingPasswordlessUser(): vo $guard->setCookieJar($cookie); $foreverCookie = new Cookie($guard->getRecallerName(), 'foo'); $expectedHash = hash_hmac('sha256', '', 'base-key-for-password-hash-mac'); - $cookie->shouldReceive('make')->once()->with($guard->getRecallerName(), 'foo|recaller|' . $expectedHash, 576000)->andReturn($foreverCookie); - $cookie->shouldReceive('queue')->once()->with($foreverCookie); - $guard->getSession()->shouldReceive('put')->once()->with($guard->getName(), 'foo'); - $guard->getSession()->shouldReceive('remove')->once()->with('password_hash_default'); - $session->shouldReceive('regenerate')->once(); - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->andReturn('foo'); - $user->shouldReceive('getAuthPassword')->andReturn(null); - $user->shouldReceive('getRememberToken')->andReturn('recaller'); - $user->shouldReceive('setRememberToken')->never(); - $provider->shouldReceive('updateRememberToken')->never(); + $cookie->expects('make')->with($guard->getRecallerName(), 'foo|recaller|' . $expectedHash, 576000)->returns($foreverCookie); + $cookie->expects('queue')->with(Argument::same($foreverCookie)); + $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->allows('getAuthIdentifier')->returns('foo'); + $user->allows('getAuthPassword')->returns(null); + $user->allows('getRememberToken')->returns('recaller'); + $user->expects('setRememberToken')->never(); + $provider->expects('updateRememberToken')->never(); $guard->login($user, true); } public function testLoginMethodQueuesCookieWhenRememberingAndAllowsOverride(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $guard = new SessionGuard('default', $provider, $session, $app); + [$guard, $provider] = $this->getRealGuard(); $guard->setRememberDuration(5000); - $guard->setCookieJar($cookie); - $foreverCookie = new Cookie($guard->getRecallerName(), 'foo'); + $guard->setCookieJar($cookies = new CookieJar); $expectedHash = hash_hmac('sha256', 'bar', 'base-key-for-password-hash-mac'); - $cookie->expects('make')->with($guard->getRecallerName(), 'foo|recaller|' . $expectedHash, 5000)->andReturn($foreverCookie); - $cookie->expects('queue')->with($foreverCookie); - $guard->getSession()->expects('put')->with($guard->getName(), 'foo'); - $guard->getSession()->expects('put')->with('password_hash_default', $expectedHash); - $session->expects('regenerate'); - $user = m::mock(Authenticatable::class); - $user->expects('getAuthIdentifier')->times(2)->andReturn('foo'); - $user->expects('getAuthPassword')->times(2)->andReturn('bar'); - $user->expects('getRememberToken')->times(2)->andReturn('recaller'); - $user->shouldReceive('setRememberToken')->never(); - $provider->shouldReceive('updateRememberToken')->never(); + $user = new GenericUser(['id' => 'foo', 'password' => 'bar', 'remember_token' => 'recaller']); + $provider->expects('updateRememberToken')->never(); $guard->login($user, true); + + $cookie = $cookies->queued($guard->getRecallerName()); + $this->assertSame('foo|recaller|' . $expectedHash, $cookie->getValue()); + $this->assertEqualsWithDelta(time() + 5000 * 60, $cookie->getExpiresTime(), 5); + $this->assertSame('recaller', $user->getRememberToken()); } public function testLoginMethodCreatesRememberTokenIfOneDoesntExist(): void { - [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $guard = new SessionGuard('default', $provider, $session, $app); - $guard->setCookieJar($cookie); - $foreverCookie = new Cookie($guard->getRecallerName(), 'foo'); - $cookie->expects('make')->andReturn($foreverCookie); - $cookie->expects('queue')->with($foreverCookie); - $guard->getSession()->expects('put')->with($guard->getName(), 'foo'); - $guard->getSession()->expects('put')->with('password_hash_default', hash_hmac('sha256', 'foo', 'base-key-for-password-hash-mac')); - $session->expects('regenerate'); - $user = m::mock(Authenticatable::class); - $user->expects('getAuthIdentifier')->times(2)->andReturn('foo'); - $user->expects('getAuthPassword')->times(2)->andReturn('foo'); - $user->expects('getRememberToken')->times(2)->andReturn(null); - $user->expects('setRememberToken'); + [$guard, $provider, $session] = $this->getRealGuard(); + $guard->setCookieJar($cookies = new CookieJar); + $expectedHash = hash_hmac('sha256', 'foo', 'base-key-for-password-hash-mac'); + $user = new GenericUser(['id' => 'foo', 'password' => 'foo', 'remember_token' => null]); $provider->expects('updateRememberToken'); $guard->login($user, true); + + $this->assertNotEmpty($user->getRememberToken()); + $this->assertSame( + 'foo|' . $user->getRememberToken() . '|' . $expectedHash, + $cookies->queued($guard->getRecallerName())->getValue() + ); + $this->assertSame($expectedHash, $session->get('password_hash_default')); } public function testLoginUsingIdLogsInWithUser(): void @@ -691,7 +625,7 @@ public function testLoginUsingIdLogsInWithUser(): void [$guard, $provider, $session] = $this->getRealGuard(); $user = new GenericUser(['id' => 10, 'password' => 'secret']); - $provider->expects('retrieveById')->with(10)->andReturn($user); + $provider->expects('retrieveById')->with(10)->returns($user); $this->assertSame($user, $guard->loginUsingId(10)); $this->assertSame($user, $guard->user()); @@ -702,7 +636,7 @@ public function testLoginUsingIdFailure(): void { [$guard, $provider, $session] = $this->getRealGuard(); - $provider->expects('retrieveById')->with(11)->andReturn(null); + $provider->expects('retrieveById')->with(11)->returns(null); $this->assertFalse($guard->loginUsingId(11)); $this->assertNull($guard->user()); @@ -714,7 +648,7 @@ public function testOnceUsingIdSetsUser(): void [$guard, $provider, $session] = $this->getRealGuard(); $user = new GenericUser(['id' => 10, 'password' => 'secret']); - $provider->expects('retrieveById')->with(10)->andReturn($user); + $provider->expects('retrieveById')->with(10)->returns($user); $this->assertSame($user, $guard->onceUsingId(10)); $this->assertSame($user, $guard->user()); @@ -725,7 +659,7 @@ public function testOnceUsingIdFailure(): void { [$guard, $provider] = $this->getRealGuard(); - $provider->expects('retrieveById')->with(11)->andReturn(null); + $provider->expects('retrieveById')->with(11)->returns(null); $this->assertFalse($guard->onceUsingId(11)); $this->assertNull($guard->user()); @@ -739,14 +673,14 @@ public function testUserUsesRememberCookieIfItExists(?string $passwordHash): voi $guard->getRecallerName() => 'id|recaller|' . $guard->hashPasswordForCookie($passwordHash), ])); $sessionId = $session->getId(); - $user = m::mock(Authenticatable::class); - $provider->expects('retrieveByToken')->with('id', 'recaller')->andReturn($user); - $user->expects('getAuthIdentifier')->twice()->andReturn('bar'); - $user->expects('getAuthPassword')->twice()->andReturn($passwordHash); - $events = m::mock(DispatcherContract::class); - $events->shouldReceive('hasListeners')->andReturnUsing(static fn (string $event): bool => $event === Login::class); + $user = Double::for(Authenticatable::class); + $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->allows('hasListeners')->resolves(static fn (string $event): bool => $event === Login::class); $rememberedLogins = []; - $events->expects('dispatch')->twice()->with(m::on(function (Login $event) use ($guard, &$rememberedLogins): bool { + $events->expects('dispatch')->times(2)->with(Argument::satisfies(function (Login $event) use ($guard, &$rememberedLogins): bool { $rememberedLogins[] = $guard->viaRemember(); return true; @@ -785,9 +719,9 @@ public function testUserReturnsNullWhenRememberCookieTokenDoesNotMatchAnyUser(): [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $guard = new SessionGuard('default', $provider, $session, $app); $cookieRequest = Request::create('/', 'GET', [], [$guard->getRecallerName() => 'id|recaller|baz']); - $app->shouldReceive('make')->with('request')->andReturn($cookieRequest); - $guard->getSession()->expects('get')->with($guard->getName())->andReturn(null); - $guard->getProvider()->expects('retrieveByToken')->with('id', 'recaller')->andReturn(null); + $app->instance('request', $cookieRequest); + $guard->getSession()->expects('get')->with($guard->getName())->returns(null); + $guard->getProvider()->expects('retrieveByToken')->with('id', 'recaller')->returns(null); $this->assertNull($guard->user()); $this->assertFalse($guard->viaRemember()); } @@ -797,9 +731,9 @@ public function testUserReturnsNullWhenRememberCookieHasEmptyToken(): void [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $guard = new SessionGuard('default', $provider, $session, $app); $cookieRequest = Request::create('/', 'GET', [], [$guard->getRecallerName() => 'id||baz']); - $app->shouldReceive('make')->with('request')->andReturn($cookieRequest); - $guard->getSession()->expects('get')->with($guard->getName())->andReturn(null); - $guard->getProvider()->shouldReceive('retrieveByToken')->never(); + $app->instance('request', $cookieRequest); + $guard->getSession()->expects('get')->with($guard->getName())->returns(null); + $guard->getProvider()->expects('retrieveByToken')->never(); $this->assertNull($guard->user()); $this->assertFalse($guard->viaRemember()); } @@ -809,11 +743,11 @@ public function testUserReturnsNullWhenPasswordlessUserHasInvalidRememberCookieH [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $guard = new SessionGuard('default', $provider, $session, $app); $cookieRequest = Request::create('/', 'GET', [], [$guard->getRecallerName() => 'id|recaller|baz']); - $app->shouldReceive('make')->with('request')->andReturn($cookieRequest); - $session->expects('get')->with($guard->getName())->andReturn(null); - $user = m::mock(Authenticatable::class); - $provider->expects('retrieveByToken')->with('id', 'recaller')->andReturn($user); - $user->expects('getAuthPassword')->andReturn(null); + $app->instance('request', $cookieRequest); + $session->expects('get')->with($guard->getName())->returns(null); + $user = Double::for(Authenticatable::class); + $provider->expects('retrieveByToken')->with('id', 'recaller')->returns($user); + $user->expects('getAuthPassword')->returns(null); $this->assertNull($guard->user()); $this->assertFalse($guard->viaRemember()); @@ -825,13 +759,13 @@ public function testUserRejectsRememberCookieWithInvalidPasswordHash(string $coo [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $guard = new SessionGuard('default', $provider, $session, $app); $cookieRequest = Request::create('/', 'GET', [], [$guard->getRecallerName() => 'id|recaller|' . $cookieHash]); - $app->shouldReceive('make')->with('request')->andReturn($cookieRequest); - $session->expects('get')->with($guard->getName())->andReturn(null); - $user = m::mock(Authenticatable::class); - $provider->expects('retrieveByToken')->with('id', 'recaller')->andReturn($user); - $user->expects('getAuthPassword')->andReturn('baz'); - $session->shouldNotReceive('put'); - $session->shouldNotReceive('regenerate'); + $app->instance('request', $cookieRequest); + $session->expects('get')->with($guard->getName())->returns(null); + $user = Double::for(Authenticatable::class); + $provider->expects('retrieveByToken')->with('id', 'recaller')->returns($user); + $user->expects('getAuthPassword')->returns('baz'); + $session->expects('put')->never(); + $session->expects('regenerate')->never(); $this->assertNull($guard->user()); $this->assertFalse($guard->viaRemember()); @@ -874,8 +808,8 @@ public function testLoginOnceSetsUser(): void [$guard, $provider, $session] = $this->getRealGuard(); $user = new GenericUser(['id' => 10, 'password' => 'secret']); - $provider->expects('retrieveByCredentials')->with(['foo'])->andReturn($user); - $provider->expects('validateCredentials')->with($user, ['foo'])->andReturn(true); + $provider->expects('retrieveByCredentials')->with(['foo'])->returns($user); + $provider->expects('validateCredentials')->with($user, ['foo'])->returns(true); $provider->expects('rehashPasswordIfRequired')->with($user, ['foo']); $this->assertTrue($guard->once(['foo'])); @@ -888,9 +822,9 @@ public function testLoginOnceFailure(): void [$guard, $provider] = $this->getRealGuard(); $user = new GenericUser(['id' => 10, 'password' => 'secret']); - $provider->expects('retrieveByCredentials')->with(['foo'])->andReturn($user); - $provider->expects('validateCredentials')->with($user, ['foo'])->andReturn(false); - $provider->shouldNotReceive('rehashPasswordIfRequired'); + $provider->expects('retrieveByCredentials')->with(['foo'])->returns($user); + $provider->expects('validateCredentials')->with($user, ['foo'])->returns(false); + $provider->expects('rehashPasswordIfRequired')->never(); $this->assertFalse($guard->once(['foo'])); $this->assertNull($guard->user()); @@ -914,9 +848,9 @@ public function testForgetUserSetsUserToNull(): void public function testForgetUserClearsCachedMiss(): void { $guard = $this->getGuard(); - $user = m::mock(Authenticatable::class); - $guard->getSession()->expects('get')->twice()->with($guard->getName())->andReturn(null, 42); - $guard->getProvider()->expects('retrieveById')->with(42)->andReturn($user); + $user = Double::for(Authenticatable::class); + $guard->getSession()->expects('get')->times(2)->with($guard->getName())->returns(null, 42); + $guard->getProvider()->expects('retrieveById')->with(42)->returns($user); $this->assertNull($guard->user()); $guard->forgetUser(); @@ -927,14 +861,14 @@ public function testForgetUserClearsCachedMiss(): void public function testAuthenticatedListenerCanReadAndReplaceResolvedUser(): void { $guard = $this->getGuard(); - $user = m::mock(Authenticatable::class); - $replacement = m::mock(Authenticatable::class); - $guard->getSession()->expects('get')->with($guard->getName())->andReturn(1); - $guard->getProvider()->expects('retrieveById')->with(1)->andReturn($user); + $user = Double::for(Authenticatable::class); + $replacement = Double::for(Authenticatable::class); + $guard->getSession()->expects('get')->with($guard->getName())->returns(1); + $guard->getProvider()->expects('retrieveById')->with(1)->returns($user); $events = $this->mockEventDispatcher(); - $events->expects('dispatch')->twice()->with(m::type(Authenticated::class)) - ->andReturnUsing(function (Authenticated $event) use ($guard, $user, $replacement): void { + $events->expects('dispatch')->times(2)->with(Argument::type(Authenticated::class)) + ->resolves(function (Authenticated $event) use ($guard, $user, $replacement): void { $this->assertTrue($guard->hasUser()); $this->assertSame($event->user, $guard->getUser()); $this->assertSame($event->user, $guard->user()); @@ -954,20 +888,20 @@ public function testRememberedUserIsCachedBeforeAndAfterSessionRotation(): void [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $guard = new SessionGuard('default', $provider, $session, $app); $request->cookies->set($guard->getRecallerName(), 'id|recaller|' . $guard->hashPasswordForCookie('baz')); - $app->shouldReceive('make')->with('request')->andReturn($request); + $app->instance('request', $request); $sessionId = 'old-session-id'; - $session->shouldReceive('getId')->andReturnUsing(function () use (&$sessionId): string { + $session->allows('getId')->resolves(function () use (&$sessionId): string { return $sessionId; }); - $session->expects('get')->with($guard->getName())->andReturn(null); - $user = m::mock(Authenticatable::class); - $provider->expects('retrieveByToken')->with('id', 'recaller')->andReturn($user); - $provider->shouldNotReceive('retrieveById'); - $user->expects('getAuthPassword')->andReturn('baz'); - $user->expects('getAuthIdentifier')->andReturn('id'); + $session->expects('get')->with($guard->getName())->returns(null); + $user = Double::for(Authenticatable::class); + $provider->expects('retrieveByToken')->with('id', 'recaller')->returns($user); + $provider->expects('retrieveById')->never(); + $user->expects('getAuthPassword')->returns('baz'); + $user->expects('getAuthIdentifier')->returns('id'); $session->expects('put')->with($guard->getName(), 'id'); $session->expects('regenerate')->with(true) - ->andReturnUsing(function () use ($guard, $user, &$sessionId): bool { + ->resolves(function () use ($guard, $user, &$sessionId): bool { // Database session deletion can invoke query listeners before the ID changes. $this->assertTrue($guard->hasUser()); $this->assertSame($user, $guard->getUser()); @@ -977,8 +911,8 @@ public function testRememberedUserIsCachedBeforeAndAfterSessionRotation(): void return true; }); $events = $this->mockEventDispatcher(); - $events->expects('dispatch')->with(m::type(Login::class)) - ->andReturnUsing(function (Login $event) use ($guard, $user): void { + $events->expects('dispatch')->with(Argument::type(Login::class)) + ->resolves(function (Login $event) use ($guard, $user): void { $this->assertSame($user, $event->user); $this->assertTrue($guard->hasUser()); $this->assertSame($user, $guard->getUser()); @@ -995,22 +929,22 @@ public function testRememberedUserIsCachedBeforeAndAfterSessionRotation(): void public function testLoginListenersSeeTheNewUserBeforeAuthenticatedIsFired(): void { $guard = $this->getGuard(); - $guard->setUser(m::mock(Authenticatable::class)); - $user = m::mock(Authenticatable::class); - $user->expects('getAuthIdentifier')->andReturn(42); - $user->expects('getAuthPassword')->andReturn(null); + $guard->setUser(Double::for(Authenticatable::class)); + $user = Double::for(Authenticatable::class); + $user->expects('getAuthIdentifier')->returns(42); + $user->expects('getAuthPassword')->returns(null); $guard->getSession()->expects('put')->with($guard->getName(), 42); $guard->getSession()->expects('remove')->with('password_hash_default'); $guard->getSession()->expects('regenerate')->with(true); $events = $this->mockEventDispatcher(); - $events->expects('dispatch')->with(m::type(Login::class))->ordered() - ->andReturnUsing(function (Login $event) use ($guard, $user): void { + $events->expects('dispatch')->with(Argument::type(Login::class))->ordered() + ->resolves(function (Login $event) use ($guard, $user): void { $this->assertSame($user, $event->user); $this->assertTrue($guard->hasUser()); $this->assertSame($user, $guard->getUser()); $this->assertSame($user, $guard->user()); }); - $events->expects('dispatch')->with(m::type(Authenticated::class))->ordered(); + $events->expects('dispatch')->with(Argument::type(Authenticated::class))->ordered(); $guard->setDispatcher($events); $guard->login($user); @@ -1023,24 +957,24 @@ public function testLoggedInUserSurvivesIndependentSessionRotation(): void [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $guard = new SessionGuard('default', $provider, $session, $app); $sessionId = 'session-id'; - $session->shouldReceive('getId')->andReturnUsing(function () use (&$sessionId): string { + $session->allows('getId')->resolves(function () use (&$sessionId): string { return $sessionId; }); - $session->expects('regenerate')->twice()->andReturnUsing(function () use (&$sessionId): bool { + $session->expects('regenerate')->times(2)->resolves(function () use (&$sessionId): bool { $sessionId .= '-rotated'; return true; }); - $user = m::mock(Authenticatable::class); - $user->expects('getAuthIdentifier')->andReturn(42); - $user->expects('getAuthPassword')->andReturn(null); + $user = Double::for(Authenticatable::class); + $user->expects('getAuthIdentifier')->returns(42); + $user->expects('getAuthPassword')->returns(null); $session->expects('put')->with($guard->getName(), 42); $session->expects('remove')->with('password_hash_default'); - $session->shouldNotReceive('get'); - $provider->shouldNotReceive('retrieveById'); + $session->expects('get')->never(); + $provider->expects('retrieveById')->never(); $events = $this->mockEventDispatcher(); - $events->expects('dispatch')->with(m::type(Login::class)); - $events->expects('dispatch')->with(m::type(Authenticated::class)); + $events->expects('dispatch')->with(Argument::type(Login::class)); + $events->expects('dispatch')->with(Argument::type(Authenticated::class)); $guard->setDispatcher($events); $guard->login($user); @@ -1057,15 +991,15 @@ public function testMissingUserIsResolvedAgainWhenSessionStateChanges(bool $sess [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $guard = new SessionGuard('default', $provider, $session, $app); $sessionId = 'session-id'; - $session->shouldReceive('getId')->andReturnUsing(function () use (&$sessionId): string { + $session->allows('getId')->resolves(function () use (&$sessionId): string { return $sessionId; }); - $session->shouldReceive('isStarted')->andReturnUsing(function () use (&$sessionStarted): bool { + $session->allows('isStarted')->resolves(function () use (&$sessionStarted): bool { return $sessionStarted; }); - $session->expects('get')->twice()->with($guard->getName())->andReturn(null, 42); - $user = m::mock(Authenticatable::class); - $provider->expects('retrieveById')->with(42)->andReturn($user); + $session->expects('get')->times(2)->with($guard->getName())->returns(null, 42); + $user = Double::for(Authenticatable::class); + $provider->expects('retrieveById')->with(42)->returns($user); $this->assertNull($guard->user()); $this->assertNull($guard->user()); @@ -1092,9 +1026,9 @@ public function testMissingUserIsNotInheritedByAChildRequest(): void { [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $guard = new SessionGuard('default', $provider, $session, $app); - $session->expects('get')->twice()->with($guard->getName())->andReturn(null, 42); - $user = m::mock(Authenticatable::class); - $provider->expects('retrieveById')->with(42)->andReturn($user); + $session->expects('get')->times(2)->with($guard->getName())->returns(null, 42); + $user = Double::for(Authenticatable::class); + $provider->expects('retrieveById')->with(42)->returns($user); $this->assertNull($guard->user()); @@ -1110,10 +1044,10 @@ public function testMissingUserIsNotInheritedByAChildRequest(): void public function testSetUserBeforeSessionStartCachesTheUser(): void { [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $session->shouldReceive('isStarted')->andReturn(false); + $session->allows('isStarted')->returns(false); $guard = new SessionGuard('default', $provider, $session, $app, $timebox); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $guard->setUser($user); @@ -1126,20 +1060,20 @@ public function testUserSetBeforeSessionStartCanBeReplacedAfterSessionStarts(): { [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $sessionStarted = false; - $session->shouldReceive('isStarted')->andReturnUsing(function () use (&$sessionStarted): bool { + $session->allows('isStarted')->resolves(function () use (&$sessionStarted): bool { return $sessionStarted; }); $guard = new SessionGuard('default', $provider, $session, $app, $timebox); - $unstartedUser = m::mock(Authenticatable::class); + $unstartedUser = Double::for(Authenticatable::class); $guard->setUser($unstartedUser); - $session->shouldNotReceive('get'); + $session->expects('get')->never(); $this->assertSame($unstartedUser, $guard->user()); $sessionStarted = true; - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $guard->setUser($user); $this->assertSame($user, $guard->user()); @@ -1149,10 +1083,10 @@ public function testUserSetBeforeSessionStartCanBeReplacedAfterSessionStarts(): public function testForgetUserClearsUserSetBeforeSessionStart(): void { [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $session->shouldReceive('isStarted')->andReturn(false); + $session->allows('isStarted')->returns(false); $guard = new SessionGuard('default', $provider, $session, $app, $timebox); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $guard->setUser($user); $this->assertTrue($guard->hasUser()); @@ -1166,14 +1100,11 @@ public function testForgetUserClearsUserSetBeforeSessionStart(): void public function testLoggedOutFlagMakesUserReturnNull(): void { [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class) - ->onlyMethods(['clearUserDataFromStorage']) - ->setConstructorArgs(['default', $provider, $session, $app]) - ->getMock(); - $mock->expects($this->once())->method('clearUserDataFromStorage'); + $mock = Double::for(new SessionGuard('default', $provider, $session, $app))->passthru(); + $mock->expects('clearUserDataFromStorage'); - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getRememberToken')->andReturn(null); + $user = Double::for(Authenticatable::class); + $user->allows('getRememberToken')->returns(null); $mock->setUser($user); $this->assertSame($user, $mock->user()); @@ -1182,20 +1113,20 @@ public function testLoggedOutFlagMakesUserReturnNull(): void $this->assertNull($mock->user()); - $nextUser = m::mock(Authenticatable::class); - $nextUser->expects('getAuthIdentifier')->andReturn(42); - $nextUser->expects('getAuthPassword')->andReturn(null); + $nextUser = Double::for(Authenticatable::class); + $nextUser->expects('getAuthIdentifier')->returns(42); + $nextUser->expects('getAuthPassword')->returns(null); $session->expects('put')->with($mock->getName(), 42); $session->expects('remove')->with('password_hash_default'); $session->expects('regenerate')->with(true); $events = $this->mockEventDispatcher(); - $events->expects('dispatch')->with(m::type(Login::class))->ordered() - ->andReturnUsing(function (Login $event) use ($mock, $nextUser): void { + $events->expects('dispatch')->with(Argument::type(Login::class))->ordered() + ->resolves(function (Login $event) use ($mock, $nextUser): void { $this->assertSame($nextUser, $event->user); $this->assertSame($nextUser, $mock->getUser()); $this->assertSame($nextUser, $mock->user()); }); - $events->expects('dispatch')->with(m::type(Authenticated::class))->ordered(); + $events->expects('dispatch')->with(Argument::type(Authenticated::class))->ordered(); $mock->setDispatcher($events); $mock->login($nextUser); @@ -1206,15 +1137,12 @@ public function testLoggedOutFlagMakesUserReturnNull(): void public function testIdReturnsNullAfterLogout(): void { [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); - $mock = $this->getMockBuilder(SessionGuard::class) - ->onlyMethods(['clearUserDataFromStorage']) - ->setConstructorArgs(['default', $provider, $session, $app]) - ->getMock(); - $mock->expects($this->once())->method('clearUserDataFromStorage'); + $mock = Double::for(new SessionGuard('default', $provider, $session, $app))->passthru(); + $mock->expects('clearUserDataFromStorage'); - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getRememberToken')->andReturn(null); - $user->shouldReceive('getAuthIdentifier')->andReturn(42); + $user = Double::for(Authenticatable::class); + $user->allows('getRememberToken')->returns(null); + $user->allows('getAuthIdentifier')->returns(42); $mock->setUser($user); $this->assertSame(42, $mock->id()); @@ -1228,7 +1156,7 @@ public function testGetRequestResolvesFromContainer(): void { [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $freshRequest = Request::create('/new-path', 'POST'); - $app->shouldReceive('make')->with('request')->andReturn($freshRequest); + $app->instance('request', $freshRequest); $guard = new SessionGuard('default', $provider, $session, $app, $timebox); @@ -1251,10 +1179,9 @@ public function testAttemptingRegistersEventListener(): void [$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks(); $guard = new SessionGuard('default', $provider, $session, $app, $timebox); - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('listen') - ->with(Attempting::class, m::type('callable')) - ->once(); + $dispatcher = Double::for(DispatcherContract::class); + $dispatcher->expects('listen') + ->with(Attempting::class, Argument::type('callable')); $guard->setDispatcher($dispatcher); $guard->attempting(function (): void {}); @@ -1263,17 +1190,17 @@ public function testAttemptingRegistersEventListener(): void public function testAttemptSkipsEventDispatchWhenNoListenersAreRegistered(): void { $guard = $this->getGuard(); - $guard->setDispatcher($events = m::mock(DispatcherContract::class)); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(false); - $events->shouldNotReceive('dispatch'); + $guard->setDispatcher($events = Double::for(DispatcherContract::class)); + $events->allows('hasListeners')->returns(false); + $events->expects('dispatch')->never(); $timebox = $guard->getTimebox(); - $timebox->shouldReceive('call')->once()->andReturnUsing(function (Closure $callback, int $microseconds) use ($timebox): bool { + $timebox->expects('call')->resolves(function (Closure $callback, int $microseconds) use ($timebox): bool { return $callback($timebox); }); - $guard->getProvider()->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn(null); - $guard->getProvider()->shouldNotReceive('rehashPasswordIfRequired'); + $guard->getProvider()->expects('retrieveByCredentials')->with(['foo'])->returns(null); + $guard->getProvider()->expects('rehashPasswordIfRequired')->never(); $this->assertFalse($guard->attempt(['foo'])); } @@ -1334,7 +1261,7 @@ public function testGetNameContainsGuardName(): void protected function getRealGuard(?Request $request = null): array { $session = new Store('test', new ArraySessionHandler(10)); - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $app = new Container; $app->instance('request', $request ?? Request::create('/', 'GET')); @@ -1356,19 +1283,19 @@ protected function getGuard(): SessionGuard */ protected function getMocks(): array { - $session = m::mock(Session::class); - $session->shouldReceive('isStarted')->andReturn(true)->byDefault(); - $session->shouldReceive('getId')->andReturn('test-session-id')->byDefault(); + $session = Double::for(Session::class); + $session->allows('isStarted')->returns(true); + $session->allows('getId')->returns('test-session-id'); - $app = m::mock(Container::class); - $app->shouldReceive('make')->with('request')->andReturn(Request::create('/', 'GET'))->byDefault(); + $app = new Container; + $app->instance('request', Request::create('/', 'GET')); return [ $session, - m::mock(UserProvider::class), + Double::for(UserProvider::class), Request::create('/', 'GET'), - m::mock(CookieJar::class), - m::mock(Timebox::class), + Double::for(CookieJar::class), + Double::for(Timebox::class), $app, ]; } @@ -1378,8 +1305,8 @@ protected function getMocks(): array */ protected function mockEventDispatcher(): DispatcherContract { - $events = m::mock(DispatcherContract::class); - $events->shouldReceive('hasListeners')->byDefault()->andReturn(true); + $events = Double::for(DispatcherContract::class); + $events->allows('hasListeners')->returns(true); return $events; } diff --git a/tests/Auth/AuthPasswordBrokerManagerTest.php b/tests/Auth/AuthPasswordBrokerManagerTest.php index 0e54d4931..8e0f997ae 100644 --- a/tests/Auth/AuthPasswordBrokerManagerTest.php +++ b/tests/Auth/AuthPasswordBrokerManagerTest.php @@ -5,6 +5,7 @@ namespace Hypervel\Tests\Auth; use BackedEnum; +use Hypervel\Auth\AuthManager; use Hypervel\Auth\Passwords\DatabaseTokenRepository; use Hypervel\Auth\Passwords\PasswordBroker as PasswordBrokerImplementation; use Hypervel\Auth\Passwords\PasswordBrokerManager; @@ -14,13 +15,16 @@ use Hypervel\Contracts\Auth\Factory as AuthFactory; use Hypervel\Contracts\Auth\PasswordBroker as PasswordBrokerContract; use Hypervel\Contracts\Auth\UserProvider; +use Hypervel\Contracts\Cache\Factory as CacheFactory; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Contracts\Hashing\Hasher; use Hypervel\Database\Connection; use Hypervel\Database\ConnectionResolverInterface; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; @@ -28,6 +32,8 @@ class AuthPasswordBrokerManagerTest extends TestCase { + use VerifiesDoubles; + public function testResolveBrokerNameForGuardReturnsDeclaredBroker(): void { $manager = new PasswordBrokerManager($this->makeContainer([ @@ -196,8 +202,8 @@ public function testDefaultDriverThrowsWhenGuardDeclaresNoBroker(): void public function testSetDefaultDriverOverridesGuardDeclaration(): void { - $auth = $this->mockAuthFactory('web'); - $auth->shouldNotReceive('getDefaultDriver'); + $auth = Double::for(AuthFactory::class); + $auth->expects('getDefaultDriver')->never(); $container = $this->makeContainer([ 'auth' => [ @@ -219,7 +225,7 @@ public function testSetDefaultDriverOverridesGuardDeclaration(): void #[DataProvider('backedBrokerNames')] public function testBrokerCanResolveBackedEnum(BackedEnum $name, string $expected): void { - $broker = m::mock(PasswordBrokerContract::class); + $broker = Double::for(PasswordBrokerContract::class); $manager = new AuthPasswordBrokerManagerStub(new Container); $manager->resolvedBroker = $broker; @@ -307,20 +313,18 @@ public function testBrokerWithExplicitNameBypassesDefaultResolution(): void ], ], ]); - $container->instance('auth', $auth = m::mock()); - $container->instance('db', $database = m::mock(ConnectionResolverInterface::class)); - $container->instance('hash', m::mock(Hasher::class)); + $container->instance('auth', $auth = Double::for(AuthManager::class)); + $container->instance('db', $database = Double::for(ConnectionResolverInterface::class)); + $container->instance('hash', Double::for(Hasher::class)); - $auth->shouldReceive('createUserProvider') - ->once() + $auth->expects('createUserProvider') ->with('admins') - ->andReturn(m::mock(UserProvider::class)); - $connection = m::mock(Connection::class); + ->returns(Double::for(UserProvider::class)); + $connection = Double::for(Connection::class); $resolutions = 0; - $database->shouldReceive('connection') - ->once() + $database->expects('connection') ->with('passwords') - ->andReturnUsing(function () use (&$resolutions, $connection) { + ->resolves(function () use (&$resolutions, $connection) { ++$resolutions; return $connection; @@ -352,22 +356,21 @@ public function testBrokerWithExplicitFalseyNameDoesNotFallBackToDefaultDriver() ], ], ]); - $container->instance('auth', $auth = m::mock()); - $container->instance('db', $database = m::mock(ConnectionResolverInterface::class)); - $container->instance('hash', m::mock(Hasher::class)); + $container->instance('auth', $auth = Double::for(AuthManager::class)); + $container->instance('db', $database = Double::for(ConnectionResolverInterface::class)); + $container->instance('hash', Double::for(Hasher::class)); - $auth->shouldReceive('createUserProvider') - ->once() + $auth->expects('createUserProvider') ->with('zero') - ->andReturn(m::mock(UserProvider::class)); - $database->shouldNotReceive('connection'); + ->returns(Double::for(UserProvider::class)); + $database->expects('connection')->never(); $this->assertInstanceOf(PasswordBrokerContract::class, (new PasswordBrokerManager($container))->broker('0')); } public function testBrokerWithEmptyNameUsesDefaultDriver(): void { - $broker = m::mock(PasswordBrokerContract::class); + $broker = Double::for(PasswordBrokerContract::class); $manager = new AuthPasswordBrokerManagerStub(new Container); $manager->resolvedBroker = $broker; $manager->setDefaultDriver('users'); @@ -384,16 +387,15 @@ public function testShippedDatabaseBrokerUsesDefaultConnection(): void ], 'auth' => require __DIR__ . '/../../src/foundation/config/auth.php', ]); - $container->instance('auth', $auth = m::mock()); - $container->instance('db', $database = m::mock(ConnectionResolverInterface::class)); - $container->instance('hash', m::mock(Hasher::class)); + $container->instance('auth', $auth = Double::for(AuthManager::class)); + $container->instance('db', $database = Double::for(ConnectionResolverInterface::class)); + $container->instance('hash', Double::for(Hasher::class)); - $auth->shouldReceive('createUserProvider') - ->once() + $auth->expects('createUserProvider') ->with('users') - ->andReturn(m::mock(UserProvider::class)); - $connection = m::mock(Connection::class); - $database->shouldReceive('connection')->once()->with(null)->andReturn($connection); + ->returns(Double::for(UserProvider::class)); + $connection = Double::for(Connection::class); + $database->expects('connection')->with(null)->returns($connection); $broker = (new PasswordBrokerManager($container))->broker('users'); $repository = (new ReflectionProperty($broker, 'tokens'))->getValue($broker); @@ -419,15 +421,14 @@ public function testBrokerUsesDefaultExpiryAndThrottleWhenOmitted(): void ], ], ]); - $container->instance('auth', $auth = m::mock()); - $container->instance('db', $database = m::mock(ConnectionResolverInterface::class)); - $container->instance('hash', m::mock(Hasher::class)); + $container->instance('auth', $auth = Double::for(AuthManager::class)); + $container->instance('db', $database = Double::for(ConnectionResolverInterface::class)); + $container->instance('hash', Double::for(Hasher::class)); - $auth->shouldReceive('createUserProvider') - ->once() + $auth->expects('createUserProvider') ->with('users') - ->andReturn(m::mock(UserProvider::class)); - $database->shouldNotReceive('connection'); + ->returns(Double::for(UserProvider::class)); + $database->expects('connection')->never(); $broker = (new PasswordBrokerManager($container))->broker('users'); $repository = (new ReflectionProperty($broker, 'tokens'))->getValue($broker); @@ -454,18 +455,16 @@ public function testCacheBrokerUsesDefaultStore(array $broker): void ], ], ]); - $container->instance('auth', $auth = m::mock()); - $container->instance('cache', $cache = m::mock()); - $container->instance('hash', m::mock(Hasher::class)); + $container->instance('auth', $auth = Double::for(AuthManager::class)); + $container->instance('cache', $cache = Double::for(CacheFactory::class)); + $container->instance('hash', Double::for(Hasher::class)); - $auth->shouldReceive('createUserProvider') - ->once() + $auth->expects('createUserProvider') ->with('users') - ->andReturn(m::mock(UserProvider::class)); - $cache->shouldReceive('store') - ->once() + ->returns(Double::for(UserProvider::class)); + $cache->expects('store') ->with(null) - ->andReturn(m::mock(CacheRepository::class)); + ->returns(Double::for(CacheRepository::class)); $this->assertInstanceOf( PasswordBrokerContract::class, @@ -514,10 +513,10 @@ public function testBrokerRejectsUnknownDriver(): void public function testRefreshingDispatcherUpdatesOnlyConcreteResolvedBrokers(): void { $manager = new AuthPasswordBrokerManagerStub(new Container); - $concreteBroker = m::mock(PasswordBrokerImplementation::class); - $customBroker = m::mock(PasswordBrokerContract::class); - $events = m::mock(Dispatcher::class); - $concreteBroker->shouldReceive('setDispatcher')->once()->with($events); + $concreteBroker = Double::for(PasswordBrokerImplementation::class); + $customBroker = Double::for(PasswordBrokerContract::class); + $events = Double::for(Dispatcher::class); + $concreteBroker->expects('setDispatcher')->with(Argument::same($events)); $manager->seedBroker('concrete', $concreteBroker); $manager->seedBroker('custom', $customBroker); @@ -566,8 +565,8 @@ private function makeContainer(array $config): Container */ private function mockAuthFactory(string $guard): AuthFactory { - $auth = m::mock(AuthFactory::class); - $auth->shouldReceive('getDefaultDriver')->andReturn($guard)->byDefault(); + $auth = Double::for(AuthFactory::class); + $auth->allows('getDefaultDriver')->returns($guard); return $auth; } diff --git a/tests/Auth/AuthPasswordBrokerTest.php b/tests/Auth/AuthPasswordBrokerTest.php index a7d2d4ff0..ee5a16ce9 100755 --- a/tests/Auth/AuthPasswordBrokerTest.php +++ b/tests/Auth/AuthPasswordBrokerTest.php @@ -17,12 +17,16 @@ use Hypervel\Support\Arr; use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Override; use UnexpectedValueException; class AuthPasswordBrokerTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ @@ -37,7 +41,7 @@ protected function setUp(): void public function testIfUserIsNotFoundErrorRedirectIsReturned(): void { $broker = $this->getBroker($mocks = $this->getMocks()); - $mocks['users']->expects('retrieveByCredentials')->with(['credentials'])->andReturnNull(); + $mocks['users']->expects('retrieveByCredentials')->with(['credentials'])->returns(null); $this->assertSame(PasswordBrokerContract::INVALID_USER, $broker->sendResetLink(['credentials'])); } @@ -46,8 +50,8 @@ public function testIfTokenIsRecentlyCreated(): void { $broker = $this->getBroker($mocks = $this->getMocks()); $user = new User; - $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->andReturn($user); - $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->andReturn(true); + $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user); + $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(true); $this->assertSame(PasswordBrokerContract::RESET_THROTTLED, $broker->sendResetLink(['foo'])); } @@ -57,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'])->andReturn(m::mock(Authenticatable::class)); + $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns(Double::for(Authenticatable::class)); $broker->getUser(['foo']); } @@ -66,7 +70,7 @@ public function testUserIsRetrievedByCredentials(): void { $broker = $this->getBroker($mocks = $this->getMocks()); $user = new User; - $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->andReturn($user); + $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user); $this->assertEquals($user, $broker->getUser(['foo'])); } @@ -74,10 +78,10 @@ public function testUserIsRetrievedByCredentials(): void public function testBrokerCreatesTokenAndRedirectsWithoutError(): void { $broker = $this->getBroker($mocks = $this->getMocks()); - $user = m::mock(Authenticatable::class, CanResetPassword::class); - $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->andReturn($user); - $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->andReturn(false); - $mocks['tokens']->expects('create')->with($user)->andReturn('token'); + $user = Double::for(Authenticatable::class, CanResetPassword::class); + $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user); + $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false); + $mocks['tokens']->expects('create')->with($user)->returns('token'); $user->expects('sendPasswordResetNotification')->with('token'); $this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo'])); @@ -86,13 +90,13 @@ public function testBrokerCreatesTokenAndRedirectsWithoutError(): void public function testResetLinkEventIsSkippedWhenThereAreNoListeners(): void { $mocks = $this->getMocks(); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(PasswordResetLinkSent::class)->andReturnFalse(); - $events->shouldNotReceive('dispatch'); - $mocks['users']->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn($user = m::mock(Authenticatable::class . ',' . CanResetPassword::class)); - $mocks['tokens']->shouldReceive('recentlyCreatedToken')->once()->with($user)->andReturnFalse(); - $mocks['tokens']->shouldReceive('create')->once()->with($user)->andReturn('token'); - $user->shouldReceive('sendPasswordResetNotification')->once()->with('token'); + $events = Double::for(Dispatcher::class); + $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'); + $user->expects('sendPasswordResetNotification')->with('token'); $broker = new PasswordBroker($mocks['tokens'], $mocks['users'], $mocks['name'], $events); $this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo'])); @@ -101,15 +105,14 @@ public function testResetLinkEventIsSkippedWhenThereAreNoListeners(): void public function testResetLinkEventIsDispatchedWhenThereIsAListener(): void { $mocks = $this->getMocks(); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(PasswordResetLinkSent::class)->andReturnTrue(); - $events->shouldReceive('dispatch') - ->once() - ->with(m::type(PasswordResetLinkSent::class)); - $mocks['users']->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn($user = m::mock(Authenticatable::class . ',' . CanResetPassword::class)); - $mocks['tokens']->shouldReceive('recentlyCreatedToken')->once()->with($user)->andReturnFalse(); - $mocks['tokens']->shouldReceive('create')->once()->with($user)->andReturn('token'); - $user->shouldReceive('sendPasswordResetNotification')->once()->with('token'); + $events = Double::for(Dispatcher::class); + $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'); + $user->expects('sendPasswordResetNotification')->with('token'); $broker = new PasswordBroker($mocks['tokens'], $mocks['users'], $mocks['name'], $events); $this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo'])); @@ -118,17 +121,17 @@ public function testResetLinkEventIsDispatchedWhenThereIsAListener(): void public function testEventDispatcherCanBeReplacedOnAnExistingBroker(): void { $mocks = $this->getMocks(); - $originalEvents = m::mock(Dispatcher::class); - $originalEvents->shouldReceive('hasListeners', 'dispatch')->never(); - $replacementEvents = m::mock(Dispatcher::class); - $replacementEvents->shouldReceive('hasListeners')->once()->with(PasswordResetLinkSent::class)->andReturnTrue(); - $replacementEvents->shouldReceive('dispatch') - ->once() - ->with(m::type(PasswordResetLinkSent::class)); - $mocks['users']->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn($user = m::mock(Authenticatable::class . ',' . CanResetPassword::class)); - $mocks['tokens']->shouldReceive('recentlyCreatedToken')->once()->with($user)->andReturnFalse(); - $mocks['tokens']->shouldReceive('create')->once()->with($user)->andReturn('token'); - $user->shouldReceive('sendPasswordResetNotification')->once()->with('token'); + $originalEvents = Double::for(Dispatcher::class); + $originalEvents->expects('hasListeners')->never(); + $originalEvents->expects('dispatch')->never(); + $replacementEvents = Double::for(Dispatcher::class); + $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'); + $user->expects('sendPasswordResetNotification')->with('token'); $broker = new PasswordBroker($mocks['tokens'], $mocks['users'], $mocks['name'], $originalEvents); $broker->setDispatcher($replacementEvents); @@ -139,7 +142,7 @@ public function testEventDispatcherCanBeReplacedOnAnExistingBroker(): void public function testRedirectIsReturnedByResetWhenUserCredentialsInvalid(): void { $broker = $this->getBroker($mocks = $this->getMocks()); - $mocks['users']->expects('retrieveByCredentials')->with(['creds'])->andReturn(null); + $mocks['users']->expects('retrieveByCredentials')->with(['creds'])->returns(null); $this->assertSame(PasswordBrokerContract::INVALID_USER, $broker->reset(['creds'], function (): void { })); @@ -150,8 +153,8 @@ public function testRedirectReturnedByRemindWhenRecordDoesntExistInTable(): void $credentials = ['token' => 'token']; $broker = $this->getBroker($mocks = $this->getMocks()); $user = new User; - $mocks['users']->expects('retrieveByCredentials')->with(Arr::except($credentials, ['token']))->andReturn($user); - $mocks['tokens']->expects('exists')->with($user, 'token')->andReturn(false); + $mocks['users']->expects('retrieveByCredentials')->with(Arr::except($credentials, ['token']))->returns($user); + $mocks['tokens']->expects('exists')->with($user, 'token')->returns(false); $this->assertSame(PasswordBrokerContract::INVALID_TOKEN, $broker->reset($credentials, function (): void { })); @@ -162,8 +165,8 @@ public function testResetRemovesRecordOnReminderTableAndCallsCallback(): void $resetArguments = null; $broker = $this->getBroker($mocks = $this->getMocks()); $user = new User; - $mocks['users']->expects('retrieveByCredentials')->with(['password' => 'password'])->andReturn($user); - $mocks['tokens']->expects('exists')->with($user, 'token')->andReturn(true); + $mocks['users']->expects('retrieveByCredentials')->with(['password' => 'password'])->returns($user); + $mocks['tokens']->expects('exists')->with($user, 'token')->returns(true); $mocks['tokens']->expects('delete')->with($user); $callback = function (CanResetPassword $user, string $password) use (&$resetArguments): string { $resetArguments = ['user' => $user, 'password' => $password]; @@ -185,9 +188,9 @@ public function testExecutesCallbackInsteadOfSendingNotification(): void $broker = $this->getBroker($mocks = $this->getMocks()); $user = new User; - $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->andReturn($user); - $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->andReturn(false); - $mocks['tokens']->expects('create')->with($user)->andReturn('token'); + $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user); + $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false); + $mocks['tokens']->expects('create')->with($user)->returns('token'); $this->assertEquals(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo'], $closure)); @@ -197,13 +200,12 @@ public function testExecutesCallbackInsteadOfSendingNotification(): void public function testSendResetLinkStampsSendingBrokerContext(): void { $broker = $this->getBroker($mocks = $this->getMocks()); - $mocks['users']->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn($user = m::mock(Authenticatable::class . ',' . CanResetPassword::class)); - $mocks['tokens']->shouldReceive('recentlyCreatedToken')->once()->with($user)->andReturn(false); - $mocks['tokens']->shouldReceive('create')->once()->with($user)->andReturn('token'); - $user->shouldReceive('sendPasswordResetNotification') - ->once() + $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'); + $user->expects('sendPasswordResetNotification') ->with('token') - ->andReturnUsing(function (): void { + ->resolves(function (): void { $this->assertSame('users', CoroutineContext::get(PasswordBroker::SENDING_BROKER_CONTEXT_KEY)); }); @@ -215,10 +217,10 @@ public function testSendResetLinkRestoresPreviousSendingBrokerContext(): void CoroutineContext::set(PasswordBroker::SENDING_BROKER_CONTEXT_KEY, 'outer'); $broker = $this->getBroker($mocks = $this->getMocks()); - $mocks['users']->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn($user = m::mock(Authenticatable::class . ',' . CanResetPassword::class)); - $mocks['tokens']->shouldReceive('recentlyCreatedToken')->once()->with($user)->andReturn(false); - $mocks['tokens']->shouldReceive('create')->once()->with($user)->andReturn('token'); - $user->shouldReceive('sendPasswordResetNotification')->once()->with('token'); + $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'); + $user->expects('sendPasswordResetNotification')->with('token'); $this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo'])); $this->assertSame('outer', CoroutineContext::get(PasswordBroker::SENDING_BROKER_CONTEXT_KEY)); @@ -229,10 +231,10 @@ public function testSendResetLinkForgetsSendingBrokerContextWhenNoneExisted(): v CoroutineContext::forget(PasswordBroker::SENDING_BROKER_CONTEXT_KEY); $broker = $this->getBroker($mocks = $this->getMocks()); - $mocks['users']->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn($user = m::mock(Authenticatable::class . ',' . CanResetPassword::class)); - $mocks['tokens']->shouldReceive('recentlyCreatedToken')->once()->with($user)->andReturn(false); - $mocks['tokens']->shouldReceive('create')->once()->with($user)->andReturn('token'); - $user->shouldReceive('sendPasswordResetNotification')->once()->with('token'); + $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'); + $user->expects('sendPasswordResetNotification')->with('token'); $this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo'])); $this->assertFalse(CoroutineContext::has(PasswordBroker::SENDING_BROKER_CONTEXT_KEY)); @@ -241,10 +243,10 @@ public function testSendResetLinkForgetsSendingBrokerContextWhenNoneExisted(): v public function testSendResetLinkStampsContextForCallback(): void { $broker = $this->getBroker($mocks = $this->getMocks()); - $mocks['users']->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn($user = m::mock(Authenticatable::class . ',' . CanResetPassword::class)); - $mocks['tokens']->shouldReceive('recentlyCreatedToken')->once()->with($user)->andReturn(false); - $mocks['tokens']->shouldReceive('create')->once()->with($user)->andReturn('token'); - $user->shouldNotReceive('sendPasswordResetNotification'); + $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'); + $user->expects('sendPasswordResetNotification')->never(); $this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo'], function (): void { $this->assertSame('users', CoroutineContext::get(PasswordBroker::SENDING_BROKER_CONTEXT_KEY)); @@ -265,8 +267,8 @@ protected function getBroker(array $mocks): PasswordBroker protected function getMocks(): array { return [ - 'tokens' => m::mock(TokenRepositoryInterface::class), - 'users' => m::mock(UserProvider::class), + 'tokens' => Double::for(TokenRepositoryInterface::class), + 'users' => Double::for(UserProvider::class), 'name' => 'users', ]; } diff --git a/tests/Auth/AuthTokenGuardTest.php b/tests/Auth/AuthTokenGuardTest.php index 3a1093c81..26c5541d3 100644 --- a/tests/Auth/AuthTokenGuardTest.php +++ b/tests/Auth/AuthTokenGuardTest.php @@ -10,13 +10,16 @@ use Hypervel\Contracts\Auth\UserProvider; use Hypervel\Http\Request; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use function Hypervel\Coroutine\parallel; class AuthTokenGuardTest extends TestCase { + use VerifiesDoubles; + /** * Create a TokenGuard with a request seeded in coroutine context. */ @@ -34,10 +37,10 @@ protected function createGuard( public function testUserCanBeRetrievedByQueryStringVariable(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns($user); $request = Request::create('/', 'GET', ['api_token' => 'foo']); $guard = $this->createGuard($provider, $request); @@ -52,10 +55,10 @@ public function testUserCanBeRetrievedByQueryStringVariable(): void public function testTokenCanBeHashed(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['api_token' => hash('sha256', 'foo')])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['api_token' => hash('sha256', 'foo')])->returns($user); $request = Request::create('/', 'GET', ['api_token' => 'foo']); $guard = $this->createGuard($provider, $request, 'api_token', 'api_token', hash: true); @@ -70,8 +73,8 @@ public function testTokenCanBeHashed(): void public function testUserCannotBeRetrievedWithNonStringToken(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveByCredentials'); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->never(); $request = Request::create('/', 'GET', ['api_token' => [0]]); $guard = $this->createGuard($provider, $request); @@ -81,10 +84,10 @@ public function testUserCannotBeRetrievedWithNonStringToken(): void public function testUserCanBeRetrievedByAuthHeaders(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns($user); $request = Request::create('/', 'GET', [], [], [], ['PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'foo']); $guard = $this->createGuard($provider, $request); @@ -96,10 +99,10 @@ public function testUserCanBeRetrievedByAuthHeaders(): void public function testUserCanBeRetrievedByBearerToken(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns($user); $request = Request::create('/', 'GET', [], [], [], ['HTTP_AUTHORIZATION' => 'Bearer foo']); $guard = $this->createGuard($provider, $request); @@ -111,10 +114,10 @@ public function testUserCanBeRetrievedByBearerToken(): void public function testValidateCanDetermineIfCredentialsAreValid(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns($user); $request = Request::create('/', 'GET', ['api_token' => 'foo']); $guard = $this->createGuard($provider, $request); @@ -126,13 +129,12 @@ public function testValidateCanDetermineIfCredentialsAreValid(): void #[TestWith(['provided_token', 'stored_token', 'plain-token'])] public function testValidateHashesTokenWhenHashingIsEnabled(string $inputKey, string $storageKey, string $token): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->shouldReceive('retrieveByCredentials') - ->once() + $provider->expects('retrieveByCredentials') ->with([$storageKey => hash('sha256', $token)]) - ->andReturn($user); + ->returns($user); $guard = $this->createGuard( $provider, @@ -147,8 +149,8 @@ public function testValidateHashesTokenWhenHashingIsEnabled(string $inputKey, st public function testValidateCanDetermineIfCredentialsAreInvalid(): void { - $provider = m::mock(UserProvider::class); - $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->andReturn(null); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns(null); $request = Request::create('/', 'GET', ['api_token' => 'foo']); $guard = $this->createGuard($provider, $request); @@ -158,8 +160,8 @@ public function testValidateCanDetermineIfCredentialsAreInvalid(): void public function testValidateRejectsMissingToken(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveByCredentials'); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->never(); $guard = $this->createGuard($provider, Request::create('/')); @@ -168,11 +170,10 @@ public function testValidateRejectsMissingToken(): void public function testValidatePreservesStringZero(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials') - ->once() + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials') ->with(['api_token' => '0']) - ->andReturn(new AuthTokenGuardTestUser); + ->returns(new AuthTokenGuardTestUser); $guard = $this->createGuard($provider, Request::create('/')); @@ -181,8 +182,8 @@ public function testValidatePreservesStringZero(): void public function testValidateIfApiTokenIsEmpty(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveByCredentials'); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->never(); $request = Request::create('/', 'GET', ['api_token' => '']); $guard = $this->createGuard($provider, $request); @@ -192,8 +193,8 @@ public function testValidateIfApiTokenIsEmpty(): void public function testValidateRejectsNonStringToken(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveByCredentials'); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->never(); $request = Request::create('/'); $guard = $this->createGuard($provider, $request); @@ -203,10 +204,10 @@ public function testValidateRejectsNonStringToken(): void public function testItAllowsToPassCustomRequestViaContainerAndUseItForValidation(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['api_token' => 'custom'])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['api_token' => 'custom'])->returns($user); $request = Request::create('/', 'GET', ['api_token' => 'foo']); $guard = $this->createGuard($provider, $request); @@ -221,10 +222,10 @@ public function testItAllowsToPassCustomRequestViaContainerAndUseItForValidation public function testUserCanBeRetrievedByBearerTokenWithCustomKey(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns($user); $request = Request::create('/', 'GET', [], [], [], ['HTTP_AUTHORIZATION' => 'Bearer foo']); $guard = $this->createGuard($provider, $request, 'custom_token_field', 'custom_token_field'); @@ -236,10 +237,10 @@ public function testUserCanBeRetrievedByBearerTokenWithCustomKey(): void public function testUserCanBeRetrievedByQueryStringVariableWithCustomKey(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns($user); $request = Request::create('/', 'GET', ['custom_token_field' => 'foo']); $guard = $this->createGuard($provider, $request, 'custom_token_field', 'custom_token_field'); @@ -254,10 +255,10 @@ public function testUserCanBeRetrievedByQueryStringVariableWithCustomKey(): void public function testUserCanBeRetrievedByAuthHeadersWithCustomField(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns($user); $request = Request::create('/', 'GET', [], [], [], ['PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'foo']); $guard = $this->createGuard($provider, $request, 'custom_token_field', 'custom_token_field'); @@ -269,10 +270,10 @@ public function testUserCanBeRetrievedByAuthHeadersWithCustomField(): void public function testValidateCanDetermineIfCredentialsAreValidWithCustomKey(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->andReturn($user); + $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns($user); $request = Request::create('/', 'GET', ['custom_token_field' => 'foo']); $guard = $this->createGuard($provider, $request, 'custom_token_field', 'custom_token_field'); @@ -282,8 +283,8 @@ public function testValidateCanDetermineIfCredentialsAreValidWithCustomKey(): vo public function testValidateCanDetermineIfCredentialsAreInvalidWithCustomKey(): void { - $provider = m::mock(UserProvider::class); - $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->andReturn(null); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns(null); $request = Request::create('/', 'GET', ['custom_token_field' => 'foo']); $guard = $this->createGuard($provider, $request, 'custom_token_field', 'custom_token_field'); @@ -293,48 +294,53 @@ public function testValidateCanDetermineIfCredentialsAreInvalidWithCustomKey(): public function testValidateIfApiTokenIsEmptyWithCustomKey(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $request = Request::create('/', 'GET', ['custom_token_field' => '']); $guard = $this->createGuard($provider, $request, 'custom_token_field', 'custom_token_field'); $this->assertFalse($guard->validate(['custom_token_field' => ''])); + $provider->unused(); } public function testTokenLookupStopsAfterTheFirstNonEmptyString(): void { - $provider = m::mock(UserProvider::class); - $request = m::mock(Request::class)->makePartial(); - $request->shouldReceive('query')->once()->with('api_token')->andReturn('query-token'); - $request->shouldReceive('input', 'bearerToken', 'getPassword')->never(); + $provider = Double::for(UserProvider::class); + $request = Double::for(new Request, override: true)->passthru(); + $request->expects('query')->with('api_token')->returns('query-token'); + $request->expects('input')->never(); + $request->expects('bearerToken')->never(); + $request->expects('getPassword')->never(); - $guard = $this->createGuard($provider, $request); + $guard = $this->createGuard($provider, $request->instance()); $this->assertSame('query-token', $guard->getTokenForRequest()); } public function testTokenLookupFallsThroughInvalidAndEmptyValues(): void { - $provider = m::mock(UserProvider::class); - $request = m::mock(Request::class)->makePartial(); - $request->shouldReceive('query')->once()->with('api_token')->andReturn(['invalid']); - $request->shouldReceive('input')->once()->with('api_token')->andReturn(''); - $request->shouldReceive('bearerToken')->once()->andReturn('bearer-token'); - $request->shouldNotReceive('getPassword'); + $provider = Double::for(UserProvider::class); + $request = Double::for(new Request, override: true)->passthru(); + $request->expects('query')->with('api_token')->returns(['invalid']); + $request->expects('input')->with('api_token')->returns(''); + $request->expects('bearerToken')->returns('bearer-token'); + $request->expects('getPassword')->never(); - $guard = $this->createGuard($provider, $request); + $guard = $this->createGuard($provider, $request->instance()); $this->assertSame('bearer-token', $guard->getTokenForRequest()); } public function testTokenLookupPreservesStringZero(): void { - $provider = m::mock(UserProvider::class); - $request = m::mock(Request::class)->makePartial(); - $request->shouldReceive('query')->once()->with('api_token')->andReturn('0'); - $request->shouldReceive('input', 'bearerToken', 'getPassword')->never(); + $provider = Double::for(UserProvider::class); + $request = Double::for(new Request, override: true)->passthru(); + $request->expects('query')->with('api_token')->returns('0'); + $request->expects('input')->never(); + $request->expects('bearerToken')->never(); + $request->expects('getPassword')->never(); - $guard = $this->createGuard($provider, $request); + $guard = $this->createGuard($provider, $request->instance()); $this->assertSame('0', $guard->getTokenForRequest()); } @@ -350,15 +356,13 @@ public function testDifferentTokensGetDifferentCachedUsers(): void $user2 = new AuthTokenGuardTestUser; $user2->id = 2; - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials') + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials') ->with(['api_token' => 'token-a']) - ->once() - ->andReturn($user1); - $provider->shouldReceive('retrieveByCredentials') + ->returns($user1); + $provider->expects('retrieveByCredentials') ->with(['api_token' => 'token-b']) - ->once() - ->andReturn($user2); + ->returns($user2); // First request with token-a $request1 = Request::create('/', 'GET', ['api_token' => 'token-a']); @@ -378,9 +382,9 @@ public function testCopiedRequestRechecksTheSameTokenWithoutChangingItsParent(): { $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials')->with(['api_token' => 'token']) - ->twice()->andReturn($user, null); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->with(['api_token' => 'token']) + ->times(2)->returns($user, null); $request = Request::create('/', 'GET', ['api_token' => 'token']); $guard = $this->createGuard($provider, $request); $this->assertSame($user, $guard->user()); @@ -396,7 +400,7 @@ public function testCopiedRequestRechecksTheSameTokenWithoutChangingItsParent(): public function testEmptyTokenUsesDefaultKey(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $request = Request::create('/', 'GET'); $guard = $this->createGuard($provider, $request); @@ -404,6 +408,7 @@ public function testEmptyTokenUsesDefaultKey(): void // hasUser should be false (no token means no user) $this->assertFalse($guard->hasUser()); + $provider->unused(); } public function testSetUserOverridesAnUnrelatedRequestToken(): void @@ -411,8 +416,8 @@ public function testSetUserOverridesAnUnrelatedRequestToken(): void $user = new AuthTokenGuardTestUser; $user->id = 1; - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveByCredentials'); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->never(); $request = Request::create('/', 'GET', ['api_token' => 'my-token']); $guard = $this->createGuard($provider, $request); @@ -430,11 +435,10 @@ public function testForgetUserRestoresNormalTokenAuthentication(): void $tokenUser = new AuthTokenGuardTestUser; $tokenUser->id = 2; - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials') - ->once() + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials') ->with(['api_token' => 'my-token']) - ->andReturn($tokenUser); + ->returns($tokenUser); $request = Request::create('/', 'GET', ['api_token' => 'my-token']); $guard = $this->createGuard($provider, $request); @@ -454,8 +458,8 @@ public function testForgetUserRestoresNormalTokenAuthentication(): void public function testExplicitUsersAreIsolatedByGuard(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveByCredentials'); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->never(); $request = Request::create('/', 'GET', ['api_token' => 'request-token']); RequestContext::set($request); @@ -479,13 +483,13 @@ public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsUsers() $tokenUser->id = 1; $explicitUser = new AuthTokenGuardTestUser; $explicitUser->id = 2; - $previousProvider = m::mock(UserProvider::class); - $previousProvider->expects('retrieveByCredentials')->with(['api_token' => 'request-token'])->andReturn($tokenUser); + $previousProvider = Double::for(UserProvider::class); + $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 = m::mock(UserProvider::class); - $provider->expects('retrieveByCredentials')->with(['api_token' => 'request-token'])->andReturnNull(); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->with(['api_token' => 'request-token'])->returns(null); $guard = new TokenGuard('token', $provider, $this->app); @@ -495,8 +499,8 @@ public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsUsers() public function testExplicitUsersAreIsolatedBetweenCoroutines(): void { - $provider = m::mock(UserProvider::class); - $provider->shouldNotReceive('retrieveByCredentials'); + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials')->never(); $guard = new TokenGuard('token', $provider, $this->app); [$first, $second] = parallel([ @@ -524,7 +528,7 @@ function () use ($guard): int { public function testAuthContextKeysIncludeOnlyDurableExplicitState(): void { - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $guard = $this->createGuard( $provider, Request::create('/', 'GET', ['api_token' => 'request-token']), @@ -540,11 +544,10 @@ public function testChangingRequestTokenChangesWhichCachedUserIsSeen(): void $user1 = new AuthTokenGuardTestUser; $user1->id = 1; - $provider = m::mock(UserProvider::class); - $provider->shouldReceive('retrieveByCredentials') + $provider = Double::for(UserProvider::class); + $provider->expects('retrieveByCredentials') ->with(['api_token' => 'token-a']) - ->once() - ->andReturn($user1); + ->returns($user1); $request1 = Request::create('/', 'GET', ['api_token' => 'token-a']); RequestContext::set($request1); diff --git a/tests/Auth/AuthenticateMiddlewareTest.php b/tests/Auth/AuthenticateMiddlewareTest.php index 6f280ee95..97846fb69 100644 --- a/tests/Auth/AuthenticateMiddlewareTest.php +++ b/tests/Auth/AuthenticateMiddlewareTest.php @@ -16,11 +16,14 @@ use Hypervel\Contracts\Auth\Guard; use Hypervel\Http\Request; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Response; class AuthenticateMiddlewareTest extends TestCase { + use VerifiesDoubles; + protected AuthManager $auth; /** @@ -157,7 +160,7 @@ public function testCustomDriverClosureBoundObjectIsAuthManager(): void $this->auth->extend(__CLASS__, function () use (&$boundTo): Guard { $boundTo = $this; - return m::mock(Guard::class); + return Double::for(Guard::class); }); $this->auth->guard(__CLASS__); @@ -167,7 +170,7 @@ public function testCustomDriverClosureBoundObjectIsAuthManager(): void public function testCustomDriverStatic(): void { - $driver = m::mock(Guard::class); + $driver = Double::for(Guard::class); $this->auth->extend(__CLASS__, static fn (): Guard => $driver); @@ -176,7 +179,7 @@ public function testCustomDriverStatic(): void public function testCustomInvokableDriver(): void { - $driver = m::mock(Guard::class); + $driver = Double::for(Guard::class); $creator = new AuthenticateMiddlewareTestCustomAuthDriver($driver); $this->auth->extend(__CLASS__, $creator(...)); @@ -262,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 ? m::mock(Authenticatable::class) : null; - }, Container::getInstance(), m::mock(EloquentUserProvider::class)); + return $authenticated ? Double::for(Authenticatable::class) : null; + }, Container::getInstance(), Double::for(EloquentUserProvider::class)); } /** diff --git a/tests/Broadcasting/Ably2BroadcasterTest.php b/tests/Broadcasting/Ably2BroadcasterTest.php index 7813d5865..d83e4e326 100644 --- a/tests/Broadcasting/Ably2BroadcasterTest.php +++ b/tests/Broadcasting/Ably2BroadcasterTest.php @@ -11,15 +11,17 @@ use Ably\PubSub\Utils\Crypto; use Hypervel\Broadcasting\Broadcasters\Ably2Broadcaster; use Hypervel\Broadcasting\BroadcastException; -use Hypervel\Contracts\Container\Container; -use Hypervel\Contracts\Routing\BindingRegistrar; +use Hypervel\Container\Container; use Hypervel\Http\Request; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; class Ably2BroadcasterTest extends TestCase { + use VerifiesDoubles; + public Ably2Broadcaster $broadcaster; public PubSubHttpClient $ably; @@ -37,11 +39,10 @@ protected function setUp(): void $this->markTestSkipped(sprintf('%s class is not available.', PubSubHttpClient::class)); } - $this->container = m::mock(Container::class); - $this->container->shouldReceive('bound')->with(BindingRegistrar::class)->andReturnFalse()->byDefault(); - $this->ably = m::mock(PubSubHttpClient::class, ['abcd:efgh']); + $this->container = new Container; + $this->ably = new PubSubHttpClient('abcd:efgh'); - $this->broadcaster = m::mock(Ably2Broadcaster::class, [$this->container, $this->ably])->makePartial(); + $this->broadcaster = Double::for(Ably2Broadcaster::class)->passthru(new Ably2Broadcaster($this->container, $this->ably)); } public function testAuthCallValidAuthenticationResponseWithPrivateChannelWhenCallbackReturnTrue(): void @@ -52,7 +53,7 @@ public function testAuthCallValidAuthenticationResponseWithPrivateChannelWhenCal $this->broadcaster->expects('generateAblySignature') ->with('private-test', 'abcd.1234') - ->andReturn('signature'); + ->returns('signature'); $this->assertSame( ['auth' => 'abcd:signature'], @@ -95,7 +96,7 @@ public function testAuthCallValidAuthenticationResponseWithPresenceChannelWhenCa $this->broadcaster->expects('generateAblySignature') ->with('presence-test', 'abcd.1234', ['user_id' => '42', 'user_info' => $returnData]) - ->andReturn('signature'); + ->returns('signature'); $this->assertSame( [ diff --git a/tests/Broadcasting/AblyBroadcasterTest.php b/tests/Broadcasting/AblyBroadcasterTest.php index f83328978..fd7b06108 100644 --- a/tests/Broadcasting/AblyBroadcasterTest.php +++ b/tests/Broadcasting/AblyBroadcasterTest.php @@ -11,16 +11,20 @@ use Hypervel\Broadcasting\Broadcasters\AblyBroadcaster; use Hypervel\Broadcasting\Broadcasters\Broadcaster; use Hypervel\Broadcasting\BroadcastException; -use Hypervel\Contracts\Container\Container; -use Hypervel\Contracts\Routing\BindingRegistrar; +use Hypervel\Container\Container; +use Hypervel\Contracts\Auth\Authenticatable; use Hypervel\Http\Request; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use JsonException; -use Mockery as m; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; class AblyBroadcasterTest extends TestCase { + use VerifiesDoubles; + protected AblyBroadcaster $broadcaster; protected AblyRest $ably; @@ -38,10 +42,9 @@ protected function setUp(): void $this->markTestSkipped(sprintf('%s class is not available.', AblyRest::class)); } - $this->container = m::mock(Container::class); - $this->container->shouldReceive('bound')->with(BindingRegistrar::class)->andReturnFalse()->byDefault(); - $this->ably = m::mock(AblyRest::class, ['abcd:efg']); - $this->broadcaster = m::mock(AblyBroadcaster::class, [$this->container, $this->ably])->makePartial(); + $this->container = new Container; + $this->ably = new AblyRest('abcd:efg'); + $this->broadcaster = Double::for(AblyBroadcaster::class)->passthru(new AblyBroadcaster($this->container, $this->ably)); } public function testAuthCallValidAuthenticationResponseWithPrivateChannelWhenCallbackReturnTrue(): void @@ -52,7 +55,7 @@ public function testAuthCallValidAuthenticationResponseWithPrivateChannelWhenCal $this->broadcaster->expects('generateAblySignature') ->with('private-test', 'abcd.1234') - ->andReturn('signature'); + ->returns('signature'); $this->assertSame( ['auth' => 'abcd:signature'], @@ -108,7 +111,7 @@ public function testAuthCallValidAuthenticationResponseWithPresenceChannelWhenCa 'abcd.1234', ['user_id' => '42', 'user_info' => $returnData], ) - ->andReturn('signature'); + ->returns('signature'); $this->assertSame( [ @@ -152,14 +155,14 @@ public function testAuthThrowAccessDeniedHttpExceptionWithPresenceChannelWhenReq public function testAuthUsesRewrittenChannelForConfiguredGuardAndOriginalNameForPresenceSignature(): void { $wireChannel = 'presence-application.tenant.orders.5'; - $user = m::mock('User'); - $user->shouldReceive('getAuthIdentifier')->once()->andReturn(42); + $user = Double::for(Authenticatable::class); + $user->expects('getAuthIdentifier')->returns(42); - $request = m::mock(Request::class); - $request->shouldReceive('input')->with('channel_name')->andReturn($wireChannel); - $request->shouldReceive('input')->with('socket_id')->andReturn('abcd.1234'); - $request->shouldReceive('user')->times(3)->with('members')->andReturn($user); - $request->shouldNotReceive('user')->withNoArgs(); + $request = Double::for(Request::class, override: true); + $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); + $request->expects('user')->never()->with(Argument::none()); $calls = 0; Broadcaster::authorizeChannelsUsing(function (Request $request, string $channel) use (&$calls): ?string { @@ -178,14 +181,13 @@ public function testAuthUsesRewrittenChannelForConfiguredGuardAndOriginalNameFor ['guards' => ['members']], ); - $this->broadcaster->shouldReceive('generateAblySignature') - ->once() + $this->broadcaster->expects('generateAblySignature') ->with( $wireChannel, 'abcd.1234', ['user_id' => '42', 'user_info' => ['role' => 'viewer']], ) - ->andReturn('signature'); + ->returns('signature'); $this->assertSame( [ @@ -195,7 +197,7 @@ public function testAuthUsesRewrittenChannelForConfiguredGuardAndOriginalNameFor 'user_info' => ['role' => 'viewer'], ]), ], - $this->broadcaster->auth($request), + $this->broadcaster->auth($request->instance()), ); $this->assertSame(1, $calls); } @@ -233,9 +235,8 @@ public function testPresenceAuthenticationThrowsWhenChannelDataCannotBeEncoded() { $this->expectException(JsonException::class); - $this->broadcaster->shouldReceive('generateAblySignature') - ->once() - ->andReturn('signature'); + $this->broadcaster->expects('generateAblySignature') + ->returns('signature'); $this->broadcaster->validAuthenticationResponse( $this->getMockRequestWithUserForChannel('presence-test'), @@ -313,15 +314,27 @@ protected function createAbly(): AblyRest */ protected function getMockRequestWithUserForChannel(string|array $channel): Request { - $request = m::mock(Request::class); - $request->shouldReceive('input')->with('channel_name')->andReturn($channel); - $request->shouldReceive('input')->with('socket_id')->andReturn('abcd.1234'); - - $user = m::mock('User'); - $user->shouldReceive('getAuthIdentifierForBroadcasting')->andReturn(42); - $user->shouldReceive('getAuthIdentifier')->andReturn(42); - - $request->shouldReceive('user')->andReturn($user); + $request = new Request(['channel_name' => $channel, 'socket_id' => 'abcd.1234']); + + $user = new class { + /** + * Get the user's broadcast identifier. + */ + public function getAuthIdentifierForBroadcasting(): int + { + return 42; + } + + /** + * Get the user's authentication identifier. + */ + public function getAuthIdentifier(): int + { + return 42; + } + }; + + $request->setUserResolver(fn () => $user); return $request; } @@ -331,10 +344,9 @@ protected function getMockRequestWithUserForChannel(string|array $channel): Requ */ protected function getMockRequestWithoutUserForChannel(string $channel): Request { - $request = m::mock(Request::class); - $request->shouldReceive('input')->with('channel_name')->andReturn($channel); + $request = new Request(['channel_name' => $channel]); - $request->expects('user')->andReturn(null); + $request->setUserResolver(fn () => null); return $request; } diff --git a/tests/Broadcasting/BroadcastEventTest.php b/tests/Broadcasting/BroadcastEventTest.php index d30274e23..7ad780cde 100644 --- a/tests/Broadcasting/BroadcastEventTest.php +++ b/tests/Broadcasting/BroadcastEventTest.php @@ -16,11 +16,15 @@ use Hypervel\Queue\Attributes\UniqueFor; use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Throwable; class BroadcastEventTest extends TestCase { + use VerifiesDoubles; + public function testUniqueBroadcastEventReadsUniqueForAttribute(): void { $job = new UniqueBroadcastEvent(new TestBroadcastEventWithUniqueForAttribute); @@ -51,7 +55,7 @@ public function testUniqueBroadcastEventChildPropertyOverridesInheritedAttribute public function testBasicEventBroadcastParameterFormatting(): void { - $broadcaster = m::mock(Broadcaster::class); + $broadcaster = Double::for(Broadcaster::class); $broadcaster->expects('broadcast')->with( ['test-channel'], @@ -59,9 +63,9 @@ public function testBasicEventBroadcastParameterFormatting(): void ['firstName' => 'Taylor', 'lastName' => 'Otwell', 'collection' => ['foo' => 'bar']] ); - $manager = m::mock(BroadcastingFactory::class); + $manager = Double::for(BroadcastingFactory::class); - $manager->expects('connection')->with(null)->andReturn($broadcaster); + $manager->expects('connection')->with(null)->returns($broadcaster); $event = new TestBroadcastEvent; @@ -70,7 +74,7 @@ public function testBasicEventBroadcastParameterFormatting(): void public function testManualParameterSpecification(): void { - $broadcaster = m::mock(Broadcaster::class); + $broadcaster = Double::for(Broadcaster::class); $broadcaster->expects('broadcast')->with( ['test-channel'], @@ -78,9 +82,9 @@ public function testManualParameterSpecification(): void ['name' => 'Taylor', 'socket' => null] ); - $manager = m::mock(BroadcastingFactory::class); + $manager = Double::for(BroadcastingFactory::class); - $manager->expects('connection')->with(null)->andReturn($broadcaster); + $manager->expects('connection')->with(null)->returns($broadcaster); $event = new TestBroadcastEventWithManualData; @@ -100,23 +104,27 @@ public function testUninitializedPublicPropertiesAreOmittedFromThePayload(): voi $payload = get_object_vars($event); $payload['collection'] = ['foo' => 'bar']; - $broadcaster = m::mock(Broadcaster::class); - $broadcaster->expects('broadcast')->with(['test-channel'], $event::class, $payload); - $manager = m::mock(BroadcastingFactory::class); - $manager->expects('connection')->with(null)->andReturn($broadcaster); + $broadcaster = Double::for(Broadcaster::class); + $broadcaster->expects('broadcast')->with( + ['test-channel'], + $event::class, + Argument::satisfies(static fn (array $actual): bool => $actual == $payload), + ); + $manager = Double::for(BroadcastingFactory::class); + $manager->expects('connection')->with(null)->returns($broadcaster); (new BroadcastEvent($event))->handle($manager); } public function testSpecificBroadcasterGiven(): void { - $broadcaster = m::mock(Broadcaster::class); + $broadcaster = Double::for(Broadcaster::class); $broadcaster->expects('broadcast'); - $manager = m::mock(BroadcastingFactory::class); + $manager = Double::for(BroadcastingFactory::class); - $manager->expects('connection')->with('log')->andReturn($broadcaster); + $manager->expects('connection')->with('log')->returns($broadcaster); $event = new TestBroadcastEventWithSpecificBroadcaster; @@ -125,7 +133,7 @@ public function testSpecificBroadcasterGiven(): void public function testSpecificChannelsPerConnection(): void { - $broadcaster = m::mock(Broadcaster::class); + $broadcaster = Double::for(Broadcaster::class); $broadcaster->expects('broadcast')->with( ['first-channel'], @@ -139,10 +147,10 @@ public function testSpecificChannelsPerConnection(): void ['firstName' => 'Taylor'] ); - $manager = m::mock(BroadcastingFactory::class); + $manager = Double::for(BroadcastingFactory::class); - $manager->expects('connection')->with('first_connection')->andReturn($broadcaster); - $manager->expects('connection')->with('second_connection')->andReturn($broadcaster); + $manager->expects('connection')->with('first_connection')->returns($broadcaster); + $manager->expects('connection')->with('second_connection')->returns($broadcaster); $event = new TestBroadcastEventWithChannelsPerConnection; @@ -183,12 +191,12 @@ public function testBroadcastAsUnitEnumResolvesToName(): void public function testSingleStringChannelIsBroadcast(): void { - $broadcaster = m::mock(Broadcaster::class); + $broadcaster = Double::for(Broadcaster::class); $broadcaster->expects('broadcast') - ->with(['test-channel'], TestBroadcastEventWithStringChannel::class, m::type('array')); + ->with(['test-channel'], TestBroadcastEventWithStringChannel::class, Argument::type('array')); - $manager = m::mock(BroadcastingFactory::class); - $manager->expects('connection')->with(null)->andReturn($broadcaster); + $manager = Double::for(BroadcastingFactory::class); + $manager->expects('connection')->with(null)->returns($broadcaster); (new BroadcastEvent(new TestBroadcastEventWithStringChannel))->handle($manager); } @@ -286,15 +294,15 @@ public function testVariadicBackoffIsReadFromTheUnderlyingEvent(): void */ protected function assertEventBroadcastsAs(object $event, string $name): void { - $broadcaster = m::mock(Broadcaster::class); + $broadcaster = Double::for(Broadcaster::class); $broadcaster->expects('broadcast')->with( ['test-channel'], $name, ['firstName' => 'Taylor', 'lastName' => 'Otwell', 'collection' => ['foo' => 'bar']] ); - $manager = m::mock(BroadcastingFactory::class); - $manager->expects('connection')->with(null)->andReturn($broadcaster); + $manager = Double::for(BroadcastingFactory::class); + $manager->expects('connection')->with(null)->returns($broadcaster); (new BroadcastEvent($event))->handle($manager); } diff --git a/tests/Broadcasting/BroadcasterTest.php b/tests/Broadcasting/BroadcasterTest.php index 3c399b4b0..d6fdba234 100644 --- a/tests/Broadcasting/BroadcasterTest.php +++ b/tests/Broadcasting/BroadcasterTest.php @@ -6,20 +6,25 @@ use Exception; use Hypervel\Broadcasting\Broadcasters\Broadcaster; +use Hypervel\Container\Container; use Hypervel\Contracts\Auth\Authenticatable; -use Hypervel\Contracts\Container\Container; +use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Routing\BindingRegistrar; use Hypervel\Database\Eloquent\Model; use Hypervel\Http\Request; use Hypervel\Routing\RouteBinding; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\HttpException; class BroadcasterTest extends TestCase { + use VerifiesDoubles; + protected Container $container; protected FakeBroadcaster $broadcaster; @@ -31,8 +36,7 @@ protected function setUp(): void { parent::setUp(); - $this->container = m::mock(Container::class); - $this->container->shouldReceive('bound')->with(BindingRegistrar::class)->andReturnFalse()->byDefault(); + $this->container = new Container; $this->broadcaster = new FakeBroadcaster($this->container); } @@ -68,12 +72,11 @@ public function testExtractingParametersWhileCheckingForUserAccess(): void $this->assertSame([], $parameters); // Test Explicit Binding... - $binder = m::mock(BindingRegistrar::class); - $binder->expects('getBindingCallback')->times(2)->with('model')->andReturn(function (): string { + $binder = Double::for(BindingRegistrar::class); + $binder->expects('getBindingCallback')->times(2)->with('model')->returns(function (): string { return 'bound'; }); - $this->container->shouldReceive('bound')->with(BindingRegistrar::class)->andReturnTrue(); - $this->container->shouldReceive('make')->with(BindingRegistrar::class)->andReturn($binder); + $this->container->instance(BindingRegistrar::class, $binder); $callback = function (mixed $user, mixed $model): void { }; $parameters = $this->broadcaster->extractAuthParameters('something.{model}', 'something.1', $callback); @@ -93,12 +96,12 @@ public function testCanUseChannelClasses(): void public function testCallableChannelHandlersReceiveTheUserAndBoundModel(callable $handler): void { $user = new DummyUser; - $request = m::mock(Request::class); - $request->expects('user')->withNoArgs()->andReturn($user); + $request = Double::for(Request::class, override: true); + $request->expects('user')->with(Argument::none())->returns($user); $this->broadcaster->channel('orders.{order}', $handler); - $result = $this->broadcaster->verifyAccess($request, 'orders.5'); + $result = $this->broadcaster->verifyAccess($request->instance(), 'orders.5'); $this->assertSame($user, $result['user']); $this->assertInstanceOf(BroadcasterTestEloquentModelStub::class, $result['order']); @@ -119,13 +122,11 @@ public static function callableChannelHandlers(): array public function testModelRouteBinding(): void { - $binder = m::mock(BindingRegistrar::class); + $binder = Double::for(BindingRegistrar::class); $routeModelCallback = RouteBinding::forModel($this->container, BroadcasterTestEloquentModelStub::class); - $binder->expects('getBindingCallback')->times(2)->with('model')->andReturn($routeModelCallback); - $this->container->shouldReceive('bound')->with(BindingRegistrar::class)->andReturnTrue(); - $this->container->shouldReceive('make')->with(BindingRegistrar::class)->andReturn($binder); - $this->container->shouldReceive('make')->with(BroadcasterTestEloquentModelStub::class)->andReturn(new BroadcasterTestEloquentModelStub); + $binder->expects('getBindingCallback')->times(2)->with('model')->returns($routeModelCallback); + $this->container->instance(BindingRegistrar::class, $binder); $callback = function (mixed $user, mixed $model): void { }; $parameters = $this->broadcaster->extractAuthParameters('something.{model}', 'something.1', $callback); @@ -219,15 +220,27 @@ public function testDontRetrieveChannelsOptionsWhenChannelDoesntExists(): void ); } + /** + * Create a request and record the guards used to resolve its user. + */ + protected function requestResolvingUsers(array $users, array &$guards = []): Request + { + $request = new Request; + $request->setUserResolver(function (?string $guard = null) use ($users, &$guards): ?DummyUser { + $guards[] = $guard; + + return $users[$guard ?? ''] ?? null; + }); + + return $request; + } + public function testRetrieveUserWithoutGuard(): void { $this->broadcaster->channel('somechannel', function (): void { }); - $request = m::mock(Request::class); - $request->expects('user') - ->withNoArgs() - ->andReturn(new DummyUser); + $request = $this->requestResolvingUsers(['' => new DummyUser]); $this->assertInstanceOf( DummyUser::class, @@ -240,10 +253,7 @@ public function testRetrieveUserWithOneGuardUsingAStringForSpecifyingGuard(): vo $this->broadcaster->channel('somechannel', function (): void { }, ['guards' => 'myguard']); - $request = m::mock(Request::class); - $request->expects('user') - ->with('myguard') - ->andReturn(new DummyUser); + $request = $this->requestResolvingUsers(['myguard' => new DummyUser]); $this->assertInstanceOf( DummyUser::class, @@ -258,15 +268,8 @@ public function testRetrieveUserWithMultipleGuardsAndRespectGuardsOrder(): void $this->broadcaster->channel('someotherchannel', function (): void { }, ['guards' => ['myguard2', 'myguard1']]); - $request = m::mock(Request::class); - $request->expects('user') - ->with('myguard1') - ->andReturn(null); - $request->expects('user') - ->times(2) - ->with('myguard2') - ->andReturn(new DummyUser) - ->ordered('user'); + $guards = []; + $request = $this->requestResolvingUsers(['myguard1' => null, 'myguard2' => new DummyUser], $guards); $this->assertInstanceOf( DummyUser::class, @@ -277,6 +280,8 @@ public function testRetrieveUserWithMultipleGuardsAndRespectGuardsOrder(): void DummyUser::class, $this->broadcaster->retrieveUser($request, 'someotherchannel') ); + + $this->assertSame(['myguard1', 'myguard2', 'myguard2'], $guards); } public function testRetrieveUserDontUseDefaultGuardWhenOneGuardSpecified(): void @@ -284,14 +289,12 @@ public function testRetrieveUserDontUseDefaultGuardWhenOneGuardSpecified(): void $this->broadcaster->channel('somechannel', function (): void { }, ['guards' => 'myguard']); - $request = m::mock(Request::class); - $request->expects('user') - ->with('myguard') - ->andReturn(null); - $request->shouldNotReceive('user') - ->withNoArgs(); + $guards = []; + $request = $this->requestResolvingUsers(['myguard' => null], $guards); $this->broadcaster->retrieveUser($request, 'somechannel'); + + $this->assertSame(['myguard'], $guards); } public function testRetrieveUserDontUseDefaultGuardWhenMultipleGuardsSpecified(): void @@ -299,17 +302,12 @@ public function testRetrieveUserDontUseDefaultGuardWhenMultipleGuardsSpecified() $this->broadcaster->channel('somechannel', function (): void { }, ['guards' => ['myguard1', 'myguard2']]); - $request = m::mock(Request::class); - $request->expects('user') - ->with('myguard1') - ->andReturn(null); - $request->expects('user') - ->with('myguard2') - ->andReturn(null); - $request->shouldNotReceive('user') - ->withNoArgs(); + $guards = []; + $request = $this->requestResolvingUsers(['myguard1' => null, 'myguard2' => null], $guards); $this->broadcaster->retrieveUser($request, 'somechannel'); + + $this->assertSame(['myguard1', 'myguard2'], $guards); } public function testUserAuthenticationWithValidUser(): void @@ -350,9 +348,9 @@ public function testUserAuthenticationWithoutResolve(): void public function testChannelAuthorizerRewritesTheNameBeforeGuardLookupBindingAndInvocation(): void { - $request = m::mock(Request::class); + $request = Double::for(Request::class, override: true); $user = new DummyUser; - $request->expects('user')->times(2)->with('members')->andReturn($user); + $request->expects('user')->times(2)->with('members')->returns($user); $calls = 0; $receivedUser = null; @@ -379,7 +377,7 @@ function (DummyUser $user, BroadcasterTestEloquentModelStub $order) use (&$recei $this->assertTrue( $this->broadcaster->verifyAccess( - $request, + $request->instance(), 'application.tenant.orders.5', guarded: true, ), @@ -403,7 +401,7 @@ public function testChannelAuthorizerDeniesBeforeTheChannelCallbackRuns(): void }); try { - $this->broadcaster->verifyAccess(m::mock(Request::class), 'orders'); + $this->broadcaster->verifyAccess(new Request, 'orders'); $this->fail('Channel authorization should have been denied.'); } catch (AccessDeniedHttpException) { $this->assertFalse($callbackRan); @@ -412,9 +410,9 @@ public function testChannelAuthorizerDeniesBeforeTheChannelCallbackRuns(): void public function testChannelAuthorizerLeavesUnchangedNamesOnTheNativePath(): void { - $request = m::mock(Request::class); + $request = Double::for(Request::class, override: true); $user = new DummyUser; - $request->expects('user')->withNoArgs()->andReturn($user); + $request->expects('user')->with(Argument::none())->returns($user); Broadcaster::authorizeChannelsUsing( static fn (Request $request, string $channel): string => $channel, @@ -426,13 +424,13 @@ public function testChannelAuthorizerLeavesUnchangedNamesOnTheNativePath(): void && $order === '5', ); - $this->assertTrue($this->broadcaster->verifyAccess($request, 'orders.5')); + $this->assertTrue($this->broadcaster->verifyAccess($request->instance(), 'orders.5')); } public function testChannelAuthorizerIsSingleOwner(): void { - $request = m::mock(Request::class); - $request->expects('user')->withNoArgs()->andReturn(new DummyUser); + $request = Double::for(Request::class, override: true); + $request->expects('user')->with(Argument::none())->returns(new DummyUser); Broadcaster::authorizeChannelsUsing(static fn (Request $request, string $channel): ?string => null); Broadcaster::authorizeChannelsUsing( @@ -441,33 +439,33 @@ public function testChannelAuthorizerIsSingleOwner(): void $this->broadcaster->channel('orders', static fn (): bool => true); - $this->assertTrue($this->broadcaster->verifyAccess($request, 'orders')); + $this->assertTrue($this->broadcaster->verifyAccess($request->instance(), 'orders')); } public function testPassingNullRemovesChannelAuthorizer(): void { - $request = m::mock(Request::class); - $request->expects('user')->withNoArgs()->andReturn(new DummyUser); + $request = Double::for(Request::class, override: true); + $request->expects('user')->with(Argument::none())->returns(new DummyUser); Broadcaster::authorizeChannelsUsing(static fn (Request $request, string $channel): ?string => null); Broadcaster::authorizeChannelsUsing(null); $this->broadcaster->channel('orders', static fn (): bool => true); - $this->assertTrue($this->broadcaster->verifyAccess($request, 'orders')); + $this->assertTrue($this->broadcaster->verifyAccess($request->instance(), 'orders')); } public function testBaseChannelResponsePathPreservesPublicOverrides(): void { - $request = m::mock(Request::class); - $request->expects('user')->withNoArgs()->andReturn(new DummyUser); + $request = Double::for(Request::class, override: true); + $request->expects('user')->with(Argument::none())->returns(new DummyUser); $broadcaster = new PublicResponseOnlyBroadcaster($this->container); $broadcaster->channel('orders', static fn (): array => ['allowed' => true]); $this->assertSame( ['result' => ['allowed' => true]], - $broadcaster->verifyAccess($request, 'orders'), + $broadcaster->verifyAccess($request->instance(), 'orders'), ); } @@ -530,16 +528,16 @@ public function testFlushStateClearsChannelsOptionsFormatterAndAuthorizer(): voi $this->assertSame([], $this->broadcaster->retrieveChannelOptions('orders')); $this->assertSame(['orders'], $this->broadcaster->formatOutgoingChannels(['orders'])); - $request = m::mock(Request::class); - $request->expects('user')->withNoArgs()->andReturn(new DummyUser); + $request = Double::for(Request::class, override: true); + $request->expects('user')->with(Argument::none())->returns(new DummyUser); $this->broadcaster->channel('orders', static fn (): bool => true); - $this->assertTrue($this->broadcaster->verifyAccess($request, 'orders')); + $this->assertTrue($this->broadcaster->verifyAccess($request->instance(), 'orders')); } public function testChannelFormatterIsSharedAcrossBroadcasterInstances(): void { - $broadcasterA = new FakeBroadcaster(m::mock(Container::class)); - $broadcasterB = new FakeBroadcaster(m::mock(Container::class)); + $broadcasterA = new FakeBroadcaster(new Container); + $broadcasterB = new FakeBroadcaster(new Container); $broadcasterA::formatChannelsUsing( static fn (array $channels): array => ['formatted.' . $channels[0]], @@ -582,13 +580,13 @@ public static function channelNameMatchPatternProvider(): array public function testChannelsAreSharedAcrossBroadcasterInstances(): void { // Simulate boot time: register channel on first broadcaster instance - $broadcasterA = new FakeBroadcaster(m::mock(Container::class)); + $broadcasterA = new FakeBroadcaster(new Container); $broadcasterA->channel('App.Models.User.{id}', function (mixed $user, string $id): bool { return (int) $user->id === (int) $id; }); // Simulate auth request time: create a second broadcaster instance - $broadcasterB = new FakeBroadcaster(m::mock(Container::class)); + $broadcasterB = new FakeBroadcaster(new Container); // The second instance should see the channel registered on the first $channels = $broadcasterB->getChannels(); @@ -604,7 +602,7 @@ class FakeBroadcaster extends Broadcaster * Create a new broadcaster instance. */ public function __construct( - protected Container $container + protected ContainerContract $container ) { } diff --git a/tests/Broadcasting/MercureBroadcasterTest.php b/tests/Broadcasting/MercureBroadcasterTest.php index 605c255d5..ed4b1568b 100644 --- a/tests/Broadcasting/MercureBroadcasterTest.php +++ b/tests/Broadcasting/MercureBroadcasterTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Broadcasting; +use ArrayObject; use Hypervel\Broadcasting\Broadcasters\Broadcaster; use Hypervel\Broadcasting\Broadcasters\MercureBroadcaster; use Hypervel\Broadcasting\BroadcastException; @@ -14,14 +15,16 @@ use Hypervel\Http\Request; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Jose\Component\Core\AlgorithmManager; use Jose\Component\Core\JWK; use Jose\Component\Encryption\Algorithm\ContentEncryption\A256GCM; use Jose\Component\Encryption\Algorithm\KeyEncryption\Dir; use Jose\Component\Encryption\JWEDecrypter; use Jose\Component\Encryption\Serializer\CompactSerializer; -use Mockery as m; -use Mockery\MockInterface; use PHPUnit\Framework\Attributes\TestWith; use ReflectionClass; use RuntimeException; @@ -35,18 +38,20 @@ class MercureBroadcasterTest extends TestCase { + use VerifiesDoubles; + public MercureBroadcaster $broadcaster; - public HubInterface&MockInterface $hub; + public HubInterface&DoubleInterface $hub; protected function setUp(): void { parent::setUp(); - $this->hub = m::mock(HubInterface::class); - $this->hub->shouldReceive('getPublicUrl')->andReturn('https://localhost/.well-known/mercure'); - $this->hub->shouldReceive('getCookieName')->andReturn('__Secure-mercure_access_token'); - $this->hub->shouldReceive('getFactory')->andReturn($this->tokenFactory()); + $this->hub = Double::for(HubInterface::class); + $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()); $this->broadcaster = new MercureBroadcaster(new Container, $this->hub); } @@ -82,8 +87,8 @@ public function testConstructingRegistersTheHubsCookieNameAsNeverEncrypted(): vo public function testSettingAHubRegistersItsCookieNameAsNeverEncrypted(): void { - $hub = m::mock(HubInterface::class); - $hub->shouldReceive('getCookieName')->andReturn('custom_mercure_cookie'); + $hub = Double::for(HubInterface::class); + $hub->expects('getCookieName')->returns('custom_mercure_cookie'); $this->broadcaster->setHub($hub); @@ -236,9 +241,27 @@ public function testAuthSetsTheCookieProvidedByTheHub(string $publicUrl, string $this->assertSame('strict', $cookie->getSameSite()); } + /** + * Capture updates published by the broadcaster. + * + * @return ArrayObject + */ + protected function capturePublishedUpdates(): ArrayObject + { + $updates = new ArrayObject; + + $this->hub->allows('publish')->resolves(function (Update $update) use ($updates): string { + $updates[] = $update; + + return 'id'; + }); + + return $updates; + } + public function testBroadcastPublishesOneUnprivatedUpdateWhenEveryChannelIsPublic(): void { - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update): bool { + $this->hub->expects('publish')->with(Argument::satisfies(function (Update $update): bool { $data = json_decode($update->getData(), true); return $update->getTopics() === ['https://laravel.alt/echo/channel/news', 'https://laravel.alt/echo/channel/weather'] @@ -251,22 +274,24 @@ public function testBroadcastPublishesOneUnprivatedUpdateWhenEveryChannelIsPubli public function testBroadcastPublishesOnePrivateUpdatePerGuardedChannel(): void { - foreach (['private-room.1', 'presence-room.2'] as $channel) { - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update) use ($channel): bool { - $data = json_decode($update->getData(), true); - - return $update->getTopics() === ['https://laravel.alt/echo/channel/' . $channel] - && $update->isPrivate() - && $data['channels'] === [$channel]; - })); - } + $updates = $this->capturePublishedUpdates(); $this->broadcaster->broadcast(['private-room.1', 'presence-room.2'], 'MessageSent', []); + + $this->assertCount(2, $updates); + + foreach (['private-room.1', 'presence-room.2'] as $index => $channel) { + $data = json_decode($updates[$index]->getData(), true); + + $this->assertSame(['https://laravel.alt/echo/channel/' . $channel], $updates[$index]->getTopics()); + $this->assertTrue($updates[$index]->isPrivate()); + $this->assertSame([$channel], $data['channels']); + } } public function testBroadcastStripsTheSocketKeyFromThePayloadAndEmbedsItInTheEnvelope(): void { - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update): bool { + $this->hub->expects('publish')->with(Argument::satisfies(function (Update $update): bool { $data = json_decode($update->getData(), true); return $data['socket'] === 'abcd.1234' && $data['payload'] === ['text' => 'hi']; @@ -277,7 +302,7 @@ public function testBroadcastStripsTheSocketKeyFromThePayloadAndEmbedsItInTheEnv public function testBroadcastOmitsTheSocketKeyFromTheEnvelopeWhenAbsent(): void { - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update): bool { + $this->hub->expects('publish')->with(Argument::satisfies(function (Update $update): bool { return ! array_key_exists('socket', json_decode($update->getData(), true)); })); @@ -286,20 +311,20 @@ public function testBroadcastOmitsTheSocketKeyFromTheEnvelopeWhenAbsent(): void public function testBroadcastSplitsAMixedBatchIntoTwoUpdates(): void { - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update): bool { - return $update->getTopics() === ['https://laravel.alt/echo/channel/news'] && ! $update->isPrivate(); - })); - - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update): bool { - return $update->getTopics() === ['https://laravel.alt/echo/channel/private-room.1'] && $update->isPrivate(); - })); + $updates = $this->capturePublishedUpdates(); $this->broadcaster->broadcast(['news', 'private-room.1'], 'MessageSent', ['text' => 'hi']); + + $this->assertCount(2, $updates); + $this->assertSame(['https://laravel.alt/echo/channel/news'], $updates[0]->getTopics()); + $this->assertFalse($updates[0]->isPrivate()); + $this->assertSame(['https://laravel.alt/echo/channel/private-room.1'], $updates[1]->getTopics()); + $this->assertTrue($updates[1]->isPrivate()); } public function testTopicsEncodeChannelNamesIntoASinglePathSegment(): void { - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update): bool { + $this->hub->expects('publish')->with(Argument::satisfies(function (Update $update): bool { return $update->getTopics() === ['https://laravel.alt/echo/channel/order%2F1%20%2A%27%28%29%21']; })); @@ -310,7 +335,7 @@ public function testBroadcastWrapsHubExceptionsIntoABroadcastException(): void { $this->expectException(BroadcastException::class); - $this->hub->shouldReceive('publish')->andThrow( + $this->hub->expects('publish')->throws( new MercureRuntimeException('unreachable') ); @@ -325,7 +350,7 @@ public function testBroadcastSurfacesTheUnderlyingCauseAndChainsTheHubException( new RuntimeException('HTTP/2 401 from the hub') ); - $this->hub->shouldReceive('publish')->andThrow($hubException); + $this->hub->expects('publish')->throws($hubException); try { $this->broadcaster->broadcast(['news'], 'Tick'); @@ -340,7 +365,7 @@ public function testBroadcastWrapsBuiltInHubRuntimeExceptionsIntoABroadcastExcep { $hubException = new RuntimeException('No Mercure hub configured'); - $this->hub->shouldReceive('publish')->andThrow($hubException); + $this->hub->expects('publish')->throws($hubException); try { $this->broadcaster->broadcast(['news'], 'Tick'); @@ -539,26 +564,26 @@ public function testBroadcastPublishesOnePrivateUpdatePerEncryptedChannel(): voi { $broadcaster = $this->encryptedBroadcaster(); - $this->hub->shouldReceive('publish')->once()->with(m::on( - static fn (Update $update): bool => $update->getTopics() === ['https://laravel.alt/echo/channel/news'] && ! $update->isPrivate() - )); - $this->hub->shouldReceive('publish')->once()->with(m::on( - static fn (Update $update): bool => $update->getTopics() === ['https://laravel.alt/echo/channel/private-room.1'] && $update->isPrivate() - )); + $updates = $this->capturePublishedUpdates(); - foreach (['private-encrypted-a', 'private-encrypted-b'] as $channel) { - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update) use ($channel): bool { - $data = json_decode($update->getData(), true); + $broadcaster->broadcast(['news', 'private-room.1', 'private-encrypted-a', 'private-encrypted-b'], 'MessageSent', ['text' => 'hi']); - return $update->getTopics() === ['https://laravel.alt/echo/channel/' . $channel] - && $update->isPrivate() - && array_keys($data) === ['channels', 'data'] - && $data['channels'] === [$channel] - && count(explode('.', $data['data'])) === 5; - })); - } + $this->assertCount(4, $updates); + $this->assertSame(['https://laravel.alt/echo/channel/news'], $updates[0]->getTopics()); + $this->assertFalse($updates[0]->isPrivate()); + $this->assertSame(['https://laravel.alt/echo/channel/private-room.1'], $updates[1]->getTopics()); + $this->assertTrue($updates[1]->isPrivate()); - $broadcaster->broadcast(['news', 'private-room.1', 'private-encrypted-a', 'private-encrypted-b'], 'MessageSent', ['text' => 'hi']); + foreach (['private-encrypted-a', 'private-encrypted-b'] as $index => $channel) { + $update = $updates[$index + 2]; + $data = json_decode($update->getData(), true); + + $this->assertSame(['https://laravel.alt/echo/channel/' . $channel], $update->getTopics()); + $this->assertTrue($update->isPrivate()); + $this->assertSame(['channels', 'data'], array_keys($data)); + $this->assertSame([$channel], $data['channels']); + $this->assertCount(5, explode('.', $data['data'])); + } } public function testBroadcastEncryptedUpdateRoundTrips(): void @@ -566,7 +591,7 @@ public function testBroadcastEncryptedUpdateRoundTrips(): void $broadcaster = $this->encryptedBroadcaster(); $captured = null; - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update) use (&$captured): bool { + $this->hub->expects('publish')->with(Argument::satisfies(function (Update $update) use (&$captured): bool { $captured = $update; return true; @@ -590,7 +615,7 @@ public function testBroadcastEncryptedChannelsUseDistinctKeys(): void $broadcaster = $this->encryptedBroadcaster(); $captured = null; - $this->hub->shouldReceive('publish')->once()->with(m::on(function (Update $update) use (&$captured): bool { + $this->hub->expects('publish')->with(Argument::satisfies(function (Update $update) use (&$captured): bool { $captured = $update; return true; @@ -708,7 +733,7 @@ public function testAuthAndBroadcastHonorACustomTopicPrefix(): void $this->assertSame([['match' => 'https://app.example.com/broadcasting/channel/private-room.1']], $details[0]['topics']); $this->assertSame([['match' => 'https://app.example.com/broadcasting/whisper/private-room.1']], $details[1]['topics']); - $this->hub->shouldReceive('publish')->once()->with(m::on( + $this->hub->expects('publish')->with(Argument::satisfies( static fn (Update $update): bool => $update->getTopics() === ['https://app.example.com/broadcasting/channel/news'] )); @@ -720,10 +745,10 @@ public function testAuthAndBroadcastHonorACustomTopicPrefix(): void */ protected function broadcasterForHub(string $publicUrl, string $cookieName = '__Secure-mercure_access_token'): MercureBroadcaster { - $hub = m::mock(HubInterface::class); - $hub->shouldReceive('getPublicUrl')->andReturn($publicUrl); - $hub->shouldReceive('getCookieName')->andReturn($cookieName); - $hub->shouldReceive('getFactory')->andReturn($this->tokenFactory()); + $hub = Double::for(HubInterface::class); + $hub->allows('getPublicUrl')->returns($publicUrl); + $hub->allows('getCookieName')->returns($cookieName); + $hub->allows('getFactory')->returns($this->tokenFactory()); return new MercureBroadcaster(new Container, $hub); } diff --git a/tests/Broadcasting/PusherBroadcasterTest.php b/tests/Broadcasting/PusherBroadcasterTest.php index 44b98fbea..372e5709d 100644 --- a/tests/Broadcasting/PusherBroadcasterTest.php +++ b/tests/Broadcasting/PusherBroadcasterTest.php @@ -7,8 +7,8 @@ use Hypervel\Broadcasting\Broadcasters\Broadcaster; use Hypervel\Broadcasting\Broadcasters\PusherBroadcaster; use Hypervel\Container\Container as ApplicationContainer; +use Hypervel\Contracts\Auth\Authenticatable; use Hypervel\Contracts\Container\Container; -use Hypervel\Contracts\Routing\BindingRegistrar; use Hypervel\Contracts\Routing\ResponseFactory as ResponseFactoryContract; use Hypervel\Contracts\View\Factory as ViewFactory; use Hypervel\Database\Eloquent\Model; @@ -17,13 +17,16 @@ use Hypervel\Routing\Redirector; use Hypervel\Routing\ResponseFactory; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Pusher\Pusher; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; class PusherBroadcasterTest extends TestCase { + use VerifiesDoubles; + protected Container $container; protected PusherBroadcaster $broadcaster; @@ -37,10 +40,9 @@ protected function setUp(): void { parent::setUp(); - $this->container = m::mock(Container::class); - $this->container->shouldReceive('bound')->with(BindingRegistrar::class)->andReturnFalse()->byDefault(); - $this->pusher = m::mock(Pusher::class); - $this->broadcaster = m::mock(PusherBroadcaster::class, [$this->container, $this->pusher])->makePartial(); + $this->container = new ApplicationContainer; + $this->pusher = Double::for(Pusher::class); + $this->broadcaster = new PusherBroadcaster($this->container, $this->pusher); } public function testAuthCallValidAuthenticationResponseWithPrivateChannelWhenCallbackReturnTrue(): void @@ -49,11 +51,14 @@ public function testAuthCallValidAuthenticationResponseWithPrivateChannelWhenCal return true; }); + $data = ['auth' => 'abcd:efgh']; + $this->pusher->expects('authorizeChannel') - ->andReturn(json_encode(['auth' => 'signed'])); + ->with('private-test', 'abcd.1234') + ->returns(json_encode($data)); $this->assertSame( - ['auth' => 'signed'], + $data, $this->broadcaster->auth( $this->getMockRequestWithUserForChannel('private-test') ), @@ -102,11 +107,14 @@ public function testAuthCallValidAuthenticationResponseWithPresenceChannelWhenCa return $returnData; }); + $data = ['auth' => 'abcd:efgh', 'channel_data' => ['user_id' => 42, 'user_info' => $returnData]]; + $this->pusher->expects('authorizePresenceChannel') - ->andReturn(json_encode(['auth' => 'signed'])); + ->with('presence-test', 'abcd.1234', '42', $returnData) + ->returns(json_encode($data)); $this->assertSame( - ['auth' => 'signed'], + $data, $this->broadcaster->auth( $this->getMockRequestWithUserForChannel('presence-test') ), @@ -143,15 +151,15 @@ public function testAuthUsesRewrittenChannelForConfiguredGuardAndOriginalNameFor $wireChannel = 'presence-application.tenant.orders.5'; $calls = 0; $boundOrder = null; - $user = m::mock('User'); - $user->expects('getAuthIdentifier')->andReturn(42); + $user = Double::for(Authenticatable::class); + $user->expects('getAuthIdentifier')->returns(42); - $request = m::mock(Request::class); - $request->shouldReceive('input')->with('channel_name')->andReturn($wireChannel); - $request->shouldReceive('input')->with('socket_id')->andReturn('abcd.1234'); - $request->shouldReceive('input')->with('callback', false)->andReturn(false); - $request->expects('user')->times(3)->with('members')->andReturn($user); - $request->shouldNotReceive('user')->withNoArgs(); + $request = Double::for(Request::class, override: true); + $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); + $request->expects('user')->times(3)->with('members')->returns($user); + $request->expects('user')->never()->with(Argument::none()); Broadcaster::authorizeChannelsUsing(function (Request $request, string $channel) use (&$calls): ?string { ++$calls; @@ -173,11 +181,11 @@ function (object $authenticatedUser, PusherBroadcasterTestEloquentModelStub $ord $this->pusher->expects('authorizePresenceChannel') ->with($wireChannel, 'abcd.1234', '42', ['role' => 'viewer']) - ->andReturn(json_encode(['auth' => 'signed'])); + ->returns(json_encode(['auth' => 'signed'])); $this->assertSame( ['auth' => 'signed'], - $this->broadcaster->auth($request), + $this->broadcaster->auth($request->instance()), ); $this->assertSame(1, $calls); $this->assertInstanceOf(PusherBroadcasterTestEloquentModelStub::class, $boundOrder); @@ -186,9 +194,9 @@ function (object $authenticatedUser, PusherBroadcasterTestEloquentModelStub $ord public function testBroadcastTriggersEncryptedChannelsSeparately(): void { - $this->pusher->expects('trigger')->with(['private-a', 'b'], 'event', ['foo' => 'bar'], []); - $this->pusher->expects('trigger')->with(['private-encrypted-c'], 'event', ['foo' => 'bar'], []); - $this->pusher->expects('trigger')->with(['private-encrypted-d'], 'event', ['foo' => 'bar'], []); + $this->pusher->expects('trigger')->with(['private-a', 'b'], 'event', ['foo' => 'bar'], [])->returns((object) []); + $this->pusher->expects('trigger')->with(['private-encrypted-c'], 'event', ['foo' => 'bar'], [])->returns((object) []); + $this->pusher->expects('trigger')->with(['private-encrypted-d'], 'event', ['foo' => 'bar'], [])->returns((object) []); $this->broadcaster->broadcast( ['private-a', 'private-encrypted-c', 'b', 'private-encrypted-d'], @@ -206,7 +214,7 @@ public function testValidAuthenticationResponseCallPusherSocketAuthMethodWithPri ]; $this->pusher->expects('authorizeChannel') - ->andReturn(json_encode($data)); + ->returns(json_encode($data)); $this->assertEquals( $data, @@ -227,7 +235,7 @@ public function testValidAuthenticationResponseCallPusherPresenceAuthMethodWithP ]; $this->pusher->expects('authorizePresenceChannel') - ->andReturn(json_encode($data)); + ->returns(json_encode($data)); $this->assertEquals( $data, @@ -269,23 +277,20 @@ public function testBroadcastUsesFormattedChannelNames(): void ); $this->pusher->expects('trigger') - ->with(['application.orders'], 'OrderCreated', ['id' => 1], []); + ->with(['application.orders'], 'OrderCreated', ['id' => 1], [])->returns((object) []); $this->broadcaster->broadcast(['orders'], 'OrderCreated', ['id' => 1]); } public function testJsonpCallbackReturnsJsonWithoutExplicitOptIn(): void { - $request = m::mock(Request::class); - $request->shouldReceive('input')->with('channel_name')->andReturn('private-test'); - $request->shouldReceive('input')->with('socket_id')->andReturn('abcd.1234'); - $request->shouldReceive('input')->with('callback', false)->andReturn('myCallback'); - $request->shouldReceive('user')->andReturn(m::mock('User')); + $request = $this->getMockRequestWithUserForChannel('private-test'); + $request->request->set('callback', 'myCallback'); $data = ['auth' => 'abcd:efgh']; $this->pusher->expects('authorizeChannel') - ->andReturn(json_encode($data)); + ->returns(json_encode($data)); $response = $this->broadcaster->validAuthenticationResponse($request, true); @@ -298,27 +303,20 @@ public function testJsonpCallbackReturnsJsonpWhenExplicitlyEnabled(): void $container->singleton( ResponseFactoryContract::class, fn (): ResponseFactory => new ResponseFactory( - m::mock(ViewFactory::class), - m::mock(Redirector::class), + Double::for(ViewFactory::class), + Double::for(Redirector::class), ) ); - $request = m::mock(Request::class); - $request->shouldReceive('input')->with('channel_name')->andReturn('private-test'); - $request->shouldReceive('input')->with('socket_id')->andReturn('abcd.1234'); - $request->shouldReceive('input')->with('callback', false)->andReturn('myCallback'); - $request->shouldReceive('input')->with('callback')->andReturn('myCallback'); - $request->shouldReceive('user')->andReturn(m::mock('User')); + $request = $this->getMockRequestWithUserForChannel('private-test'); + $request->request->set('callback', 'myCallback'); $data = ['auth' => 'abcd:efgh']; $this->pusher->expects('authorizeChannel') - ->andReturn(json_encode($data)); + ->returns(json_encode($data)); - $broadcaster = m::mock( - PusherBroadcaster::class, - [$this->container, $this->pusher, true], - )->makePartial(); + $broadcaster = new PusherBroadcaster($this->container, $this->pusher, true); $response = $broadcaster->validAuthenticationResponse($request, true); @@ -335,12 +333,9 @@ public function testExplicitJsonpOptInWithoutCallbackReturnsJson(): void $data = ['auth' => 'abcd:efgh']; $this->pusher->expects('authorizeChannel') - ->andReturn(json_encode($data)); + ->returns(json_encode($data)); - $broadcaster = m::mock( - PusherBroadcaster::class, - [$this->container, $this->pusher, true], - )->makePartial(); + $broadcaster = new PusherBroadcaster($this->container, $this->pusher, true); $this->assertSame( $data, @@ -355,11 +350,25 @@ protected function getMockRequestWithUserForChannel(string|array $channel): Requ { $request = Request::create('/', 'POST', ['channel_name' => $channel, 'socket_id' => 'abcd.1234']); - $user = m::mock('User'); - $user->shouldReceive('getAuthIdentifierForBroadcasting')->andReturn(42); - $user->shouldReceive('getAuthIdentifier')->andReturn(42); - - $request->setUserResolver(fn (): MockInterface => $user); + $user = new class { + /** + * Get the user's broadcast identifier. + */ + public function getAuthIdentifierForBroadcasting(): int + { + return 42; + } + + /** + * Get the user's authentication identifier. + */ + public function getAuthIdentifier(): int + { + return 42; + } + }; + + $request->setUserResolver(fn () => $user); return $request; } diff --git a/tests/Broadcasting/RedisBroadcasterTest.php b/tests/Broadcasting/RedisBroadcasterTest.php index 33738e64d..f3b4ba758 100644 --- a/tests/Broadcasting/RedisBroadcasterTest.php +++ b/tests/Broadcasting/RedisBroadcasterTest.php @@ -7,25 +7,29 @@ use Hypervel\Broadcasting\Broadcasters\Broadcaster; use Hypervel\Broadcasting\Broadcasters\RedisBroadcaster; use Hypervel\Broadcasting\BroadcastException; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; +use Hypervel\Contracts\Auth\Authenticatable; use Hypervel\Contracts\Redis\Factory as Redis; -use Hypervel\Contracts\Routing\BindingRegistrar; use Hypervel\Http\Request; use Hypervel\Redis\RedisProxy; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use JsonException; -use Mockery as m; -use Mockery\MockInterface; use RedisClusterException; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; class RedisBroadcasterTest extends TestCase { + use VerifiesDoubles; + protected RedisBroadcaster $broadcaster; protected Container $container; - protected Redis&MockInterface $redis; + protected Redis&DoubleInterface $redis; /** * Set up the test environment. @@ -34,10 +38,9 @@ protected function setUp(): void { parent::setUp(); - $this->container = m::mock(Container::class); - $this->container->shouldReceive('bound')->with(BindingRegistrar::class)->andReturnFalse()->byDefault(); - $this->redis = m::mock(Redis::class); - $this->broadcaster = m::mock(RedisBroadcaster::class, [$this->container, $this->redis])->makePartial(); + $this->container = new Container; + $this->redis = Double::for(Redis::class); + $this->broadcaster = new RedisBroadcaster($this->container, $this->redis); } public function testAuthCallValidAuthenticationResponseWithPrivateChannelWhenCallbackReturnTrue(): void @@ -58,8 +61,7 @@ public function testAuthRejectsMissingChannelName(): void { $this->expectException(AccessDeniedHttpException::class); - $request = m::mock(Request::class); - $request->shouldReceive('input')->with('channel_name')->andReturn(null); + $request = new Request; $this->broadcaster->auth($request); } @@ -144,19 +146,16 @@ public function testAuthThrowAccessDeniedHttpExceptionWithPresenceChannelWhenReq public function testAuthUsesRewrittenChannelForConfiguredGuardAndPresenceUser(): void { - $broadcaster = m::mock( - RedisBroadcaster::class, - [$this->container, $this->redis, 'default', 'redis.'], - )->makePartial(); - $user = m::mock('User'); - $user->expects('getAuthIdentifier')->andReturn(42); - - $request = m::mock(Request::class); - $request->shouldReceive('input') + $broadcaster = new RedisBroadcaster($this->container, $this->redis, 'default', 'redis.'); + $user = Double::for(Authenticatable::class); + $user->expects('getAuthIdentifier')->returns(42); + + $request = Double::for(Request::class, override: true); + $request->allows('input') ->with('channel_name') - ->andReturn('redis.presence-application.tenant.orders.5'); - $request->expects('user')->times(3)->with('members')->andReturn($user); - $request->shouldNotReceive('user')->withNoArgs(); + ->returns('redis.presence-application.tenant.orders.5'); + $request->expects('user')->times(3)->with('members')->returns($user); + $request->expects('user')->never()->with(Argument::none()); $calls = 0; Broadcaster::authorizeChannelsUsing(function (Request $request, string $channel) use (&$calls): ?string { @@ -182,17 +181,14 @@ public function testAuthUsesRewrittenChannelForConfiguredGuardAndPresenceUser(): 'user_info' => ['role' => 'viewer'], ], ]), - $broadcaster->auth($request), + $broadcaster->auth($request->instance()), ); $this->assertSame(1, $calls); } public function testAuthDoesNotRemoveConfiguredPrefixFromTheMiddleOfAChannel(): void { - $broadcaster = m::mock( - RedisBroadcaster::class, - [$this->container, $this->redis, 'default', 'redis.'], - )->makePartial(); + $broadcaster = new RedisBroadcaster($this->container, $this->redis, 'default', 'redis.'); $broadcaster->channel('orders.redis.audit', static fn (): bool => true); $this->assertSame( @@ -205,10 +201,7 @@ public function testAuthDoesNotRemoveConfiguredPrefixFromTheMiddleOfAChannel(): public function testAuthLeavesAChannelWithoutTheConfiguredPrefixUnchanged(): void { - $broadcaster = m::mock( - RedisBroadcaster::class, - [$this->container, $this->redis, 'default', 'redis.'], - )->makePartial(); + $broadcaster = new RedisBroadcaster($this->container, $this->redis, 'default', 'redis.'); $broadcaster->channel('orders', static fn (): bool => true); $this->assertSame( @@ -262,13 +255,13 @@ public function testPresenceAuthenticationThrowsWhenUserDataCannotBeEncoded(): v public function testBroadcastUsesPublishPerChannelOnCluster(): void { - $connection = m::mock(RedisProxy::class); - $connection->expects('isCluster')->andReturnTrue(); - $connection->expects('publish')->with('test-channel-1', m::type('string')); - $connection->expects('publish')->with('test-channel-2', m::type('string')); - $connection->shouldNotReceive('eval'); + $connection = Double::for(RedisBroadcasterTestConnection::class); + $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')); + $connection->expects('eval')->never(); - $this->redis->expects('connection')->andReturn($connection); + $this->redis->expects('connection')->returns($connection); $broadcaster = new RedisBroadcaster($this->container, $this->redis); $broadcaster->broadcast(['test-channel-1', 'test-channel-2'], 'test-event', ['data' => 'value']); @@ -276,13 +269,13 @@ public function testBroadcastUsesPublishPerChannelOnCluster(): void public function testClusterBroadcastWrapsRedisClusterException(): void { - $connection = m::mock(RedisProxy::class); - $connection->expects('isCluster')->andReturnTrue(); + $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection->expects('isCluster')->returns(true); $connection->expects('publish') - ->with('test-channel', m::type('string')) - ->andThrow(new RedisClusterException('Cluster unavailable')); + ->with('test-channel', Argument::type('string')) + ->throws(new RedisClusterException('Cluster unavailable')); - $this->redis->expects('connection')->andReturn($connection); + $this->redis->expects('connection')->returns($connection); $this->expectException(BroadcastException::class); $this->expectExceptionMessageIs('Redis error: Cluster unavailable.'); @@ -293,12 +286,12 @@ public function testClusterBroadcastWrapsRedisClusterException(): void public function testBroadcastUsesEvalOnNonCluster(): void { - $connection = m::mock(RedisProxy::class); - $connection->expects('isCluster')->andReturnFalse(); + $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection->expects('isCluster')->returns(false); $connection->expects('eval'); - $connection->shouldNotReceive('publish'); + $connection->expects('publish')->never(); - $this->redis->expects('connection')->andReturn($connection); + $this->redis->expects('connection')->returns($connection); $broadcaster = new RedisBroadcaster($this->container, $this->redis); $broadcaster->broadcast(['test-channel'], 'test-event', ['data' => 'value']); @@ -313,12 +306,12 @@ public function testClusterBroadcastLeavesRedisPrefixToNativePublishAfterFormatt ), ); - $connection = m::mock(RedisProxy::class); - $connection->expects('isCluster')->andReturnTrue(); + $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection->expects('isCluster')->returns(true); $connection->expects('publish') - ->with('application.orders', m::type('string')); + ->with('application.orders', Argument::type('string')); - $this->redis->expects('connection')->andReturn($connection); + $this->redis->expects('connection')->returns($connection); (new RedisBroadcaster( $this->container, @@ -336,17 +329,17 @@ public function testLuaBroadcastAddsRedisPrefixAfterFormattingChannels(): void ), ); - $connection = m::mock(RedisProxy::class); - $connection->expects('isCluster')->andReturnFalse(); + $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection->expects('isCluster')->returns(false); $connection->expects('eval') ->with( - m::type('string'), + Argument::type('string'), 0, - m::type('string'), + Argument::type('string'), 'redis.application.orders', ); - $this->redis->expects('connection')->andReturn($connection); + $this->redis->expects('connection')->returns($connection); (new RedisBroadcaster( $this->container, @@ -359,8 +352,8 @@ public function testBroadcastThrowsWhenPayloadCannotBeEncoded(): void { $this->expectException(JsonException::class); - $this->redis->expects('connection')->andReturn( - m::mock(RedisProxy::class) + $this->redis->expects('connection')->returns( + Double::for(RedisBroadcasterTestConnection::class) ); $this->broadcaster->broadcast( @@ -372,17 +365,17 @@ public function testBroadcastThrowsWhenPayloadCannotBeEncoded(): void public function testBroadcastPayloadDoesNotDuplicateSocketInData(): void { - $connection = m::mock(RedisProxy::class); - $connection->shouldReceive('isCluster')->andReturnFalse(); - $connection->expects('eval')->withArgs(function (string $script, int $numberOfKeys, string $payload): bool { + $connection = Double::for(RedisBroadcasterTestConnection::class); + $connection->allows('isCluster')->returns(false); + $connection->expects('eval')->with(Argument::all(function (string $script, int $numberOfKeys, string $payload): bool { $decoded = json_decode($payload, true); // socket should be at top level only, not inside data return $decoded['socket'] === 'test-socket' && ! isset($decoded['data']['socket']); - }); + })); - $this->redis->shouldReceive('connection')->andReturn($connection); + $this->redis->allows('connection')->returns($connection); $broadcaster = new RedisBroadcaster($this->container, $this->redis); $broadcaster->broadcast(['test-channel'], 'test-event', ['message' => 'hello', 'socket' => 'test-socket']); @@ -395,11 +388,25 @@ protected function getMockRequestWithUserForChannel(string|array $channel): Requ { $request = Request::create('/', 'POST', ['channel_name' => $channel]); - $user = m::mock('User'); - $user->shouldReceive('getAuthIdentifierForBroadcasting')->andReturn(42); - $user->shouldReceive('getAuthIdentifier')->andReturn(42); - - $request->setUserResolver(fn (): MockInterface => $user); + $user = new class { + /** + * Get the user's broadcast identifier. + */ + public function getAuthIdentifierForBroadcasting(): int + { + return 42; + } + + /** + * Get the user's authentication identifier. + */ + public function getAuthIdentifier(): int + { + return 42; + } + }; + + $request->setUserResolver(fn () => $user); return $request; } @@ -412,3 +419,17 @@ protected function getMockRequestWithoutUserForChannel(string $channel): Request return Request::create('/', 'POST', ['channel_name' => $channel]); } } + +// Declare the proxy's dynamic commands so Double can reflect their signatures. +abstract class RedisBroadcasterTestConnection extends RedisProxy +{ + /** + * Publish a message to a channel. + */ + abstract public function publish(string $channel, string $message): int|false; + + /** + * Evaluate a Lua script. + */ + abstract public function eval(string $script, int $numberOfKeys, mixed ...$arguments): mixed; +} diff --git a/tests/Bus/BusBatchTest.php b/tests/Bus/BusBatchTest.php index 5a79f604c..23afbe8f4 100644 --- a/tests/Bus/BusBatchTest.php +++ b/tests/Bus/BusBatchTest.php @@ -36,7 +36,9 @@ use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -46,6 +48,7 @@ class BusBatchTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected bool $migrateRefresh = true; @@ -116,7 +119,7 @@ public function testBatchRepositoryUsesDefaultDatabaseConnectionWhenBatchingData public function testBatchRepositoryAppliesAZeroBeforeCursor(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $batch = $this->createTestBatch($queue); $repository = new DatabaseBatchRepository( @@ -131,7 +134,7 @@ public function testBatchRepositoryAppliesAZeroBeforeCursor(): void public function testJobsCanBeAddedToTheBatch(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $batch = $this->createTestBatch($queue); @@ -146,12 +149,12 @@ public function testJobsCanBeAddedToTheBatch(): void $thirdJob = function (): void { }; - $connection = m::mock(QueueContract::class); + $connection = Double::for(QueueContract::class); $queue->expects('connection') ->with('test-connection') - ->andReturn($connection); + ->returns($connection); - $connection->expects('bulk')->with(m::on(function (array $jobs) use ($job, $secondJob, $thirdJob): bool { + $connection->expects('bulk')->with(Argument::satisfies(function (array $jobs) use ($job, $secondJob, $thirdJob): bool { return count($jobs) === 3 && $jobs[0] === $job @@ -276,19 +279,19 @@ public function testProcessedJobsCanBeCalculated(): void public function testProgressContinuesOnlyAfterOrdinaryCallbackFailures(bool $canceled): void { $failure = new RuntimeException('Progress failed.', previous: $canceled ? new CanceledException : null); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->times($canceled ? 0 : 1)->with($failure, []); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->times($canceled ? 0 : 1)->with(Argument::same($failure), []); $this->app->instance(ExceptionHandler::class, $handler); - $repository = m::mock(BatchRepository::class); + $repository = Double::for(BatchRepository::class); $continued = false; - $batch = new Batch(m::mock(Factory::class), $repository, 'batch', 'batch', 2, 2, 0, [], [ + $batch = new Batch(Double::for(Factory::class), $repository, 'batch', 'batch', 2, 2, 0, [], [ 'progress' => [ static fn () => throw $failure, static function () use (&$continued): void { $continued = true; }, ], ], CarbonImmutable::now()); - $repository->shouldReceive('find')->with('batch')->andReturn($batch); - $repository->shouldReceive('decrementPendingJobs')->once()->andReturn(new UpdatedBatchJobCounts(1)); + $repository->allows('find')->with('batch')->returns($batch); + $repository->expects('decrementPendingJobs')->returns(new UpdatedBatchJobCounts(1)); $caught = null; try { @@ -303,7 +306,7 @@ static function () use (&$continued): void { $continued = true; }, public function testSuccessfulJobsCanBeRecorded(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $batch = $this->createTestBatch($queue); @@ -315,10 +318,10 @@ public function testSuccessfulJobsCanBeRecorded(): void use Batchable; }; - $connection = m::mock(QueueContract::class); + $connection = Double::for(QueueContract::class); $queue->expects('connection') ->with('test-connection') - ->andReturn($connection); + ->returns($connection); $connection->expects('bulk'); @@ -425,7 +428,7 @@ public function testBatchStartedEventIsDispatchedWhenFirstJobFails(): void public function testFailedJobsCanBeRecordedWhileNotAllowingFailures(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $batch = $this->createTestBatch($queue, $allowFailures = false); @@ -437,10 +440,10 @@ public function testFailedJobsCanBeRecordedWhileNotAllowingFailures(): void use Batchable; }; - $connection = m::mock(QueueContract::class); + $connection = Double::for(QueueContract::class); $queue->expects('connection') ->with('test-connection') - ->andReturn($connection); + ->returns($connection); $connection->expects('bulk'); @@ -466,7 +469,7 @@ public function testFailedJobsCanBeRecordedWhileNotAllowingFailures(): void public function testFailedJobsCanBeRecordedWhileAllowingFailures(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $batch = $this->createTestBatch($queue, $allowFailures = true); @@ -478,10 +481,10 @@ public function testFailedJobsCanBeRecordedWhileAllowingFailures(): void use Batchable; }; - $connection = m::mock(QueueContract::class); + $connection = Double::for(QueueContract::class); $queue->expects('connection') ->with('test-connection') - ->andReturn($connection); + ->returns($connection); $connection->expects('bulk'); @@ -525,7 +528,7 @@ public function testPendingBatchFiltersOutFalsyJobs(): void public function testFailureCallbacksExecuteCorrectly(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $repository = new DatabaseBatchRepository( new BatchFactory($queue), @@ -558,10 +561,10 @@ function (Batch $batch, ?Throwable $e): void { use Batchable; }; - $connection = m::mock(QueueContract::class); + $connection = Double::for(QueueContract::class); $queue->expects('connection') ->with('test-connection') - ->andReturn($connection); + ->returns($connection); $connection->expects('bulk'); @@ -632,17 +635,17 @@ public function testBatchCanBeDeleted(): void public function testDeletedBatchIgnoresLateJobResultsAndCallbacks(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $batch = $this->createTestBatch($queue, $allowFailures = true); $job = new class { use Batchable; }; - $connection = m::mock(QueueContract::class); + $connection = Double::for(QueueContract::class); $queue->expects('connection') ->with('test-connection') - ->andReturn($connection); + ->returns($connection); $connection->expects('bulk'); @@ -701,7 +704,7 @@ public function testBatchStateCanBeInspected(): void public function testChainCanBeAddedToBatch(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $batch = $this->createTestBatch($queue); @@ -711,12 +714,12 @@ public function testChainCanBeAddedToBatch(): void $thirdJob = new ThirdTestJob; - $connection = m::mock(QueueContract::class); + $connection = Double::for(QueueContract::class); $queue->expects('connection') ->with('test-connection') - ->andReturn($connection); + ->returns($connection); - $connection->expects('bulk')->with(m::on(function (array $jobs) use ($chainHeadJob, $secondJob, $thirdJob): bool { + $connection->expects('bulk')->with(Argument::satisfies(function (array $jobs) use ($chainHeadJob, $secondJob, $thirdJob): bool { return $jobs[0] === $chainHeadJob && serialize($secondJob) === $jobs[0]->chained[0] @@ -738,7 +741,7 @@ public function testChainCanBeAddedToBatch(): void public function testChainedJobsInBatchPreserveTheirQueueWhenBatchHasNoQueue(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $repository = new DatabaseBatchRepository( new BatchFactory($queue), @@ -754,12 +757,12 @@ public function testChainedJobsInBatchPreserveTheirQueueWhenBatchHasNoQueue(): v $firstJob = (new ChainHeadJob)->onQueue('custom-queue'); $secondJob = (new SecondTestJob)->onQueue('custom-queue'); - $connection = m::mock(QueueContract::class); + $connection = Double::for(QueueContract::class); $queue->expects('connection') ->with('test-connection') - ->andReturn($connection); + ->returns($connection); - $connection->expects('bulk')->with(m::type('array'), '', null); + $connection->expects('bulk')->with(Argument::type('array'), '', null); $batch->add([ [$firstJob, $secondJob], @@ -771,7 +774,7 @@ public function testChainedJobsInBatchPreserveTheirQueueWhenBatchHasNoQueue(): v public function testChainedJobsPreserveTheirRoutesWhenTheBatchHasNone(): void { - $queue = m::mock(Factory::class); + $queue = Double::for(Factory::class); $repository = new DatabaseBatchRepository( new BatchFactory($queue), @@ -788,12 +791,12 @@ public function testChainedJobsPreserveTheirRoutesWhenTheBatchHasNone(): void ->onConnection('custom-connection') ->onQueue('custom-queue'); - $connection = m::mock(QueueContract::class); + $connection = Double::for(QueueContract::class); $queue->expects('connection') ->with(null) - ->andReturn($connection); + ->returns($connection); - $connection->expects('bulk')->with(m::type('array'), '', null); + $connection->expects('bulk')->with(Argument::type('array'), '', null); $batch->add([ [$firstJob, $secondJob], @@ -824,15 +827,15 @@ public function testOptionsSerializationOnPostgres(): void $pendingBatch = (new PendingBatch($this->app, Collection::make())) ->onQueue('test-queue'); - $connection = m::spy(PostgresConnection::class); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->andReturn($connection); - $builder = m::spy(Builder::class); + $connection = Double::for(PostgresConnection::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->returns($connection); + $builder = Double::for(Builder::class); - $connection->expects('table')->times(2)->andReturn($builder); - $builder->expects('useWritePdo')->andReturnSelf(); - $builder->expects('where')->andReturnSelf(); - $builder->expects('first')->andReturn((object) [ + $connection->expects('table')->times(2)->returns($builder); + $builder->expects('useWritePdo')->returns($builder); + $builder->expects('where')->returns($builder); + $builder->expects('first')->returns((object) [ 'id' => 'test-id', 'name' => '', 'total_jobs' => 0, @@ -846,28 +849,32 @@ public function testOptionsSerializationOnPostgres(): void ]); $repository = new DatabaseBatchRepository( - new BatchFactory(m::mock(Factory::class)), + new BatchFactory(Double::for(Factory::class)), $resolver, 'job_batches' ); $repository->store($pendingBatch); - $builder->shouldHaveReceived('insert') - ->withArgs(function (array $argument) use ($pendingBatch): bool { + $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 = m::mock(BatchFactory::class); - $connection = m::mock(PostgresConnection::class); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->andReturn($connection); - $connection->shouldReceive('table->useWritePdo->where->first')->once()->andReturn((object) [ + $factory = Double::for(BatchFactory::class); + $connection = Double::for(PostgresConnection::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->returns($connection); + $builder = Double::for(Builder::class); + $connection->expects('table')->returns($builder); + $builder->expects('useWritePdo')->returns($builder); + $builder->expects('where')->returns($builder); + $builder->expects('first')->returns((object) [ 'id' => 'batch', 'name' => '', 'total_jobs' => 0, 'pending_jobs' => 0, 'failed_jobs' => 0, 'failed_job_ids' => '[]', 'options' => serialize([new BatchOptionWithFailingRestoration($canceled)]), @@ -875,11 +882,11 @@ public function testOptionsRestorationFallbackDoesNotSwallowCancellation(bool $c ]); $repository = new DatabaseBatchRepository($factory, $resolver, 'job_batches'); if ($canceled) { - $factory->shouldNotReceive('make'); + $factory->expects('make')->never(); } else { - $factory->shouldReceive('make')->once() - ->withSomeOfArgs($repository, 'batch', '', 0, 0, 0, [], []) - ->andReturn(m::mock(Batch::class)); + $factory->expects('make') + ->with(Argument::same($repository), 'batch', '', 0, 0, 0, [], [], Argument::remaining()) + ->returns(Double::for(Batch::class)); } $caught = null; @@ -900,14 +907,18 @@ public function testOptionsRestorationFallbackDoesNotSwallowCancellation(bool $c #[DataProvider('serializedOptions')] public function testOptionsUnserializeOnPostgres(string $serialize, array $options): void { - $factory = m::mock(BatchFactory::class); - - $connection = m::spy(PostgresConnection::class); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->andReturn($connection); - - $connection->expects('table->useWritePdo->where->first') - ->andReturn((object) [ + $factory = Double::for(BatchFactory::class); + + $connection = Double::for(PostgresConnection::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->returns($connection); + + $builder = Double::for(Builder::class); + $connection->expects('table')->returns($builder); + $builder->expects('useWritePdo')->returns($builder); + $builder->expects('where')->returns($builder); + $builder->expects('first') + ->returns((object) [ 'id' => '', 'name' => '', 'total_jobs' => '', @@ -923,8 +934,8 @@ public function testOptionsUnserializeOnPostgres(string $serialize, array $optio $batch = new DatabaseBatchRepository($factory, $resolver, 'job_batches'); $factory->expects('make') - ->withSomeOfArgs($batch, '', '', 0, 0, 0, [], $options) - ->andReturn(m::mock(Batch::class)); + ->with($batch, '', '', 0, 0, 0, [], $options, Argument::remaining()) + ->returns(Double::for(Batch::class)); $batch->find('1'); } diff --git a/tests/Bus/BusBatchableTest.php b/tests/Bus/BusBatchableTest.php index 06fa2c892..5bb9bc853 100644 --- a/tests/Bus/BusBatchableTest.php +++ b/tests/Bus/BusBatchableTest.php @@ -11,10 +11,13 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Testing\Fakes\BatchFake; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class BusBatchableTest extends TestCase { + use VerifiesDoubles; + public function testBatchMayBeRetrieved(): void { $class = new class { @@ -26,9 +29,9 @@ public function testBatchMayBeRetrieved(): void Container::setInstance($container = new Container); - $repository = m::mock(BatchRepository::class); - $batch = m::mock(Batch::class); - $repository->expects('find')->with('test-batch-id')->andReturn($batch); + $repository = Double::for(BatchRepository::class); + $batch = Double::for(Batch::class); + $repository->expects('find')->with('test-batch-id')->returns($batch); $container->instance(BatchRepository::class, $repository); $this->assertSame($batch, $class->batch()); @@ -59,9 +62,9 @@ public function testZeroBatchIdMayBeRetrievedAndFaked(): void Container::setInstance($container = new Container); - $repository = m::mock(BatchRepository::class); - $batch = m::mock(Batch::class); - $repository->expects('find')->with('0')->andReturn($batch); + $repository = Double::for(BatchRepository::class); + $batch = Double::for(Batch::class); + $repository->expects('find')->with('0')->returns($batch); $container->instance(BatchRepository::class, $repository); $job->withBatchId('0'); diff --git a/tests/Bus/BusDispatcherTest.php b/tests/Bus/BusDispatcherTest.php index a12add631..678192a6c 100644 --- a/tests/Bus/BusDispatcherTest.php +++ b/tests/Bus/BusDispatcherTest.php @@ -17,11 +17,15 @@ use Hypervel\Queue\QueueRoutes; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; class BusDispatcherTest extends TestCase { + use VerifiesDoubles; + public function testCommandsThatShouldQueueIsQueued(): void { $container = new Container; @@ -54,8 +58,8 @@ public function testCommandsThatShouldQueueIsQueuedUsingCustomQueueAndDelay(): v $container->instance('queue.routes', new QueueRoutes); Container::setInstance($container); $dispatcher = new Dispatcher($container, function (): Queue { - $mock = m::mock(Queue::class); - $mock->expects('later')->with(10, m::type(BusDispatcherTestSpecificQueueAndDelayCommand::class), '', 'foo'); + $mock = Double::for(Queue::class); + $mock->expects('later')->with(10, Argument::type(BusDispatcherTestSpecificQueueAndDelayCommand::class), '', 'foo'); return $mock; }); @@ -72,8 +76,8 @@ public function testCommandsAreQueuedUsingAttributesInheritedFromParentClass(): $dispatcher = new Dispatcher($container, function (?string $connection) use (&$usedConnection): Queue { $usedConnection = $connection; - $mock = m::mock(Queue::class); - $mock->expects('later')->with(10, m::type(BusDispatcherTestQueueableChildCommand::class), '', 'foo'); + $mock = Double::for(Queue::class); + $mock->expects('later')->with(10, Argument::type(BusDispatcherTestQueueableChildCommand::class), '', 'foo'); return $mock; }); @@ -86,13 +90,13 @@ public function testCommandsAreQueuedUsingAttributesInheritedFromParentClass(): public function testCommandsThatShouldQueueIsQueuedUsingQueueAndDelayAttributes(): void { $container = new Container; - $queueRoutes = m::mock(QueueRoutes::class); - $queueRoutes->expects('getConnection')->andReturn(null); + $queueRoutes = Double::for(QueueRoutes::class); + $queueRoutes->expects('getConnection')->returns(null); $container->instance('queue.routes', $queueRoutes); Container::setInstance($container); $dispatcher = new Dispatcher($container, function (): Queue { - $mock = m::mock(Queue::class); - $mock->expects('later')->with(10, m::type(BusDispatcherTestSpecificQueueAndDelayAttributesCommand::class), '', 'foo'); + $mock = Double::for(Queue::class); + $mock->expects('later')->with(10, Argument::type(BusDispatcherTestSpecificQueueAndDelayAttributesCommand::class), '', 'foo'); return $mock; }); @@ -103,13 +107,13 @@ public function testCommandsThatShouldQueueIsQueuedUsingQueueAndDelayAttributes( public function testCommandDelayPropertyOverridesDelayAttribute(): void { $container = new Container; - $queueRoutes = m::mock(QueueRoutes::class); - $queueRoutes->expects('getConnection')->andReturn(null); + $queueRoutes = Double::for(QueueRoutes::class); + $queueRoutes->expects('getConnection')->returns(null); $container->instance('queue.routes', $queueRoutes); Container::setInstance($container); $dispatcher = new Dispatcher($container, function (): Queue { - $mock = m::mock(Queue::class); - $mock->expects('later')->with(60, m::type(BusDispatcherTestSpecificQueueAndDelayAttributeWithPropertyCommand::class), '', 'foo'); + $mock = Double::for(Queue::class); + $mock->expects('later')->with(60, Argument::type(BusDispatcherTestSpecificQueueAndDelayAttributeWithPropertyCommand::class), '', 'foo'); return $mock; }); @@ -163,8 +167,8 @@ public function testExplicitConnectionWinsOverForwardedQueue(): void $queueRoutes->forward('reports', 'processing', 'cloud'); $container->instance('queue.routes', $queueRoutes); - $mock = m::mock(Queue::class); - $mock->expects('push')->with(m::type(BusDispatcherQueueable::class), '', 'reports'); + $mock = Double::for(Queue::class); + $mock->expects('push')->with(Argument::type(BusDispatcherQueueable::class), '', 'reports'); $usedConnection = false; @@ -251,12 +255,12 @@ public function testDispatchBulk(): void $container->instance('queue.routes', new QueueRoutes); Container::setInstance($container); - $defaultQueue = m::mock(Queue::class); - $defaultQueue->expects('bulk')->with(m::on(fn (array $jobs): bool => count($jobs) === 2), '', null); - $defaultQueue->expects('bulk')->with(m::on(fn (array $jobs): bool => count($jobs) === 1), '', 'high'); + $defaultQueue = Double::for(Queue::class); + $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 = m::mock(Queue::class); - $priorityQueue->expects('bulk')->with(m::on(fn (array $jobs): bool => count($jobs) === 1), '', 'high'); + $priorityQueue = Double::for(Queue::class); + $priorityQueue->expects('bulk')->with(Argument::satisfies(fn (array $jobs): bool => count($jobs) === 1), '', 'high'); $dispatcher = new Dispatcher( $container, @@ -281,11 +285,11 @@ public function testDispatchBulkKeepsColonBearingRoutesSeparate(): void $firstJob = (new BusDispatcherQueueable)->onConnection('a:b')->onQueue('c'); $secondJob = (new BusDispatcherQueueable)->onConnection('a')->onQueue('b:c'); - $firstQueue = m::mock(Queue::class); - $firstQueue->expects('bulk')->with([$firstJob], '', 'c'); + $firstQueue = Double::for(Queue::class); + $firstQueue->expects('bulk')->with(Argument::same([$firstJob]), '', 'c'); - $secondQueue = m::mock(Queue::class); - $secondQueue->expects('bulk')->with([$secondJob], '', 'b:c'); + $secondQueue = Double::for(Queue::class); + $secondQueue->expects('bulk')->with(Argument::same([$secondJob]), '', 'b:c'); $dispatcher = new Dispatcher( new Container, diff --git a/tests/Bus/BusPendingBatchTest.php b/tests/Bus/BusPendingBatchTest.php index 2198be299..87b9fa314 100644 --- a/tests/Bus/BusPendingBatchTest.php +++ b/tests/Bus/BusPendingBatchTest.php @@ -13,6 +13,7 @@ use Hypervel\Bus\Queueable; use Hypervel\Container\Container; use Hypervel\Contracts\Bus\Dispatcher as BusDispatcher; +use Hypervel\Contracts\Bus\QueueingDispatcher; use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Coroutine\Coroutine; @@ -22,7 +23,9 @@ use Hypervel\Support\Collection; use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use stdClass; @@ -31,6 +34,8 @@ class BusPendingBatchTest extends TestCase { + use VerifiesDoubles; + #[TestWith(['direct'])] #[TestWith(['wrapped'])] #[TestWith(['deletion failure'])] @@ -43,18 +48,18 @@ public function testBeforeCallbackCancellationStopsBatchDispatch(string $scenari $cancellation = new CanceledException; $failure = $scenario === 'direct' ? $cancellation : new RuntimeException('Before cleanup failed.', previous: $cancellation); $container = new Container; - $repository = m::mock(BatchRepository::class); - $batch = m::mock(Batch::class); + $repository = Double::for(BatchRepository::class); + $batch = Double::for(Batch::class); $batch->id = 'batch'; - $batch->shouldNotReceive('add'); - $repository->shouldReceive('store')->once()->andReturn($batch); + $batch->expects('add')->never(); + $repository->expects('store')->returns($batch); $deletionFailure = new RuntimeException('Batch deletion failed.'); - $deletion = $repository->shouldReceive('delete')->once()->with('batch'); - $deleteThrows ? $deletion->andThrow($deletionFailure) : $deletion->andReturnNull(); + $deletion = $repository->expects('delete')->with('batch'); + $deleteThrows ? $deletion->throws($deletionFailure) : $deletion->returns(null); $container->instance(BatchRepository::class, $repository); if ($reporting) { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->andThrow($failure); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->throws($failure); $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); } @@ -81,17 +86,17 @@ public function testDeletionFailureRetainsDispatchCancellation(bool $stored): vo $cancellation = new CanceledException; $cleanup = new RuntimeException('Batch deletion failed.'); $container = new Container; - $repository = m::mock(BatchRepository::class); - $batch = m::mock(Batch::class); + $repository = Double::for(BatchRepository::class); + $batch = Double::for(Batch::class); $batch->id = 'batch'; - $batch->shouldReceive('add')->once()->andThrow($cancellation); + $batch->expects('add')->throws($cancellation); $container->instance(BatchRepository::class, $repository); if ($stored) { - $batch->shouldReceive('delete')->once()->andThrow($cleanup); + $batch->expects('delete')->throws($cleanup); } else { - $repository->shouldReceive('store')->once()->andReturn($batch); - $repository->shouldReceive('delete')->once()->with('batch')->andThrow($cleanup); + $repository->expects('store')->returns($batch); + $repository->expects('delete')->with('batch')->throws($cleanup); } $pending = new class($container, new Collection) extends PendingBatch { @@ -145,9 +150,9 @@ public function testChainedBatchPreservesZeroConnectionAndQueueIdentifiers(): vo ->onConnection(PendingBatchIntegerIdentifier::Zero) ->onQueue(PendingBatchIntegerIdentifier::Zero); - $dispatcher = m::mock(BusDispatcher::class); + $dispatcher = Double::for(QueueingDispatcher::class); $dispatcher->expects('batch') - ->andReturnUsing(fn (Collection $jobs): PendingBatch => new PendingBatch($container, $jobs)); + ->resolves(fn (Collection $jobs): PendingBatch => new PendingBatch($container, $jobs)); $container->instance(BusDispatcher::class, $dispatcher); $pendingBatch = (new ChainedBatch($source))->toPendingBatch(); @@ -170,9 +175,9 @@ public function testDirectlyRoutedChainedBatchPreservesZeroConnectionAndQueueIde ->onConnection('0') ->onQueue('0'); - $dispatcher = m::mock(BusDispatcher::class); + $dispatcher = Double::for(QueueingDispatcher::class); $dispatcher->expects('batch') - ->andReturnUsing(fn (Collection $jobs): PendingBatch => new PendingBatch($container, $jobs)); + ->resolves(fn (Collection $jobs): PendingBatch => new PendingBatch($container, $jobs)); $container->instance(BusDispatcher::class, $dispatcher); $pendingBatch = $chainedBatch->toPendingBatch(); @@ -194,9 +199,9 @@ public function testChainedBatchPreservesSourceEmptyConnectionAndQueueOptions(): ->onConnection('') ->onQueue(''); - $dispatcher = m::mock(BusDispatcher::class); + $dispatcher = Double::for(QueueingDispatcher::class); $dispatcher->expects('batch') - ->andReturnUsing(fn (Collection $jobs): PendingBatch => new PendingBatch($container, $jobs)); + ->resolves(fn (Collection $jobs): PendingBatch => new PendingBatch($container, $jobs)); $container->instance(BusDispatcher::class, $dispatcher); $pendingBatch = (new ChainedBatch($source))->toPendingBatch(); @@ -221,8 +226,8 @@ public function testChainedBatchRemainderInheritsEmptyIdentifiersAndPreservesZer $chainedBatch->chainConnection = 'chain-connection'; $chainedBatch->chainQueue = 'chain-queue'; - $dispatcher = m::mock(BusDispatcher::class); - $dispatcher->expects('dispatch')->with(m::on(function (ChainedBatchQueueableJob $job) use ($expectedConnection, $expectedQueue): bool { + $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); @@ -237,8 +242,8 @@ public function testChainedBatchRemainderInheritsEmptyIdentifiersAndPreservesZer $callbacks = $pendingBatch->finallyCallbacks(); $this->assertCount(1, $callbacks); - $batch = m::mock(Batch::class); - $batch->expects('cancelled')->andReturnFalse(); + $batch = Double::for(Batch::class); + $batch->expects('cancelled')->returns(false); $callbacks[0]($batch); } } @@ -254,8 +259,8 @@ public function testChainedBatchRemainderKeepsJobAttributesOverChainDefaults(): $chainedBatch->chainConnection = 'chain-connection'; $chainedBatch->chainQueue = 'chain-queue'; - $dispatcher = m::mock(BusDispatcher::class); - $dispatcher->expects('dispatch')->with(m::on(function (AttributedChainedBatchQueueableJob $job): bool { + $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); @@ -268,8 +273,8 @@ public function testChainedBatchRemainderKeepsJobAttributesOverChainDefaults(): $callbacks = $chainedBatch->attachRemainder(new PendingBatch($container, new Collection([$sourceJob]))) ->finallyCallbacks(); - $batch = m::mock(Batch::class); - $batch->expects('cancelled')->andReturnFalse(); + $batch = Double::for(Batch::class); + $batch->expects('cancelled')->returns(false); $callbacks[0]($batch); } @@ -301,11 +306,11 @@ public function testPendingBatchMayBeConfiguredAndDispatched(): void $this->assertArrayHasKey('extra-option', $pendingBatch->options); $this->assertSame(123, $pendingBatch->options['extra-option']); - $repository = m::mock(BatchRepository::class); - $storedBatch = m::mock(Batch::class); - $repository->expects('store')->with($pendingBatch)->andReturn($storedBatch); - $batch = m::mock(Batch::class); - $storedBatch->expects('add')->with(m::type(Collection::class))->andReturn($batch); + $repository = Double::for(BatchRepository::class); + $storedBatch = Double::for(Batch::class); + $repository->expects('store')->with($pendingBatch)->returns($storedBatch); + $batch = Double::for(Batch::class); + $storedBatch->expects('add')->with(Argument::type(Collection::class))->returns($batch); $container->instance(BatchRepository::class, $repository); @@ -318,9 +323,9 @@ public function testBatchDispatchedEventIsSkippedWithoutListeners(): void { $container = new Container; - $eventDispatcher = m::mock(Dispatcher::class); - $eventDispatcher->expects('hasListeners')->with(BatchDispatched::class)->andReturnFalse(); - $eventDispatcher->shouldNotReceive('dispatch'); + $eventDispatcher = Double::for(Dispatcher::class); + $eventDispatcher->expects('hasListeners')->with(BatchDispatched::class)->returns(false); + $eventDispatcher->expects('dispatch')->never(); $container->instance(Dispatcher::class, $eventDispatcher); $job = new class { @@ -329,10 +334,10 @@ public function testBatchDispatchedEventIsSkippedWithoutListeners(): void $pendingBatch = new PendingBatch($container, new Collection([$job])); - $repository = m::mock(BatchRepository::class); - $batch = m::mock(Batch::class); - $repository->expects('store')->with($pendingBatch)->andReturn($batch); - $batch->expects('add')->with(m::type(Collection::class))->andReturnSelf(); + $repository = Double::for(BatchRepository::class); + $batch = Double::for(Batch::class); + $repository->expects('store')->with($pendingBatch)->returns($batch); + $batch->expects('add')->with(Argument::type(Collection::class))->returns($batch); $container->instance(BatchRepository::class, $repository); $this->assertSame($batch, $pendingBatch->dispatch()); @@ -342,9 +347,9 @@ public function testBatchDispatchedEventIsDispatchedAfterResponse(): void { $container = new Container; - $eventDispatcher = m::mock(Dispatcher::class); - $eventDispatcher->expects('hasListeners')->with(BatchDispatched::class)->andReturnTrue(); - $eventDispatcher->expects('dispatch')->with(m::type(BatchDispatched::class)); + $eventDispatcher = Double::for(Dispatcher::class); + $eventDispatcher->expects('hasListeners')->with(BatchDispatched::class)->returns(true); + $eventDispatcher->expects('dispatch')->with(Argument::type(BatchDispatched::class)); $container->instance(Dispatcher::class, $eventDispatcher); $job = new class { @@ -353,10 +358,10 @@ public function testBatchDispatchedEventIsDispatchedAfterResponse(): void $pendingBatch = new PendingBatch($container, new Collection([$job])); - $repository = m::mock(BatchRepository::class); - $batch = m::mock(Batch::class); - $repository->expects('store')->with($pendingBatch)->andReturn($batch); - $batch->expects('add')->with(m::type(Collection::class))->andReturnSelf(); + $repository = Double::for(BatchRepository::class); + $batch = Double::for(Batch::class); + $repository->expects('store')->with($pendingBatch)->returns($batch); + $batch->expects('add')->with(Argument::type(Collection::class))->returns($batch); $container->instance(BatchRepository::class, $repository); $this->assertSame($batch, $pendingBatch->dispatchAfterResponse()); @@ -374,14 +379,14 @@ public function testBatchIsDeletedFromStorageIfExceptionThrownDuringBatching(): $pendingBatch = new PendingBatch($container, new Collection([$job])); - $repository = m::mock(BatchRepository::class); + $repository = Double::for(BatchRepository::class); - $batch = m::mock(Batch::class); - $repository->expects('store')->with($pendingBatch)->andReturn($batch); + $batch = Double::for(Batch::class); + $repository->expects('store')->with($pendingBatch)->returns($batch); $batch->id = 'test-id'; - $batch->expects('add')->andReturnUsing(function (): never { + $batch->expects('add')->resolves(function (): never { throw new RuntimeException('Failed to add jobs...'); }); @@ -405,11 +410,11 @@ public function testBatchIsDispatchedWhenDispatchifIsTrue(): void $pendingBatch = new PendingBatch($container, new Collection([$job])); - $repository = m::mock(BatchRepository::class); - $storedBatch = m::mock(Batch::class); - $repository->expects('store')->andReturn($storedBatch); - $batch = m::mock(Batch::class); - $storedBatch->expects('add')->andReturn($batch); + $repository = Double::for(BatchRepository::class); + $storedBatch = Double::for(Batch::class); + $repository->expects('store')->returns($storedBatch); + $batch = Double::for(Batch::class); + $storedBatch->expects('add')->returns($batch); $container->instance(BatchRepository::class, $repository); @@ -433,7 +438,7 @@ public function testBatchIsNotDispatchedWhenDispatchifIsFalse(): void $pendingBatch = new PendingBatch($container, new Collection([$job])); - $repository = m::mock(BatchRepository::class); + $repository = Double::for(BatchRepository::class); $container->instance(BatchRepository::class, $repository); $result = $pendingBatch->dispatchIf(false); @@ -441,6 +446,7 @@ public function testBatchIsNotDispatchedWhenDispatchifIsFalse(): void $this->assertNull($result); $eventDispatcher->assertNothingDispatched(); + $repository->unused(); } public function testBatchIsDispatchedWhenDispatchunlessIsFalse(): void @@ -456,11 +462,11 @@ public function testBatchIsDispatchedWhenDispatchunlessIsFalse(): void $pendingBatch = new PendingBatch($container, new Collection([$job])); - $repository = m::mock(BatchRepository::class); - $storedBatch = m::mock(Batch::class); - $repository->expects('store')->andReturn($storedBatch); - $batch = m::mock(Batch::class); - $storedBatch->expects('add')->andReturn($batch); + $repository = Double::for(BatchRepository::class); + $storedBatch = Double::for(Batch::class); + $repository->expects('store')->returns($storedBatch); + $batch = Double::for(Batch::class); + $storedBatch->expects('add')->returns($batch); $container->instance(BatchRepository::class, $repository); @@ -484,7 +490,7 @@ public function testBatchIsNotDispatchedWhenDispatchunlessIsTrue(): void $pendingBatch = new PendingBatch($container, new Collection([$job])); - $repository = m::mock(BatchRepository::class); + $repository = Double::for(BatchRepository::class); $container->instance(BatchRepository::class, $repository); $result = $pendingBatch->dispatchUnless(true); @@ -492,6 +498,7 @@ public function testBatchIsNotDispatchedWhenDispatchunlessIsTrue(): void $this->assertNull($result); $eventDispatcher->assertNothingDispatched(); + $repository->unused(); } public function testBatchBeforeEventIsCalled(): void @@ -513,11 +520,11 @@ public function testBatchBeforeEventIsCalled(): void $beforeCalled = true; })->onConnection('test-connection')->onQueue('test-queue'); - $repository = m::mock(BatchRepository::class); - $storedBatch = m::mock(Batch::class); - $repository->expects('store')->with($pendingBatch)->andReturn($storedBatch); - $batch = m::mock(Batch::class); - $storedBatch->expects('add')->with(m::type(Collection::class))->andReturn($batch); + $repository = Double::for(BatchRepository::class); + $storedBatch = Double::for(Batch::class); + $repository->expects('store')->with($pendingBatch)->returns($storedBatch); + $batch = Double::for(Batch::class); + $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 83633f1ee..d24bfb565 100644 --- a/tests/Bus/BusPendingDispatchTest.php +++ b/tests/Bus/BusPendingDispatchTest.php @@ -16,7 +16,9 @@ use Hypervel\Foundation\Bus\PendingDispatch; use Hypervel\Queue\Attributes\DebounceFor; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionClass; use stdClass; @@ -33,7 +35,9 @@ public function __destruct() class BusPendingDispatchTest extends TestCase { - protected stdClass&m\MockInterface $job; + use VerifiesDoubles; + + protected PendingDispatchTestJob $job; protected PendingDispatchWithoutDestructor $pendingDispatch; @@ -44,49 +48,55 @@ protected function setUp(): void { parent::setUp(); - $this->job = m::mock(stdClass::class); + $this->job = new PendingDispatchTestJob; $this->pendingDispatch = new PendingDispatchWithoutDestructor($this->job); } public function testOnConnection(): void { - $this->job->expects('onConnection')->with('test-connection'); $this->pendingDispatch->onConnection('test-connection'); + + $this->assertSame('test-connection', $this->job->connection); } public function testOnQueue(): void { - $this->job->expects('onQueue')->with('test-queue'); $this->pendingDispatch->onQueue('test-queue'); + + $this->assertSame('test-queue', $this->job->queue); } public function testOnGroup(): void { - $this->job->expects('onGroup')->with('test-group'); $this->pendingDispatch->onGroup('test-group'); + + $this->assertSame('test-group', $this->job->messageGroup); } public function testOnGroupForwardsAnArray(): void { $groups = ['first', 'second']; - $this->job->expects('onGroup')->with($groups); $this->pendingDispatch->onGroup($groups); + + $this->assertSame($groups, $this->job->messageGroup); } public function testWithDeduplicator(): void { $deduplicator = fn (): string => 'id'; - $this->job->expects('withDeduplicator')->with($deduplicator); $this->pendingDispatch->withDeduplicator($deduplicator); + + $this->assertSame($deduplicator, $this->job->deduplicator->getClosure()); } public function testWithDeduplicatorForwardsAnArrayCallable(): void { $deduplicator = [$this, 'resolveDeduplicationId']; - $this->job->expects('withDeduplicator')->with($deduplicator); $this->pendingDispatch->withDeduplicator($deduplicator); + + $this->assertSame($deduplicator, $this->job->deduplicator); } /** @@ -99,45 +109,53 @@ public function resolveDeduplicationId(): string public function testAllOnConnection(): void { - $this->job->expects('allOnConnection')->with('test-connection'); $this->pendingDispatch->allOnConnection('test-connection'); + + $this->assertSame('test-connection', $this->job->connection); + $this->assertSame('test-connection', $this->job->chainConnection); } public function testAllOnQueue(): void { - $this->job->expects('allOnQueue')->with('test-queue'); $this->pendingDispatch->allOnQueue('test-queue'); + + $this->assertSame('test-queue', $this->job->queue); + $this->assertSame('test-queue', $this->job->chainQueue); } public function testDelay(): void { - $this->job->expects('delay')->with(60); $this->pendingDispatch->delay(60); + + $this->assertSame(60, $this->job->delay); } public function testWithoutDelay(): void { - $this->job->expects('withoutDelay'); - $this->pendingDispatch->withoutDelay(); + $this->pendingDispatch->delay(60)->withoutDelay(); + + $this->assertSame(0, $this->job->delay); } public function testAfterCommit(): void { - $this->job->expects('afterCommit'); $this->pendingDispatch->afterCommit(); + + $this->assertTrue($this->job->afterCommit); } public function testBeforeCommit(): void { - $this->job->expects('beforeCommit'); $this->pendingDispatch->beforeCommit(); + + $this->assertFalse($this->job->afterCommit); } public function testChain(): void { - $chain = [new stdClass]; - $this->job->expects('chain')->with($chain); - $this->pendingDispatch->chain($chain); + $this->pendingDispatch->chain([new stdClass]); + + $this->assertSame([serialize(new stdClass)], $this->job->chained); } public function testAfterResponse(): void @@ -166,9 +184,9 @@ public function testPrepareForDispatchCanAbortDispatchBeforeDebounceCacheIsResol { Container::setInstance($container = new Container); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->never(); - $dispatcher->shouldReceive('dispatchAfterResponse')->never(); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->never(); + $dispatcher->expects('dispatchAfterResponse')->never(); $container->instance(Dispatcher::class, $dispatcher); $job = new PreparingDebouncedPendingDispatchJob(false); @@ -182,9 +200,9 @@ public function testPrepareForDispatchCanAbortDispatchBeforeUniqueLockCacheIsRes { Container::setInstance($container = new Container); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->never(); - $dispatcher->shouldReceive('dispatchAfterResponse')->never(); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->never(); + $dispatcher->expects('dispatchAfterResponse')->never(); $container->instance(Dispatcher::class, $dispatcher); $pendingDispatch = new PendingDispatch(new PreparingUniquePendingDispatchJob(false)); @@ -195,9 +213,9 @@ public function testPrepareForDispatchAllowsDispatch(): void { Container::setInstance($container = new Container); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->expects('dispatch')->with(m::type(PreparingPendingDispatchJob::class)); - $dispatcher->shouldReceive('dispatchAfterResponse')->never(); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->with(Argument::type(PreparingPendingDispatchJob::class)); + $dispatcher->expects('dispatchAfterResponse')->never(); $container->instance(Dispatcher::class, $dispatcher); $pendingDispatch = new PendingDispatch(new PreparingPendingDispatchJob(true)); @@ -215,11 +233,11 @@ public function testUniqueMetadataReachesAfterResponseDispatcherBeforeUnclaimedO $deferredJob = null; $metadata = null; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->never(); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->never(); $dispatcher->expects('dispatchAfterResponse') - ->with($job) - ->andReturnUsing(function (object $job) use (&$deferredJob, &$metadata): void { + ->with(Argument::same($job)) + ->resolves(function (object $job) use (&$deferredJob, &$metadata): void { $deferredJob = $job; $metadata = DispatchLockContext::peekPayloadMetadata($job); }); @@ -244,40 +262,45 @@ public function testUniqueMetadataReachesAfterResponseDispatcherBeforeUnclaimedO public function testDynamicallyProxyMethods(): void { - $newJob = new stdClass; - $this->job->expects('appendToChain')->with($newJob); - $this->pendingDispatch->appendToChain($newJob); + $this->pendingDispatch->appendToChain(new stdClass); + + $this->assertSame([serialize(new stdClass)], $this->job->chained); } public function testWhenMethodOfConditionableTraitWithTrue(): void { - $this->job->expects('delay')->with(300); - $this->pendingDispatch->when(true, fn (PendingDispatch $pendingDispatch): PendingDispatch => $pendingDispatch->delay(300)); + + $this->assertSame(300, $this->job->delay); } public function testWhenMethodOfConditionableTraitWithFalse(): void { - $this->job->shouldReceive('delay')->never(); - $this->pendingDispatch->when(false, fn (PendingDispatch $pendingDispatch): PendingDispatch => $pendingDispatch->delay(300)); + + $this->assertNull($this->job->delay); } public function testUnlessMethodOfConditionableTraitWithTrue(): void { - $this->job->shouldReceive('delay')->never(); - $this->pendingDispatch->unless(true, fn (PendingDispatch $pendingDispatch): PendingDispatch => $pendingDispatch->delay(300)); + + $this->assertNull($this->job->delay); } public function testUnlessMethodOfConditionableTraitWithFalse(): void { - $this->job->expects('delay')->with(300); - $this->pendingDispatch->unless(false, fn (PendingDispatch $pendingDispatch): PendingDispatch => $pendingDispatch->delay(300)); + + $this->assertSame(300, $this->job->delay); } } +class PendingDispatchTestJob +{ + use Queueable; +} + class PreparingPendingDispatchJob implements PreparesForDispatch { /** diff --git a/tests/Cache/CacheDatabaseStoreTest.php b/tests/Cache/CacheDatabaseStoreTest.php index 3f4288c09..c63df5432 100644 --- a/tests/Cache/CacheDatabaseStoreTest.php +++ b/tests/Cache/CacheDatabaseStoreTest.php @@ -16,16 +16,20 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use stdClass; class CacheDatabaseStoreTest extends TestCase { + use VerifiesDoubles; + public function testNullIsReturnedWhenItemNotFound(): void { [$store, $table] = $this->getStore(); - $table->expects('whereIn')->with('key', ['prefixfoo'])->andReturn($table); - $table->expects('get')->andReturn(new Collection); + $table->expects('whereIn')->with('key', ['prefixfoo'])->returns($table); + $table->expects('get')->returns(new Collection); $this->assertNull($store->get('foo')); } @@ -37,8 +41,8 @@ public function testNullIsReturnedAndItemDeletedWhenItemIsExpired(): void [$store, $table] = $this->getStore(); // First call for retrieval - $table->expects('whereIn')->with('key', ['prefixfoo'])->andReturn($table); - $table->expects('get')->andReturn(new Collection([(object) [ + $table->expects('whereIn')->with('key', ['prefixfoo'])->returns($table); + $table->expects('get')->returns(new Collection([(object) [ 'key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => $now->copy()->subSeconds(10)->getTimestamp(), @@ -47,8 +51,8 @@ public function testNullIsReturnedAndItemDeletedWhenItemIsExpired(): void // Second call for deletion of expired items (includes flexible key cleanup) $table->expects('whereIn') ->with('key', ['prefixfoo', 'prefixhypervel:cache:flexible:created:foo']) - ->andReturn($table); - $table->expects('where')->with('expiration', '<=', $now->getTimestamp())->andReturn($table); + ->returns($table); + $table->expects('where')->with('expiration', '<=', $now->getTimestamp())->returns($table); $table->expects('delete'); $this->assertNull($store->get('foo')); @@ -57,8 +61,8 @@ public function testNullIsReturnedAndItemDeletedWhenItemIsExpired(): void public function testDecryptedValueIsReturnedWhenItemIsValid(): void { [$store, $table] = $this->getStore(); - $table->expects('whereIn')->with('key', ['prefixfoo'])->andReturn($table); - $table->expects('get')->andReturn(new Collection([(object) ['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 999999999999999]])); + $table->expects('whereIn')->with('key', ['prefixfoo'])->returns($table); + $table->expects('get')->returns(new Collection([(object) ['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 999999999999999]])); $this->assertSame('bar', $store->get('foo')); } @@ -69,8 +73,8 @@ public function testSerializableClassesControlCachedObjects(): void [$allowingStore, $allowingTable] = $this->getStore([stdClass::class]); foreach ([$denyingTable, $allowingTable] as $table) { - $table->shouldReceive('whereIn')->once()->with('key', ['prefixfoo'])->andReturn($table); - $table->shouldReceive('get')->once()->andReturn(new Collection([(object) [ + $table->expects('whereIn')->with('key', ['prefixfoo'])->returns($table); + $table->expects('get')->returns(new Collection([(object) [ 'key' => 'prefixfoo', 'value' => serialize(new stdClass), 'expiration' => 999999999999999, @@ -91,8 +95,8 @@ public function testSerializableClassPolicyControlsCachedObjects(): void ); foreach ([$denyingTable, $allowingTable] as $table) { - $table->shouldReceive('whereIn')->once()->with('key', ['prefixfoo'])->andReturn($table); - $table->shouldReceive('get')->once()->andReturn(new Collection([(object) [ + $table->expects('whereIn')->with('key', ['prefixfoo'])->returns($table); + $table->expects('get')->returns(new Collection([(object) [ 'key' => 'prefixfoo', 'value' => serialize(new stdClass), 'expiration' => 999999999999999, @@ -106,8 +110,8 @@ public function testSerializableClassPolicyControlsCachedObjects(): void public function testValueIsReturnedOnPostgres(): void { [$store, $table] = $this->getPostgresStore(); - $table->expects('whereIn')->with('key', ['prefixfoo'])->andReturn($table); - $table->expects('get')->andReturn(new Collection([(object) ['key' => 'prefixfoo', 'value' => base64_encode(serialize('bar')), 'expiration' => 999999999999999]])); + $table->expects('whereIn')->with('key', ['prefixfoo'])->returns($table); + $table->expects('get')->returns(new Collection([(object) ['key' => 'prefixfoo', 'value' => base64_encode(serialize('bar')), 'expiration' => 999999999999999]])); $this->assertSame('bar', $store->get('foo')); } @@ -115,8 +119,8 @@ public function testValueIsReturnedOnPostgres(): void public function testValueIsReturnedOnSqlite(): void { [$store, $table] = $this->getSqliteStore(); - $table->expects('whereIn')->with('key', ['prefixfoo'])->andReturn($table); - $table->expects('get')->andReturn(new Collection([(object) ['key' => 'prefixfoo', 'value' => base64_encode(serialize("\0bar\0")), 'expiration' => 999999999999999]])); + $table->expects('whereIn')->with('key', ['prefixfoo'])->returns($table); + $table->expects('get')->returns(new Collection([(object) ['key' => 'prefixfoo', 'value' => base64_encode(serialize("\0bar\0")), 'expiration' => 999999999999999]])); $this->assertSame("\0bar\0", $store->get('foo')); } @@ -124,12 +128,11 @@ public function testValueIsReturnedOnSqlite(): void public function testManyReturnsMultipleItems(): void { [$store, $table] = $this->getStore(); - $table->shouldReceive('whereIn') - ->once() + $table->expects('whereIn') ->with('key', ['prefixfoo', 'prefixbar', 'prefixbaz']) - ->andReturn($table); + ->returns($table); - $table->shouldReceive('get')->once()->andReturn(new Collection([ + $table->expects('get')->returns(new Collection([ (object) [ 'key' => 'prefixfoo', 'value' => serialize('bar'), @@ -156,7 +159,7 @@ public function testValueIsUpserted(): void CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC(1)); [$store, $table] = $this->getStore(); - $table->expects('upsert')->with([['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 61]], 'key')->andReturn(1); + $table->expects('upsert')->with([['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 61]], 'key')->returns(1); $result = $store->put('foo', 'bar', 60); $this->assertTrue($result); @@ -167,7 +170,7 @@ public function testValueIsUpsertedOnPostgres(): void CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC(1)); [$store, $table] = $this->getPostgresStore(); - $table->expects('upsert')->with([['key' => 'prefixfoo', 'value' => base64_encode(serialize("\0")), 'expiration' => 61]], 'key')->andReturn(1); + $table->expects('upsert')->with([['key' => 'prefixfoo', 'value' => base64_encode(serialize("\0")), 'expiration' => 61]], 'key')->returns(1); $result = $store->put('foo', "\0", 60); $this->assertTrue($result); @@ -178,7 +181,7 @@ public function testValueIsUpsertedOnSqlite(): void CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC(1)); [$store, $table] = $this->getSqliteStore(); - $table->expects('upsert')->with([['key' => 'prefixfoo', 'value' => base64_encode(serialize("\0")), 'expiration' => 61]], 'key')->andReturn(1); + $table->expects('upsert')->with([['key' => 'prefixfoo', 'value' => base64_encode(serialize("\0")), 'expiration' => 61]], 'key')->returns(1); $result = $store->put('foo', "\0", 60); $this->assertTrue($result); @@ -188,7 +191,7 @@ public function testManyItemsCanBeStoredAtOnce(): void { [$store, $table] = $this->getStore(); - $table->shouldReceive('upsert')->once()->with(m::on(function (mixed $arg): bool { + $table->expects('upsert')->with(Argument::satisfies(function (mixed $arg): bool { return is_array($arg) && count($arg) === 2 && $arg[0]['key'] === 'prefixfoo' @@ -197,7 +200,7 @@ public function testManyItemsCanBeStoredAtOnce(): void && $arg[1]['key'] === 'prefixbaz' && $arg[1]['value'] === serialize('qux') && is_int($arg[1]['expiration']); - }), 'key')->andReturn(2); + }), 'key')->returns(2); $result = $store->putMany(['foo' => 'bar', 'baz' => 'qux'], 10); $this->assertTrue($result); @@ -207,7 +210,7 @@ public function testPutManyReturnsTrueForEmptyInputWithoutUpserting(): void { [$store, $table] = $this->getStore(); - $table->shouldNotReceive('upsert'); + $table->expects('upsert')->never(); $this->assertTrue($store->putMany([], 10)); } @@ -217,7 +220,7 @@ public function testPutManyReturnsTrueWhenUpsertAffectsNoRows(): void CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC(1)); [$store, $table] = $this->getStore(); - $table->shouldReceive('upsert')->once()->with([['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 61]], 'key')->andReturn(0); + $table->expects('upsert')->with([['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 61]], 'key')->returns(0); $this->assertTrue($store->putMany(['foo' => 'bar'], 60)); } @@ -227,7 +230,7 @@ public function testPutReturnsTrueWhenDelegatedUpsertAffectsNoRows(): void CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC(1)); [$store, $table] = $this->getStore(); - $table->shouldReceive('upsert')->once()->with([['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 61]], 'key')->andReturn(0); + $table->expects('upsert')->with([['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 61]], 'key')->returns(0); $this->assertTrue($store->put('foo', 'bar', 60)); } @@ -237,16 +240,16 @@ public function testAddOnlyAddsIfKeyDoesntExist(): void [$store, $table] = $this->getStore(); // Check if exists (returns null) - $table->shouldReceive('whereIn')->once()->with('key', ['prefixfoo'])->andReturn($table); - $table->shouldReceive('get')->once()->andReturn(new Collection); + $table->expects('whereIn')->with('key', ['prefixfoo'])->returns($table); + $table->expects('get')->returns(new Collection); // Insert (uses insertOrIgnore for atomicity) - $table->shouldReceive('insertOrIgnore')->once()->with(m::on(function (mixed $arg): bool { + $table->expects('insertOrIgnore')->with(Argument::satisfies(function (mixed $arg): bool { return is_array($arg) && $arg['key'] === 'prefixfoo' && $arg['value'] === serialize('bar') && is_int($arg['expiration']); - }))->andReturn(1); + }))->returns(1); $this->assertTrue($store->add('foo', 'bar', 10)); } @@ -257,25 +260,25 @@ public function testFractionalSecondWritesNeverExpireBeforeRequestedDeadline(): [$store, $table] = $this->getStore(); - $table->shouldReceive('upsert')->once()->with([ + $table->expects('upsert')->with([ ['key' => 'prefixfoo', 'value' => serialize('bar'), 'expiration' => 1002], - ], 'key')->andReturn(1); + ], 'key')->returns(1); $this->assertTrue($store->put('foo', 'bar', 1)); - $table->shouldReceive('whereIn')->once()->with('key', ['prefixnew'])->andReturn($table); - $table->shouldReceive('get')->once()->andReturn(new Collection); - $table->shouldReceive('insertOrIgnore')->once()->with([ + $table->expects('whereIn')->with('key', ['prefixnew'])->returns($table); + $table->expects('get')->returns(new Collection); + $table->expects('insertOrIgnore')->with([ 'key' => 'prefixnew', 'value' => serialize('value'), 'expiration' => 1002, - ])->andReturn(1); + ])->returns(1); $this->assertTrue($store->add('new', 'value', 1)); - $table->shouldReceive('where')->once()->with('key', '=', 'prefixtouched')->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', 1000)->andReturn($table); - $table->shouldReceive('update')->once()->with(['expiration' => 1002])->andReturn(1); + $table->expects('where')->with('key', '=', 'prefixtouched')->returns($table); + $table->expects('where')->with('expiration', '>', 1000)->returns($table); + $table->expects('update')->with(['expiration' => 1002])->returns(1); $this->assertTrue($store->touch('touched', 1)); } @@ -283,8 +286,8 @@ public function testFractionalSecondWritesNeverExpireBeforeRequestedDeadline(): public function testAddReturnsFalseIfKeyExists(): void { [$store, $table] = $this->getStore(); - $table->shouldReceive('whereIn')->once()->with('key', ['prefixfoo'])->andReturn($table); - $table->shouldReceive('get')->once()->andReturn(new Collection([ + $table->expects('whereIn')->with('key', ['prefixfoo'])->returns($table); + $table->expects('get')->returns(new Collection([ (object) [ 'key' => 'prefixfoo', 'value' => serialize('bar'), @@ -314,7 +317,7 @@ public function testForeverCallsStoreItemWithReallyLongTime(): void public function testItemsMayBeRemovedFromCache(): void { [$store, $table] = $this->getStore(); - $table->expects('whereIn')->with('key', ['prefixfoo', 'prefixhypervel:cache:flexible:created:foo'])->andReturn($table); + $table->expects('whereIn')->with('key', ['prefixfoo', 'prefixhypervel:cache:flexible:created:foo'])->returns($table); $table->expects('delete'); $store->forget('foo'); @@ -323,7 +326,7 @@ public function testItemsMayBeRemovedFromCache(): void public function testItemsMayBeFlushedFromCache(): void { [$store, $table] = $this->getStore(); - $table->expects('delete')->andReturn(2); + $table->expects('delete')->returns(2); $result = $store->flush(); $this->assertTrue($result); @@ -332,11 +335,11 @@ public function testItemsMayBeFlushedFromCache(): void public function testLocksMayBeFlushedFromCache(): void { [$store, , , $resolver] = $this->getStore(); - $lockConnection = m::mock(Connection::class); - $lockTable = m::mock(Builder::class); - $resolver->shouldReceive('connection')->with('locks')->andReturn($lockConnection); - $lockConnection->expects('table')->with('cache_locks')->andReturn($lockTable); - $lockTable->expects('delete')->andReturn(2); + $lockConnection = Double::for(Connection::class); + $lockTable = Double::for(Builder::class); + $resolver->allows('connection')->with('locks')->returns($lockConnection); + $lockConnection->expects('table')->with('cache_locks')->returns($lockTable); + $lockTable->expects('delete')->returns(2); $store->setLockConnection('locks'); $result = $store->flushLocks(); @@ -346,93 +349,49 @@ public function testLocksMayBeFlushedFromCache(): void public function testIncrementReturnsCorrectValues(): void { [$store, $table, $connection] = $this->getStore(); + $cache = new stdClass; - $connection->expects('transaction')->with(m::type(Closure::class))->andReturnUsing(function (Closure $callback) use ($connection): mixed { - return $callback($connection); + $connection->expects('transaction')->with(Argument::type(Closure::class))->times(3)->resolves(function (Closure $closure) use ($connection): mixed { + return $closure($connection); }); - - $table->expects('where')->with('key', 'prefixfoo')->andReturn($table); - $table->expects('lockForUpdate')->andReturn($table); - $table->expects('first')->andReturnNull(); + $table->expects('where')->with('key', 'prefixfoo')->times(4)->returns($table); + $table->expects('lockForUpdate')->times(3)->returns($table); + $table->expects('first')->times(3)->returns(null, $cache, $cache); + $table->expects('update')->with(['value' => serialize(3)]); $this->assertFalse($store->increment('foo')); - $connection->expects('transaction')->with(m::type(Closure::class))->andReturnUsing(function (Closure $callback) use ($connection): mixed { - return $callback($connection); - }); - - $table->expects('where')->with('key', 'prefixfoo')->andReturn($table); - $table->expects('lockForUpdate')->andReturn($table); - $table->expects('first')->andReturn((object) ['value' => serialize('bar')]); - + $cache->value = serialize('bar'); $this->assertFalse($store->increment('foo')); - $connection->expects('transaction')->with(m::type(Closure::class))->andReturnUsing(function (Closure $callback) use ($connection): mixed { - return $callback($connection); - }); - - $table->expects('where')->with('key', 'prefixfoo')->andReturn($table); - $table->expects('lockForUpdate')->andReturn($table); - $table->expects('first')->andReturn((object) [ - 'key' => 'prefixfoo', - 'value' => serialize(2), - 'expiration' => 999999999999999, - ]); - - $table->expects('where')->with('key', 'prefixfoo')->andReturn($table); - $table->expects('update')->with(['value' => serialize(3)])->andReturn(1); - + $cache->value = serialize(2); $this->assertSame(3, $store->increment('foo')); } public function testDecrementReturnsCorrectValues(): void { [$store, $table, $connection] = $this->getStore(); + $cache = new stdClass; - $connection->expects('transaction')->with(m::type(Closure::class))->andReturnUsing(function (Closure $callback) use ($connection): mixed { - return $callback($connection); + $connection->expects('transaction')->with(Argument::type(Closure::class))->times(4)->resolves(function (Closure $closure) use ($connection): mixed { + return $closure($connection); }); - $table->expects('where')->with('key', 'prefixfoo')->andReturn($table); - $table->expects('lockForUpdate')->andReturn($table); - $table->expects('first')->andReturnNull(); + $table->expects('where')->with('key', 'prefixfoo')->times(4)->returns($table); + $table->expects('where')->with('key', 'prefixbar')->times(2)->returns($table); + $table->expects('lockForUpdate')->times(4)->returns($table); + $table->expects('first')->times(4)->returns(null, $cache, $cache, $cache); + $table->expects('update')->with(['value' => serialize(2)]); + $table->expects('update')->with(['value' => serialize(7)]); $this->assertFalse($store->decrement('foo')); - $connection->expects('transaction')->with(m::type(Closure::class))->andReturnUsing(function (Closure $callback) use ($connection): mixed { - return $callback($connection); - }); - $table->expects('where')->with('key', 'prefixfoo')->andReturn($table); - $table->expects('lockForUpdate')->andReturn($table); - $table->expects('first')->andReturn((object) ['value' => serialize('bar')]); - + $cache->value = serialize('bar'); $this->assertFalse($store->decrement('foo')); - $connection->expects('transaction')->with(m::type(Closure::class))->andReturnUsing(function (Closure $callback) use ($connection): mixed { - return $callback($connection); - }); - $table->expects('where')->with('key', 'prefixbar')->andReturn($table); - $table->expects('lockForUpdate')->andReturn($table); - $table->expects('first')->andReturn((object) ['value' => serialize(3)]); - $table->expects('where')->with('key', 'prefixbar')->andReturn($table); - $table->expects('update')->with(['value' => serialize(2)])->andReturn(1); - + $cache->value = serialize(3); $this->assertSame(2, $store->decrement('bar')); - $connection->expects('transaction')->with(m::type(Closure::class))->andReturnUsing(function (Closure $callback) use ($connection): mixed { - return $callback($connection); - }); - - $table->expects('where')->with('key', 'prefixfoo')->andReturn($table); - $table->expects('lockForUpdate')->andReturn($table); - $table->expects('first')->andReturn((object) [ - 'key' => 'prefixfoo', - 'value' => serialize(10), - 'expiration' => 999999999999999, - ]); - - $table->expects('where')->with('key', 'prefixfoo')->andReturn($table); - $table->expects('update')->with(['value' => serialize(7)])->andReturn(1); - + $cache->value = serialize(10); $this->assertSame(7, $store->decrement('foo', 3)); } @@ -444,8 +403,8 @@ public function testTouchExtendsTtl(): void [$table] = $this->mockTable($store); $store->expects($this->once())->method('getTime')->willReturn(0); - $table->expects('where')->times(2)->andReturn($table); - $table->expects('update')->with(['expiration' => 60])->andReturn(1); + $table->expects('where')->times(2)->returns($table); + $table->expects('update')->with(['expiration' => 60])->returns(1); $this->assertTrue($store->touch('foo', 60)); } @@ -458,8 +417,8 @@ public function testTouchExtendsTtlOnPostgres(): void [$table] = $this->mockTable($store); $store->expects($this->once())->method('getTime')->willReturn(0); - $table->expects('where')->times(2)->andReturn($table); - $table->expects('update')->with(['expiration' => 60])->andReturn(1); + $table->expects('where')->times(2)->returns($table); + $table->expects('update')->with(['expiration' => 60])->returns(1); $this->assertTrue($store->touch('foo', 60)); } @@ -472,8 +431,8 @@ public function testTouchExtendsTtlOnSqlite(): void [$table] = $this->mockTable($store); $store->expects($this->once())->method('getTime')->willReturn(0); - $table->expects('where')->times(2)->andReturn($table); - $table->expects('update')->with(['expiration' => 60])->andReturn(1); + $table->expects('where')->times(2)->returns($table); + $table->expects('update')->with(['expiration' => 60])->returns(1); $this->assertTrue($store->touch('foo', 60)); } @@ -484,7 +443,7 @@ public function testSupportsFlushingLocksRequiresSeparateLockTable(): void $this->assertTrue($store->supportsFlushingLocks()); - $store = new DatabaseStore(m::mock(ConnectionResolverInterface::class), 'default', 'cache', '', 'cache'); + $store = new DatabaseStore(Double::for(ConnectionResolverInterface::class), 'default', 'cache', '', 'cache'); $this->assertFalse($store->supportsFlushingLocks()); } @@ -494,8 +453,8 @@ public function testPruneExpiredRemovesExpiredEntries(): void CarbonImmutable::setTestNow($now = CarbonImmutable::now()); [$store, $table] = $this->getStore(); - $table->shouldReceive('where')->once()->with('expiration', '<=', $now->getTimestamp())->andReturn($table); - $table->shouldReceive('delete')->once()->andReturn(5); + $table->expects('where')->with('expiration', '<=', $now->getTimestamp())->returns($table); + $table->expects('delete')->returns(5); $this->assertSame(5, $store->pruneExpired()); } @@ -513,12 +472,12 @@ protected function getStore( array|bool|null $serializableClasses = null, ?SerializableClassPolicy $serializableClassPolicy = null, ): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $table = m::mock(Builder::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $table = Double::for(Builder::class); - $resolver->shouldReceive('connection')->with('default')->andReturn($connection); - $connection->shouldReceive('table')->with('table')->andReturn($table); + $resolver->allows('connection')->with('default')->returns($connection); + $connection->allows('table')->with('table')->returns($table); $store = new DatabaseStore( $resolver, @@ -537,12 +496,12 @@ protected function getStore( */ protected function getPostgresStore(): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(PostgresConnection::class); - $table = m::mock(Builder::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(PostgresConnection::class); + $table = Double::for(Builder::class); - $resolver->shouldReceive('connection')->with('default')->andReturn($connection); - $connection->shouldReceive('table')->with('table')->andReturn($table); + $resolver->allows('connection')->with('default')->returns($connection); + $connection->allows('table')->with('table')->returns($table); $store = new DatabaseStore($resolver, 'default', 'table', 'prefix'); @@ -554,12 +513,12 @@ protected function getPostgresStore(): array */ protected function getSqliteStore(): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(SQLiteConnection::class); - $table = m::mock(Builder::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(SQLiteConnection::class); + $table = Double::for(Builder::class); - $resolver->shouldReceive('connection')->with('default')->andReturn($connection); - $connection->shouldReceive('table')->with('table')->andReturn($table); + $resolver->allows('connection')->with('default')->returns($connection); + $connection->allows('table')->with('table')->returns($table); $store = new DatabaseStore($resolver, 'default', 'table', 'prefix'); @@ -571,8 +530,8 @@ protected function getSqliteStore(): array */ protected function getMocks(): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with('default')->andReturn(m::mock(Connection::class)); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->with('default')->returns(Double::for(Connection::class)); return [$resolver, 'default', 'table', 'prefix']; } @@ -582,8 +541,8 @@ protected function getMocks(): array */ protected function getPostgresMocks(): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with('default')->andReturn(m::mock(PostgresConnection::class)); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->with('default')->returns(Double::for(PostgresConnection::class)); return [$resolver, 'default', 'table', 'prefix']; } @@ -593,8 +552,8 @@ protected function getPostgresMocks(): array */ protected function getSqliteMocks(): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with('default')->andReturn(m::mock(SQLiteConnection::class)); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->with('default')->returns(Double::for(SQLiteConnection::class)); return [$resolver, 'default', 'table', 'prefix']; } @@ -609,9 +568,9 @@ protected function getSqliteMocks(): array */ protected function mockTable(DatabaseStore $store): array { - $table = m::mock(Builder::class); + $table = Double::for(Builder::class); $connection = $store->getConnection(); - $connection->shouldReceive('table')->with('table')->andReturn($table); + $connection->allows('table')->with('table')->returns($table); return [$table]; } diff --git a/tests/Cache/CacheEventsTest.php b/tests/Cache/CacheEventsTest.php index 02c28fb2a..0e2bf47c3 100644 --- a/tests/Cache/CacheEventsTest.php +++ b/tests/Cache/CacheEventsTest.php @@ -33,7 +33,8 @@ use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; use Hypervel\Events\Dispatcher; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -41,6 +42,8 @@ class CacheEventsTest extends TestCase { + use VerifiesDoubles; + public function testRepositorySkipsEventDispatchSeamWithoutListenersAndEntersItWithListeners(): void { $repository = new class(new ArrayStore, ['store' => 'array']) extends Repository { @@ -56,9 +59,9 @@ protected function event(object $event): void parent::event($event); } }; - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->withAnyArgs()->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(DispatcherContract::class); + $dispatcher->allows('hasListeners')->returns(false); + $dispatcher->expects('dispatch')->never(); $repository->setEventDispatcher($dispatcher); $this->assertNull($repository->get('missing')); @@ -93,9 +96,9 @@ protected function event(object $event): void parent::event($event); } }; - $dispatcher = m::mock(DispatcherContract::class); - $dispatcher->shouldReceive('hasListeners')->withAnyArgs()->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(DispatcherContract::class); + $dispatcher->allows('hasListeners')->returns(false); + $dispatcher->expects('dispatch')->never(); $repository->setEventDispatcher($dispatcher); $this->assertNull($repository->get('missing')); @@ -186,8 +189,8 @@ public function testTaggedManyTriggersManyEvents(): void public function testGetDispatchesFailureEventWhenTheStoreThrows(): void { $exception = new RuntimeException('The cache read failed.'); - $store = m::mock(Store::class); - $store->expects('get')->with('foo')->andThrow($exception); + $store = Double::for(Store::class); + $store->expects('get')->with('foo')->throws($exception); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -211,8 +214,8 @@ public function testGetDispatchesFailureEventWhenTheStoreThrows(): void public function testManyDispatchesFailureEventWhenTheStoreThrows(): void { $exception = new RuntimeException('The cache batch read failed.'); - $store = m::mock(Store::class); - $store->expects('many')->with(['foo', 'bar'])->andThrow($exception); + $store = Double::for(Store::class); + $store->expects('many')->with(['foo', 'bar'])->throws($exception); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -236,8 +239,8 @@ public function testManyDispatchesFailureEventWhenTheStoreThrows(): void public function testPutDispatchesFailureEventWhenTheStoreThrows(): void { $exception = new RuntimeException('The cache write failed.'); - $store = m::mock(Store::class); - $store->expects('put')->with('foo', 'bar', 60)->andThrow($exception); + $store = Double::for(Store::class); + $store->expects('put')->with('foo', 'bar', 60)->throws($exception); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -266,8 +269,8 @@ public function testFalseWriteResultDispatchesFailureEventsWithoutException( array $eventClasses, array $keys, ): void { - $store = m::mock(Store::class); - $store->expects($method)->with(...$arguments)->andReturnFalse(); + $store = Double::for(Store::class); + $store->expects($method)->with(...$arguments)->returns(false); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -299,8 +302,8 @@ public function testPutManyDispatchesFailureEventsWhenTheStoreThrows(): void { $exception = new RuntimeException('The cache batch write failed.'); $values = ['foo' => 'bar', 'baz' => 'qux']; - $store = m::mock(Store::class); - $store->expects('putMany')->with($values, 60)->andThrow($exception); + $store = Double::for(Store::class); + $store->expects('putMany')->with($values, 60)->throws($exception); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -324,8 +327,8 @@ public function testPutManyDispatchesFailureEventsWhenTheStoreThrows(): void public function testForeverDispatchesFailureEventWhenTheStoreThrows(): void { $exception = new RuntimeException('The cache forever write failed.'); - $store = m::mock(Store::class); - $store->expects('forever')->with('foo', 'bar')->andThrow($exception); + $store = Double::for(Store::class); + $store->expects('forever')->with('foo', 'bar')->throws($exception); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -349,8 +352,8 @@ public function testForeverDispatchesFailureEventWhenTheStoreThrows(): void public function testForgetDispatchesFailureEventWhenTheStoreThrows(): void { $exception = new RuntimeException('The cache forget failed.'); - $store = m::mock(Store::class); - $store->expects('forget')->with('foo')->andThrow($exception); + $store = Double::for(Store::class); + $store->expects('forget')->with('foo')->throws($exception); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -383,11 +386,11 @@ public function testCancellationDoesNotDispatchFailureEvents( if ($cleanupThrows) { $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } - $store = m::mock(Store::class, CanFlushLocks::class, AuthoritativeRawReadable::class); - $store->shouldReceive('supportsFlushingLocks')->andReturnTrue()->byDefault(); + $store = Double::for(Store::class, CanFlushLocks::class, AuthoritativeRawReadable::class); + $store->allows('supportsFlushingLocks')->returns(true); $store->expects($storeMethod) ->with(...$storeArguments) - ->andThrow($cancellation); + ->throws($cancellation); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -577,8 +580,8 @@ public function testForgetTriggersEvents(): void public function testForgetDoesTriggerFailedEventOnFailure(): void { $dispatcher = $this->getDispatcher(); - $store = m::mock(Store::class); - $store->expects('forget')->andReturn(false); + $store = Double::for(Store::class); + $store->expects('forget')->returns(false); $repository = new Repository($store); $repository->setEventDispatcher($dispatcher); @@ -620,8 +623,8 @@ public function testEmptyTaggedFlushIsIdempotentAndDispatchesSuccessEvents(): vo public function testFlushDispatchesFailureEventWithExactException(): void { $exception = new RuntimeException('The cache flush failed.'); - $store = m::mock(Store::class); - $store->expects('flush')->andThrow($exception); + $store = Double::for(Store::class); + $store->expects('flush')->throws($exception); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -652,9 +655,9 @@ public function testFlushLocksTriggersEvents(): void public function testFlushLocksDispatchesFailureEventWithExactException(): void { $exception = new RuntimeException('The cache lock flush failed.'); - $store = m::mock(Store::class, CanFlushLocks::class); - $store->expects('supportsFlushingLocks')->andReturnTrue(); - $store->expects('flushLocks')->andThrow($exception); + $store = Double::for(Store::class, CanFlushLocks::class); + $store->expects('supportsFlushingLocks')->returns(true); + $store->expects('flushLocks')->throws($exception); $events = []; $repository = new Repository($store, ['store' => 'array']); $repository->setEventDispatcher($this->getCapturingDispatcher($events)); @@ -678,8 +681,8 @@ public function testFlushFailureDoesDispatchEvent(): void $dispatcher = $this->getDispatcher(); // Create a store that fails to flush - $failingStore = m::mock(Store::class); - $failingStore->expects('flush')->andReturn(false); + $failingStore = Double::for(Store::class); + $failingStore->expects('flush')->returns(false); $repository = new Repository($failingStore, ['store' => 'array']); $repository->setEventDispatcher($dispatcher); @@ -696,9 +699,9 @@ public function testFlushLocksFailureDoesDispatchEvent(): void $dispatcher = $this->getDispatcher(); // Create a store that fails to flush locks - $failingStore = m::mock(ArrayStore::class); - $failingStore->shouldReceive('supportsFlushingLocks')->andReturn(true); - $failingStore->expects('flushLocks')->andReturn(false); + $failingStore = Double::for(ArrayStore::class); + $failingStore->allows('supportsFlushingLocks')->returns(true); + $failingStore->expects('flushLocks')->returns(false); $repository = new Repository($failingStore, ['store' => 'array']); $repository->setEventDispatcher($dispatcher); diff --git a/tests/Cache/CacheFailoverStoreTest.php b/tests/Cache/CacheFailoverStoreTest.php index aa7d77676..13360083b 100644 --- a/tests/Cache/CacheFailoverStoreTest.php +++ b/tests/Cache/CacheFailoverStoreTest.php @@ -22,7 +22,9 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Events\Dispatcher as EventDispatcher; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -32,6 +34,8 @@ class CacheFailoverStoreTest extends TestCase { + use VerifiesDoubles; + public function testImplementsCanFlushLocks(): void { $store = $this->makeFailoverStore([]); @@ -47,9 +51,9 @@ public function testFlushLocksCallsFlushLocksOnAllBackingStores(): void $this->assertTrue($storeA->lock('lock-a', 60)->get()); $this->assertTrue($storeB->lock('lock-b', 60)->get()); - $cache = m::mock(CacheManager::class); - $cache->expects('store')->with('store-a')->andReturn(new Repository($storeA)); - $cache->expects('store')->with('store-b')->andReturn(new Repository($storeB)); + $cache = Double::for(CacheManager::class); + $cache->expects('store')->with('store-a')->returns(new Repository($storeA)); + $cache->expects('store')->with('store-b')->returns(new Repository($storeB)); $failover = new FailoverStore($cache, new EventDispatcher, ['store-a', 'store-b']); @@ -81,8 +85,8 @@ public function testIncompleteClassHandlerRunsOnceAcrossFailoverRepositories(): public function testAuthoritativeReadDelegatesToCapableRepository(): void { - $backingStore = m::mock(Store::class, AuthoritativeRawReadable::class); - $backingStore->shouldReceive('getAuthoritativeRaw')->once()->with('key')->andReturn(NullSentinel::VALUE); + $backingStore = Double::for(Store::class, AuthoritativeRawReadable::class); + $backingStore->expects('getAuthoritativeRaw')->with('key')->returns(NullSentinel::VALUE); $store = $this->makeFailoverStore(['cache' => $backingStore]); @@ -123,12 +127,13 @@ public function testAuthoritativeReadRecursesThroughMemoizedFailoverAndStack(): public function testAuthoritativeReadFailsOverAfterStoreFailure(): void { $failure = new RuntimeException('primary unavailable'); - $primary = m::mock(Store::class, AuthoritativeRawReadable::class); - $primary->shouldReceive('getAuthoritativeRaw')->once()->with('key')->andThrow($failure); - $secondary = m::mock(Store::class, AuthoritativeRawReadable::class); - $secondary->shouldReceive('getAuthoritativeRaw')->once()->with('key')->andReturn('value'); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(CacheFailedOver::class)->andReturnFalse(); + $primary = Double::for(Store::class, AuthoritativeRawReadable::class); + $primary->expects('getAuthoritativeRaw')->with('key')->throws($failure); + $secondary = Double::for(Store::class, AuthoritativeRawReadable::class); + $secondary->expects('getAuthoritativeRaw')->with('key')->returns('value'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(CacheFailedOver::class)->returns(false); + $events->expects('dispatch')->never(); $store = $this->makeFailoverStore( ['primary' => $primary, 'secondary' => $secondary], @@ -140,13 +145,13 @@ public function testAuthoritativeReadFailsOverAfterStoreFailure(): void public function testRawReadsFallBackToContractRepositoryWithLossyNullSemantics(): void { - $repository = m::mock(RepositoryContract::class); - $repository->shouldReceive('get')->once()->with('key')->andReturn('value'); - $repository->shouldReceive('get')->once()->with(['cached-null', 'miss'])->andReturn([ + $repository = Double::for(RepositoryContract::class); + $repository->expects('get')->with('key')->returns('value'); + $repository->expects('get')->with(['cached-null', 'miss'])->returns([ 'cached-null' => null, 'miss' => null, ]); - $repository->shouldReceive('get')->once()->with('null')->andReturnNull(); + $repository->expects('get')->with('null')->returns(null); $store = $this->makeFailoverStore(['custom' => $repository]); @@ -162,9 +167,9 @@ public function testRawReadsFallBackToContractRepositoryWithLossyNullSemantics() public function testCountersPreserveEveryContractValidResult(): void { - $backingStore = m::mock(Store::class); - $backingStore->expects('increment')->with('increment', 2)->andReturnTrue(); - $backingStore->expects('decrement')->with('decrement', 3)->andReturnFalse(); + $backingStore = Double::for(Store::class); + $backingStore->expects('increment')->with('increment', 2)->returns(true); + $backingStore->expects('decrement')->with('decrement', 3)->returns(false); $store = $this->makeFailoverStore(['cache' => $backingStore]); $this->assertTrue($store->increment('increment', 2)); @@ -175,7 +180,7 @@ public function testCountersPreserveEveryContractValidResult(): void public function testLockFlushCapabilityRequiresAtLeastOneLockProvider(bool $hasStore): void { $store = $this->makeFailoverStore($hasStore ? [ - 'plain' => m::mock(Store::class), + 'plain' => Double::for(Store::class), ] : []); $this->assertFalse($store->supportsFlushingLocks()); @@ -201,12 +206,12 @@ public static function storesWithoutLockProviders(): array public function testLockFlushCapabilityRequiresEveryLockProviderToSupportFlushing(): void { $flushable = $this->lockStore(); - $flushable->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); + $flushable->expects('supportsFlushingLocks')->returns(true); - $unsupported = m::mock(implode(',', [Store::class, LockProvider::class])); + $unsupported = Double::for(Store::class, LockProvider::class); $store = $this->makeFailoverStore([ - 'plain' => m::mock(Store::class), + 'plain' => Double::for(Store::class), 'flushable' => $flushable, 'unsupported' => $unsupported, ]); @@ -217,10 +222,10 @@ public function testLockFlushCapabilityRequiresEveryLockProviderToSupportFlushin public function testLockFlushCapabilityRequiresEveryFlushableStoreToBeCurrentlySupported(): void { $supported = $this->lockStore(); - $supported->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); + $supported->expects('supportsFlushingLocks')->returns(true); $unsupported = $this->lockStore(); - $unsupported->shouldReceive('supportsFlushingLocks')->once()->andReturnFalse(); + $unsupported->expects('supportsFlushingLocks')->returns(false); $store = $this->makeFailoverStore([ 'supported' => $supported, @@ -233,13 +238,13 @@ public function testLockFlushCapabilityRequiresEveryFlushableStoreToBeCurrentlyS public function testLockFlushCapabilityIsTrueWhenEveryLockProviderSupportsIt(): void { $first = $this->lockStore(); - $first->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); + $first->expects('supportsFlushingLocks')->returns(true); $second = $this->lockStore(); - $second->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); + $second->expects('supportsFlushingLocks')->returns(true); $store = $this->makeFailoverStore([ - 'plain' => m::mock(Store::class), + 'plain' => Double::for(Store::class), 'first' => $first, 'second' => $second, ]); @@ -250,12 +255,12 @@ public function testLockFlushCapabilityIsTrueWhenEveryLockProviderSupportsIt(): public function testFlushLocksPreflightsEveryLockProviderBeforeChangingState(): void { $first = $this->lockStore(); - $first->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); - $first->shouldNotReceive('flushLocks'); + $first->expects('supportsFlushingLocks')->returns(true); + $first->expects('flushLocks')->never(); $second = $this->lockStore(); - $second->shouldReceive('supportsFlushingLocks')->once()->andReturnFalse(); - $second->shouldNotReceive('flushLocks'); + $second->expects('supportsFlushingLocks')->returns(false); + $second->expects('flushLocks')->never(); $store = $this->makeFailoverStore([ 'first' => $first, @@ -274,12 +279,12 @@ public function testFlushLocksPreflightsEveryLockProviderBeforeChangingState(): public function testFlushLocksAttemptsEveryStoreAndAggregatesFalseResults(): void { $first = $this->lockStore(); - $first->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); - $first->shouldReceive('flushLocks')->once()->andReturnFalse(); + $first->expects('supportsFlushingLocks')->returns(true); + $first->expects('flushLocks')->returns(false); $second = $this->lockStore(); - $second->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); - $second->shouldReceive('flushLocks')->once()->andReturnTrue(); + $second->expects('supportsFlushingLocks')->returns(true); + $second->expects('flushLocks')->returns(true); $store = $this->makeFailoverStore([ 'first' => $first, @@ -292,12 +297,12 @@ public function testFlushLocksAttemptsEveryStoreAndAggregatesFalseResults(): voi public function testFlushLocksAttemptsEveryStoreAndPreservesTheEarliestFailure(): void { $first = $this->lockStore(); - $first->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); - $first->shouldReceive('flushLocks')->once()->andThrow(new RuntimeException('first failure')); + $first->expects('supportsFlushingLocks')->returns(true); + $first->expects('flushLocks')->throws(new RuntimeException('first failure')); $second = $this->lockStore(); - $second->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); - $second->shouldReceive('flushLocks')->once()->andThrow(new RuntimeException('second failure')); + $second->expects('supportsFlushingLocks')->returns(true); + $second->expects('flushLocks')->throws(new RuntimeException('second failure')); $store = $this->makeFailoverStore([ 'first' => $first, @@ -319,11 +324,11 @@ public function testFlushLocksStopsAtCancellation(bool $cleanupThrows): void $cancellation = new RuntimeException('Lock cleanup failed.', previous: $cancellation); } $first = $this->lockStore(); - $first->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); - $first->shouldReceive('flushLocks')->once()->andThrow($cancellation); + $first->expects('supportsFlushingLocks')->returns(true); + $first->expects('flushLocks')->throws($cancellation); $second = $this->lockStore(); - $second->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); - $second->shouldNotReceive('flushLocks'); + $second->expects('supportsFlushingLocks')->returns(true); + $second->expects('flushLocks')->never(); $store = $this->makeFailoverStore([ 'first' => $first, 'second' => $second, @@ -345,16 +350,16 @@ public function testFirstSuccessOperationDoesNotFailOverAfterCancellation(bool $ if ($cleanupThrows) { $cancellation = new RuntimeException('Read cleanup failed.', previous: $cancellation); } - $first = m::mock(Store::class); - $first->shouldReceive('get')->once()->with('key')->andThrow(new RuntimeException('first failure')); - $second = m::mock(Store::class); - $second->shouldReceive('get')->once()->with('key')->andThrow($cancellation); - $third = m::mock(Store::class); - $third->shouldNotReceive('get'); + $first = Double::for(Store::class); + $first->expects('get')->with('key')->throws(new RuntimeException('first failure')); + $second = Double::for(Store::class); + $second->expects('get')->with('key')->throws($cancellation); + $third = Double::for(Store::class); + $third->expects('get')->never(); $failedStores = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(CacheFailedOver::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->once()->andReturnUsing( + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(CacheFailedOver::class)->returns(true); + $events->expects('dispatch')->resolves( function (CacheFailedOver $event) use (&$failedStores): void { $failedStores[] = $event->storeName; } @@ -382,12 +387,12 @@ public function testEveryStoreOperationDoesNotContinueAfterCancellation(bool $cl if ($cleanupThrows) { $cancellation = new RuntimeException('Forget cleanup failed.', previous: $cancellation); } - $first = m::mock(Store::class); - $first->shouldReceive('forget')->once()->with('key')->andReturnTrue(); - $second = m::mock(Store::class); - $second->shouldReceive('forget')->once()->with('key')->andThrow($cancellation); - $third = m::mock(Store::class); - $third->shouldNotReceive('forget'); + $first = Double::for(Store::class); + $first->expects('forget')->with('key')->returns(true); + $second = Double::for(Store::class); + $second->expects('forget')->with('key')->throws($cancellation); + $third = Double::for(Store::class); + $third->expects('forget')->never(); $store = $this->makeFailoverStore([ 'first' => $first, 'second' => $second, @@ -405,19 +410,19 @@ public function testEveryStoreOperationDoesNotContinueAfterCancellation(bool $cl public function testFirstSuccessListenerFailurePreservesObservedAndUnattemptedFailures(): void { $listenerFailure = new RuntimeException('listener failure'); - $first = m::mock(Store::class); - $first->shouldReceive('forget')->once()->with('key')->andReturnTrue(); - $first->shouldReceive('get')->twice()->with('key')->andThrow(new RuntimeException('first failure')); - $second = m::mock(Store::class); - $second->shouldReceive('forget')->once()->with('key')->andThrow(new RuntimeException('second failure')); - $second->shouldReceive('get')->once()->with('key')->andThrow(new RuntimeException('second failure')); - $third = m::mock(Store::class); - $third->shouldReceive('forget')->once()->with('key')->andReturnTrue(); - $third->shouldReceive('get')->once()->with('key')->andReturn('value'); + $first = Double::for(Store::class); + $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->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->expects('forget')->with('key')->returns(true); + $third->expects('get')->with('key')->returns('value'); $failedStores = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->with(CacheFailedOver::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->andReturnUsing( + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->with(CacheFailedOver::class)->returns(true); + $events->allows('dispatch')->resolves( function (CacheFailedOver $event) use (&$failedStores, $listenerFailure): void { $failedStores[] = $event->storeName; @@ -448,8 +453,8 @@ public function testEveryStoreListenerFailurePreservesObservedAndUnattemptedFail { $listenerFailure = new RuntimeException('listener failure'); $firstCall = 0; - $first = m::mock(Store::class); - $first->shouldReceive('forget')->times(3)->with('key')->andReturnUsing( + $first = Double::for(Store::class); + $first->expects('forget')->times(3)->with('key')->resolves( function () use (&$firstCall): bool { ++$firstCall; @@ -458,14 +463,14 @@ function () use (&$firstCall): bool { : throw new RuntimeException('first failure'); } ); - $second = m::mock(Store::class); - $second->shouldReceive('forget')->twice()->with('key')->andThrow(new RuntimeException('second failure')); - $third = m::mock(Store::class); - $third->shouldReceive('forget')->twice()->with('key')->andReturnTrue(); + $second = Double::for(Store::class); + $second->expects('forget')->times(2)->with('key')->throws(new RuntimeException('second failure')); + $third = Double::for(Store::class); + $third->expects('forget')->times(2)->with('key')->returns(true); $failedStores = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->with(CacheFailedOver::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->andReturnUsing( + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->with(CacheFailedOver::class)->returns(true); + $events->allows('dispatch')->resolves( function (CacheFailedOver $event) use (&$failedStores, $listenerFailure): void { $failedStores[] = $event->storeName; @@ -500,28 +505,28 @@ public function testListenerInterruptionPreservesUnattemptedFailureHistoryWithSp $thirdFailure = new RuntimeException('third failure'); $firstCall = 0; $secondCall = 0; - $first = m::mock(Store::class); - $first->shouldReceive('forget')->times(3)->with('key')->andReturnUsing( + $first = Double::for(Store::class); + $first->expects('forget')->times(3)->with('key')->resolves( function () use (&$firstCall, $firstFailure): bool { ++$firstCall; return $firstCall === 1 ? true : throw $firstFailure; } ); - $second = m::mock(Store::class); - $second->shouldReceive('forget')->times(3)->with('key')->andReturnUsing( + $second = Double::for(Store::class); + $second->expects('forget')->times(3)->with('key')->resolves( function () use (&$secondCall, $secondFailure): bool { ++$secondCall; return $secondCall === 1 ? true : throw $secondFailure; } ); - $third = m::mock(Store::class); - $third->shouldReceive('forget')->twice()->with('key')->andThrow($thirdFailure); + $third = Double::for(Store::class); + $third->expects('forget')->times(2)->with('key')->throws($thirdFailure); $failedStores = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->with(CacheFailedOver::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->andReturnUsing( + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->with(CacheFailedOver::class)->returns(true); + $events->allows('dispatch')->resolves( function (CacheFailedOver $event) use (&$failedStores, $listenerFailure): void { $failedStores[] = $event->storeName; @@ -557,16 +562,16 @@ function (CacheFailedOver $event) use (&$failedStores, $listenerFailure): void { public function testReplacementStoreReportsItsOwnFirstFailure(): void { - $cache = m::mock(CacheManager::class); - $events = m::mock(Dispatcher::class); - $primary = m::mock(RepositoryContract::class); - $secondary = m::mock(RepositoryContract::class); - $primary->allows('get')->andThrow(new RuntimeException('Primary unavailable.')); - $secondary->allows('get')->andReturn('value'); - $cache->allows('store')->with('primary')->andReturn($primary); - $cache->allows('store')->with('secondary')->andReturn($secondary); - $events->allows('hasListeners')->with(CacheFailedOver::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->twice()->with(m::type(CacheFailedOver::class)); + $cache = Double::for(CacheManager::class); + $events = Double::for(Dispatcher::class); + $primary = Double::for(RepositoryContract::class); + $secondary = Double::for(RepositoryContract::class); + $primary->allows('get')->throws(new RuntimeException('Primary unavailable.')); + $secondary->allows('get')->returns('value'); + $cache->allows('store')->with('primary')->returns($primary); + $cache->allows('store')->with('secondary')->returns($secondary); + $events->allows('hasListeners')->with(CacheFailedOver::class)->returns(true); + $events->expects('dispatch')->times(2)->with(Argument::type(CacheFailedOver::class)); $store = new FailoverStore($cache, $events, ['primary', 'secondary']); $this->assertSame('value', $store->get('key')); @@ -579,14 +584,14 @@ public function testReplacementStoreReportsItsOwnFirstFailure(): void public function testFailoverEventCarriesLogicalAndFailedBackingStoreNames(): void { $exception = new RuntimeException('primary unavailable'); - $first = m::mock(Store::class); - $first->shouldReceive('get')->once()->with('key')->andThrow($exception); - $second = m::mock(Store::class); - $second->shouldReceive('get')->once()->with('key')->andReturn('value'); + $first = Double::for(Store::class); + $first->expects('get')->with('key')->throws($exception); + $second = Double::for(Store::class); + $second->expects('get')->with('key')->returns('value'); $captured = null; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(CacheFailedOver::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->once()->andReturnUsing(function (CacheFailedOver $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(CacheFailedOver::class)->returns(true); + $events->expects('dispatch')->resolves(function (CacheFailedOver $event) use (&$captured): void { $captured = $event; }); @@ -606,13 +611,13 @@ public function testFailoverEventCarriesLogicalAndFailedBackingStoreNames(): voi public function testSeparateLockStoreReportingRequiresEveryLockProviderToBeSeparate(): void { $separate = $this->lockStore(); - $separate->shouldReceive('hasSeparateLockStore')->once()->andReturnTrue(); + $separate->expects('hasSeparateLockStore')->returns(true); $shared = $this->lockStore(); - $shared->shouldReceive('hasSeparateLockStore')->once()->andReturnFalse(); + $shared->expects('hasSeparateLockStore')->returns(false); $store = $this->makeFailoverStore([ - 'plain' => m::mock(Store::class), + 'plain' => Double::for(Store::class), 'separate' => $separate, 'shared' => $shared, ]); @@ -623,13 +628,13 @@ public function testSeparateLockStoreReportingRequiresEveryLockProviderToBeSepar public function testSeparateLockStoreReportingIsTrueWhenEveryLockProviderIsSeparate(): void { $first = $this->lockStore(); - $first->shouldReceive('hasSeparateLockStore')->once()->andReturnTrue(); + $first->expects('hasSeparateLockStore')->returns(true); $second = $this->lockStore(); - $second->shouldReceive('hasSeparateLockStore')->once()->andReturnTrue(); + $second->expects('hasSeparateLockStore')->returns(true); $store = $this->makeFailoverStore([ - 'plain' => m::mock(Store::class), + 'plain' => Double::for(Store::class), 'first' => $first, 'second' => $second, ]); @@ -649,12 +654,12 @@ protected function makeFailoverStore( ?array $storeNames = null, ?string $failoverStoreName = null, ): FailoverStore { - $cache = m::mock(CacheManager::class); + $cache = Double::for(CacheManager::class); foreach ($stores as $name => $store) { - $cache->shouldReceive('store') + $cache->allows('store') ->with($name) - ->andReturn($store instanceof RepositoryContract ? $store : new Repository($store)); + ->returns($store instanceof RepositoryContract ? $store : new Repository($store)); } return new FailoverStore( @@ -670,6 +675,6 @@ protected function makeFailoverStore( */ protected function lockStore(): Store&LockProvider&CanFlushLocks { - return m::mock(implode(',', [Store::class, LockProvider::class, CanFlushLocks::class])); + return Double::for(Store::class, LockProvider::class, CanFlushLocks::class); } } diff --git a/tests/Cache/CacheFileStoreTest.php b/tests/Cache/CacheFileStoreTest.php index da4139d13..5eca6794a 100644 --- a/tests/Cache/CacheFileStoreTest.php +++ b/tests/Cache/CacheFileStoreTest.php @@ -20,7 +20,9 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Cache\Fixtures\CanceledDeserialization; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\MockObject\MockObject; use ReflectionProperty; @@ -32,6 +34,8 @@ class CacheFileStoreTest extends TestCase { + use VerifiesDoubles; + protected string $tempDir; protected Filesystem $filesystem; @@ -365,8 +369,8 @@ public function testSerializableClassPolicyControlsCachedObjects(): void public function testLockStoreRetainsBothSerializationPolicies(): void { - $files = m::mock(Filesystem::class)->shouldIgnoreMissing(); - $files->shouldReceive('exists')->andReturnTrue(); + $files = Double::for(Filesystem::class); + $files->allows('exists')->returns(true); $serializableClasses = [stdClass::class]; $policy = new SerializableClassPolicy(static fn (): false => false); $store = new FileStore( @@ -563,15 +567,16 @@ public function testTouchExtendsTtl(): void public function testStoreItemProperlySetsPermissions(): void { - $files = m::mock(Filesystem::class)->shouldIgnoreMissing(); + $files = Double::for(Filesystem::class); $store = new FileStore($files, __DIR__, 0644); + $files->allows('exists')->returns(true); $hash = hash('xxh128', 'foo'); $cache_dir = substr($hash, 0, 2) . '/' . substr($hash, 2, 2); - $files->expects('put')->times(3)->withArgs([__DIR__ . '/' . $cache_dir . '/' . $hash, m::any(), m::any()])->andReturnUsing(function (string $name, string $value): int { + $files->expects('put')->times(3)->with(__DIR__ . '/' . $cache_dir . '/' . $hash, Argument::any(), Argument::any())->resolves(function (string $name, string $value): int { return strlen($value); }); - $files->expects('chmod')->withArgs([__DIR__ . '/' . $cache_dir . '/' . $hash])->andReturnValues(['0600', '0644'])->times(3); - $files->expects('chmod')->withArgs([__DIR__ . '/' . $cache_dir . '/' . $hash, 0644])->andReturn(true); + $files->expects('chmod')->with(__DIR__ . '/' . $cache_dir . '/' . $hash)->returns('0600', '0644')->times(3); + $files->expects('chmod')->with(__DIR__ . '/' . $cache_dir . '/' . $hash, 0644)->returns(true); $result = $store->put('foo', 'foo', 10); $this->assertTrue($result); $result = $store->put('foo', 'bar', 10); @@ -582,22 +587,23 @@ public function testStoreItemProperlySetsPermissions(): void public function testStoreItemDirectoryProperlySetsPermissions(): void { - $files = m::mock(Filesystem::class)->shouldIgnoreMissing(); + $files = Double::for(Filesystem::class); $store = new FileStore($files, __DIR__, 0606); $hash = hash('xxh128', 'foo'); $cache_parent_dir = substr($hash, 0, 2); $cache_dir = $cache_parent_dir . '/' . substr($hash, 2, 2); - $files->expects('put')->withArgs([__DIR__ . '/' . $cache_dir . '/' . $hash, m::any(), m::any()])->andReturnUsing(function (string $name, string $value): int { + $files->expects('put')->with(__DIR__ . '/' . $cache_dir . '/' . $hash, Argument::any(), Argument::any())->resolves(function (string $name, string $value): int { return strlen($value); }); - $files->expects('exists')->withArgs([__DIR__ . '/' . $cache_dir])->andReturn(false); - $files->expects('makeDirectory')->withArgs([__DIR__ . '/' . $cache_dir, 0777, true, true]); - $files->expects('chmod')->withArgs([__DIR__ . '/' . $cache_parent_dir])->andReturn('0600'); - $files->expects('chmod')->withArgs([__DIR__ . '/' . $cache_parent_dir, 0606])->andReturn(true); - $files->expects('chmod')->withArgs([__DIR__ . '/' . $cache_dir])->andReturn('0600'); - $files->expects('chmod')->withArgs([__DIR__ . '/' . $cache_dir, 0606])->andReturn(true); + $files->expects('exists')->with(__DIR__ . '/' . $cache_dir)->returns(false); + $files->expects('chmod')->with(__DIR__ . '/' . $cache_dir . '/' . $hash)->returns('0606'); + $files->expects('makeDirectory')->with(__DIR__ . '/' . $cache_dir, 0777, true, true); + $files->expects('chmod')->with(__DIR__ . '/' . $cache_parent_dir)->returns('0600'); + $files->expects('chmod')->with(__DIR__ . '/' . $cache_parent_dir, 0606)->returns(true); + $files->expects('chmod')->with(__DIR__ . '/' . $cache_dir)->returns('0600'); + $files->expects('chmod')->with(__DIR__ . '/' . $cache_dir, 0606)->returns(true); $result = $store->put('foo', 'foo', 10); $this->assertTrue($result); diff --git a/tests/Cache/CacheManagerTest.php b/tests/Cache/CacheManagerTest.php index 5ed82a37d..7c5148400 100644 --- a/tests/Cache/CacheManagerTest.php +++ b/tests/Cache/CacheManagerTest.php @@ -36,8 +36,8 @@ use Hypervel\Tests\Cache\Fixtures\ArrayFilesystem; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Redis; use ReflectionProperty; @@ -47,6 +47,7 @@ class CacheManagerTest extends TestCase { use InteractsWithSwooleTables; + use VerifiesDoubles; public function testCustomDriverClosureBoundObjectIsCacheManager(): void { @@ -123,9 +124,8 @@ public function testCustomDriverOverridesInternalDrivers(): void $app = $this->getApp($userConfig); $cacheManager = new CacheManager($app); - /** @var CacheRepository&MockInterface */ - $repository = m::mock(CacheRepository::class); - $repository->shouldReceive('get')->with('foo')->andReturn('bar'); + $repository = Double::for(CacheRepository::class); + $repository->allows('get')->with('foo')->returns('bar'); $cacheManager->extend('array', fn (): CacheRepository => $repository); @@ -179,14 +179,14 @@ public function testFailoverDriverPassesItsConfiguredNameToFailoverEvents(): voi ], ]); $failure = new RuntimeException('primary unavailable'); - $primary = m::mock(Store::class); - $primary->expects('get')->with('key')->andThrow($failure); - $secondary = m::mock(Store::class); - $secondary->expects('get')->with('key')->andReturn('value'); + $primary = Double::for(Store::class); + $primary->expects('get')->with('key')->throws($failure); + $secondary = Double::for(Store::class); + $secondary->expects('get')->with('key')->returns('value'); $captured = null; - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(CacheFailedOver::class)->andReturnTrue(); - $events->expects('dispatch')->andReturnUsing(function (CacheFailedOver $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(CacheFailedOver::class)->returns(true); + $events->expects('dispatch')->resolves(function (CacheFailedOver $event) use (&$captured): void { $captured = $event; }); $app->instance(Dispatcher::class, $events); @@ -326,10 +326,10 @@ public function testManagerBuiltSerializingStoresShareOnePolicy(): void ], ], ]); - $app->instance('db', m::mock(ConnectionResolverInterface::class)); + $app->instance('db', Double::for(ConnectionResolverInterface::class)); $app->instance('files', new Filesystem); - $filesystem = m::mock(FilesystemFactory::class); - $filesystem->expects('disk')->with('test')->andReturn(new ArrayFilesystem); + $filesystem = Double::for(FilesystemFactory::class); + $filesystem->expects('disk')->with('test')->returns(new ArrayFilesystem); $app->instance('filesystem', $filesystem); $app->instance(SwooleTableManager::class, new SwooleTableManager($app)); $manager = new CacheManager($app); @@ -407,8 +407,8 @@ public function testItCanCreateStorageDriver(): void { $disk = new ArrayFilesystem; - $filesystem = m::mock(FilesystemFactory::class); - $filesystem->expects('disk')->with('s3')->andReturn($disk); + $filesystem = Double::for(FilesystemFactory::class); + $filesystem->expects('disk')->with('s3')->returns($disk); $app = $this->getApp([ 'cache' => [ @@ -505,7 +505,7 @@ public function testCustomCreatorsStillOverrideMultiWordInternalDrivers(): void ]; $cacheManager = new CacheManager($this->getApp($userConfig)); - $repository = m::mock(CacheRepository::class); + $repository = Double::for(CacheRepository::class); $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 = m::mock(Dispatcher::class); + $eventDispatcher = Double::for(Dispatcher::class); $app->instance(Dispatcher::class, $eventDispatcher); $this->assertNull($repo->getEventDispatcher()); @@ -566,7 +566,7 @@ public function testItRefreshesDispatcherOnAllStores(): void $app = $this->getApp($userConfig); - $originalDispatcher = m::mock(Dispatcher::class); + $originalDispatcher = Double::for(Dispatcher::class); $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 = m::mock(Dispatcher::class); + $replacementDispatcher = Double::for(Dispatcher::class); $app->instance(Dispatcher::class, $replacementDispatcher); $cacheManager->refreshEventDispatcher(); @@ -595,11 +595,10 @@ public function testRefreshEventDispatcherSkipsCustomRepositoryImplementations() ], ], ]); - $app->instance(Dispatcher::class, m::mock(Dispatcher::class)); + $app->instance(Dispatcher::class, Double::for(Dispatcher::class)); $cacheManager = new CacheManager($app); - $repository = m::mock(CacheRepository::class); - $repository->shouldNotReceive('setEventDispatcher'); + $repository = Double::for(CacheRepository::class); $cacheManager->extend('custom', fn (): CacheRepository => $repository); $this->assertSame($repository, $cacheManager->store('custom')); @@ -607,6 +606,7 @@ public function testRefreshEventDispatcherSkipsCustomRepositoryImplementations() $cacheManager->refreshEventDispatcher(); $this->assertSame($repository, $cacheManager->store('custom')); + $repository->unused(); } public function testItSetsDefaultDriverChangesGlobalConfig(): void @@ -677,17 +677,15 @@ public function testItPurgesMemoizedStoreObjects(): void public function testForgetDriver(): void { - $cacheManager = m::mock(CacheManager::class) - ->shouldAllowMockingProtectedMethods() - ->makePartial(); + $cacheManager = Double::for(new CacheManager($this->getApp([])))->passthru(); $cacheManager->expects('resolve') - ->withArgs(['array']) + ->with('array') ->times(4) - ->andReturn(m::mock(CacheRepository::class)); + ->returns(Double::for(CacheRepository::class)); $cacheManager->expects('getDefaultDriver') - ->andReturn('array'); + ->returns('array'); foreach (['array', ['array'], null] as $option) { $cacheManager->store('array'); @@ -712,24 +710,8 @@ public function testForgetDriverForgets(): void $app = $this->getApp($userConfig); - $count = 0; - $cacheManager = new CacheManager($app); - $cacheManager->extend('forget', function () use (&$count): CacheRepository { - /** @var CacheRepository&MockInterface */ - $repository = m::mock(CacheRepository::class); - - if ($count++ === 0) { - $repository->expects('forever')->with('foo', 'bar'); - $repository->expects('get')->with('foo')->andReturn('bar'); - - return $repository; - } - - $repository->expects('get')->with('foo')->andReturnNull(); - - return $repository; - }); + $cacheManager->extend('forget', fn (): Repository => new Repository(new ArrayStore)); $cacheManager->store('forget')->forever('foo', 'bar'); $this->assertSame('bar', $cacheManager->store('forget')->get('foo')); @@ -946,7 +928,7 @@ public function testSessionDriverResolvesSessionStore(): void $app = $this->getApp($userConfig); - $session = m::mock(Session::class); + $session = Double::for(Session::class); $app->instance('session.store', $session); $cacheManager = new CacheManager($app); @@ -1174,29 +1156,29 @@ protected function getAppWithRedis(array $userConfig): Container $app = $this->getApp($userConfig); // Mock Redis client - $redisClient = m::mock(); - $redisClient->shouldReceive('getOption') + $redisClient = Double::for(Redis::class); + $redisClient->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE); - $redisClient->shouldReceive('getOption') + ->returns(Redis::COMPRESSION_NONE); + $redisClient->allows('getOption') ->with(Redis::OPT_PREFIX) - ->andReturn(''); + ->returns(''); // Mock RedisConnection - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('release')->zeroOrMoreTimes(); - $connection->shouldReceive('serialized')->andReturn(false); - $connection->shouldReceive('client')->andReturn($redisClient); + $connection = Double::for(PhpRedisConnection::class); + $connection->allows('release'); + $connection->allows('serialized')->returns(false); + $connection->allows('client')->returns($redisClient); // Mock RedisPool - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('borrow')->andReturn($connection); + $pool = Double::for(RedisPool::class); + $pool->allows('borrow')->returns($connection); - $poolManager = m::mock(PoolManager::class); - $poolManager->shouldReceive('pool')->with('default')->andReturn($pool); + $poolManager = Double::for(PoolManager::class); + $poolManager->allows('pool')->with('default')->returns($pool); // Mock RedisFactory - $redisFactory = m::mock(RedisFactory::class); + $redisFactory = Double::for(RedisFactory::class); $app->instance('redis', $redisFactory); $app->instance(PoolManager::class, $poolManager); diff --git a/tests/Cache/CacheRedisStoreTest.php b/tests/Cache/CacheRedisStoreTest.php index d9cb87f37..86d768361 100755 --- a/tests/Cache/CacheRedisStoreTest.php +++ b/tests/Cache/CacheRedisStoreTest.php @@ -4,230 +4,19 @@ namespace Hypervel\Tests\Cache; -use __PHP_Incomplete_Class; use Hypervel\Cache\RedisStore; -use Hypervel\Cache\SerializableClassPolicy; use Hypervel\Contracts\Redis\Factory; -use Hypervel\Redis\RedisProxy; -use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; -use Hypervel\Tests\Redis\Fixtures\FakeRedisClient; -use Mockery as m; -use Redis; -use stdClass; +use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; -class CacheRedisStoreTest extends RedisCacheTestCase +class CacheRedisStoreTest extends TestCase { - public function testGetReturnsNullWhenNotFound(): void - { - $connection = $this->mockConnection(); - $connection->expects('get')->with('prefix:foo')->andReturn(null); - - $store = $this->createStore($connection); - $this->assertNull($store->get('foo')); - } - - public function testRedisValueIsReturned(): void - { - $connection = $this->mockConnection(); - $connection->expects('get')->with('prefix:foo')->andReturn(serialize('foo')); - - $store = $this->createStore($connection); - $this->assertSame('foo', $store->get('foo')); - } - - public function testSerializableClassesControlRedisValues(): void - { - $denyingConnection = $this->mockConnection(); - $denyingConnection->expects('get') - ->with('prefix:object') - ->andReturn(serialize(new stdClass)); - $allowingConnection = $this->mockConnection(); - $allowingConnection->expects('get') - ->with('prefix:object') - ->andReturn(serialize(new stdClass)); - - $denyingStore = new RedisStore( - $this->createRedisFactory($denyingConnection), - 'prefix:', - 'default', - false, - ); - $allowingStore = new RedisStore( - $this->createRedisFactory($allowingConnection), - 'prefix:', - 'default', - serializableClasses: [stdClass::class], - ); - - $this->assertInstanceOf(__PHP_Incomplete_Class::class, $denyingStore->get('object')); - $this->assertInstanceOf(stdClass::class, $allowingStore->get('object')); - } - - public function testSerializableClassPolicyControlsRedisValues(): void - { - $connection = $this->mockConnection(); - $connection->expects('get') - ->with('prefix:object') - ->andReturn(serialize(new stdClass)); - $store = new RedisStore( - $this->createRedisFactory($connection), - 'prefix:', - 'default', - serializableClassPolicy: new SerializableClassPolicy(static fn (): false => false), - ); - - $this->assertInstanceOf(__PHP_Incomplete_Class::class, $store->get('object')); - } - - public function testRedisMultipleValuesAreReturned(): void - { - $connection = $this->mockConnection(); - $connection->expects('mget')->with(['prefix:foo', 'prefix:fizz', 'prefix:norf', 'prefix:null']) - ->andReturn([ - serialize('bar'), - serialize('buzz'), - serialize('quz'), - null, - ]); - - $store = $this->createStore($connection); - $results = $store->many(['foo', 'fizz', 'norf', 'null']); - - $this->assertSame('bar', $results['foo']); - $this->assertSame('buzz', $results['fizz']); - $this->assertSame('quz', $results['norf']); - $this->assertNull($results['null']); - } - - public function testRedisValueIsReturnedForNumerics(): void - { - $connection = $this->mockConnection(); - $connection->expects('get')->with('prefix:foo')->andReturn(1); - - $store = $this->createStore($connection); - $this->assertEquals(1, $store->get('foo')); - } - - public function testSetMethodProperlyCallsRedis(): void - { - $connection = $this->mockConnection(); - $connection->expects('setex')->with('prefix:foo', 60, serialize('foo'))->andReturn('OK'); - - $store = $this->createStore($connection); - $result = $store->put('foo', 'foo', 60); - $this->assertTrue($result); - } - - public function testSetMultipleMethodProperlyCallsRedis(): void - { - $connection = $this->mockConnection(); - // Hypervel uses a Lua script for putMany in standard mode (more performant than multi/exec). - // The Lua script receives all keys and serialized values in a single EVALSHA call. - $connection->expects('evalWithShaCache') - ->with( - m::type('string'), - ['prefix:foo', 'prefix:baz', 'prefix:bar'], - [60, serialize('bar'), serialize('qux'), serialize('norf')], - ) - ->andReturn(true); - - $store = $this->createStore($connection); - $result = $store->putMany([ - 'foo' => 'bar', - 'baz' => 'qux', - 'bar' => 'norf', - ], 60); - $this->assertTrue($result); - } - - public function testSetMethodProperlyCallsRedisForNumerics(): void - { - $connection = $this->mockConnection(); - $connection->expects('setex')->with('prefix:foo', 60, 1); - - $store = $this->createStore($connection); - $result = $store->put('foo', 1, 60); - $this->assertFalse($result); - } - - public function testIncrementMethodProperlyCallsRedis(): void - { - $connection = $this->mockConnection(); - $connection->expects('incrBy')->with('prefix:foo', 5)->andReturn(5); - - $store = $this->createStore($connection); - $store->increment('foo', 5); - } - - public function testDecrementMethodProperlyCallsRedis(): void - { - $connection = $this->mockConnection(); - $connection->expects('decrBy')->with('prefix:foo', 5)->andReturn(-5); - - $store = $this->createStore($connection); - $store->decrement('foo', 5); - } - - public function testStoreItemForeverProperlyCallsRedis(): void - { - $connection = $this->mockConnection(); - $connection->expects('set')->with('prefix:foo', serialize('foo'))->andReturn('OK'); - - $store = $this->createStore($connection); - $result = $store->forever('foo', 'foo'); - $this->assertTrue($result); - } - - public function testTouchMethodProperlyCallsRedis(): void - { - $connection = $this->mockConnection(); - $connection->expects('expire')->with('prefix:key', 60)->andReturn(true); - - $store = $this->createStore($connection); - $this->assertTrue($store->touch('key', 60)); - } - - public function testForgetMethodProperlyCallsRedis(): void - { - $connection = $this->mockConnection(); - $connection->expects('del')->with('prefix:foo'); - - $store = $this->createStore($connection); - $store->forget('foo'); - } - - public function testFlushesCached(): void - { - $connection = $this->mockConnection(); - $connection->expects('flushdb')->andReturn('ok'); - - $store = $this->createStore($connection); - $result = $store->flush(); - $this->assertTrue($result); - } - - public function testFlushesCachedLocks(): void - { - $lockProxy = m::mock(RedisProxy::class); - $lockProxy->expects('flushdb')->andReturn('ok'); - - $redis = m::mock(Factory::class); - $redis->expects('connection')->with('locks')->andReturn($lockProxy); - - $store = new RedisStore( - $redis, - 'prefix:', - 'default' - ); - $store->setLockConnection('locks'); - - $result = $store->flushLocks(); - $this->assertTrue($result); - } + use VerifiesDoubles; public function testSupportsFlushingLocksRequiresSeparateLockConnection(): void { - $store = $this->createStore($this->mockConnection()); + $store = $this->getRedis(); $this->assertFalse($store->supportsFlushingLocks()); @@ -238,7 +27,7 @@ public function testSupportsFlushingLocksRequiresSeparateLockConnection(): void public function testGetAndSetPrefix(): void { - $store = $this->createStore($this->mockConnection()); + $store = $this->getRedis(); $this->assertSame('prefix:', $store->getPrefix()); $store->setPrefix('foo'); $this->assertSame('foo', $store->getPrefix()); @@ -246,35 +35,11 @@ public function testGetAndSetPrefix(): void $this->assertEmpty($store->getPrefix()); } - public function testFlushStaleTagsStopsScanningWhenTheCursorReachesZero(): void + /** + * Create a Redis store without opening a connection. + */ + protected function getRedis(): RedisStore { - $client = new FakeRedisClient(scanResults: [ - ['keys' => ['prefix:_all:tag:foo:entries'], 'iterator' => 0], - ]); - $store = $this->createStoreWithFakeClient($client, tagMode: 'all'); - - $store->flushStaleTags(); - - $this->assertSame(1, $client->getScanCallCount()); - } - - public function testFlushStaleTagsDoesNotDoublePrefixTheMatchPattern(): void - { - $connection = $this->mockConnection(); - $connection->allows('getShouldTransform')->andReturn(false); - $connection->allows('getOption')->with(Redis::OPT_PREFIX)->andReturn('app_'); - $connection->allows('getOption')->with(Redis::OPT_SCAN)->andReturn(Redis::SCAN_PREFIX); - $connection->expects('scan') - ->with(m::any(), 'prefix:_all:tag:*:entries', 1000) - ->andReturnUsing(function (mixed &$cursor): array { - $cursor = 0; - - return ['app_prefix:_all:tag:foo:entries']; - }); - $connection->expects('zRemRangeByScore')->with('prefix:_all:tag:foo:entries', '0', m::any())->andReturn(0); - $connection->allows('zscan')->andReturn(false); - $connection->allows('zCard')->andReturn(0); - - $this->createStore($connection, tagMode: 'all')->flushStaleTags(); + return new RedisStore(Double::for(Factory::class), 'prefix:'); } } diff --git a/tests/Cache/CacheRepositoryTest.php b/tests/Cache/CacheRepositoryTest.php index 09412c26d..bd4b6d735 100644 --- a/tests/Cache/CacheRepositoryTest.php +++ b/tests/Cache/CacheRepositoryTest.php @@ -43,7 +43,9 @@ use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -54,6 +56,8 @@ class CacheRepositoryTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -64,14 +68,14 @@ protected function setUp(): void public function testGetReturnsValueFromCache(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('bar'); + $repo->getStore()->expects('get')->with('foo')->returns('bar'); $this->assertSame('bar', $repo->get('foo')); } public function testAuthoritativeRawReadUsesItemKeyAndPreservesSentinelEvents(): void { - $store = m::mock(Store::class, AuthoritativeRawReadable::class); - $store->expects('getAuthoritativeRaw')->with('prefix:foo')->andReturn(NullSentinel::VALUE); + $store = Double::for(Store::class, AuthoritativeRawReadable::class); + $store->expects('getAuthoritativeRaw')->with('prefix:foo')->returns(NullSentinel::VALUE); $repository = new class($store) extends Repository { protected function itemKey(string $key): string @@ -81,9 +85,9 @@ protected function itemKey(string $key): string }; $events = []; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $dispatcher->shouldReceive('dispatch')->andReturnUsing(function ($event) use (&$events): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->returns(true); + $dispatcher->allows('dispatch')->resolves(function ($event) use (&$events): void { $events[] = $event; }); $repository->setEventDispatcher($dispatcher); @@ -99,14 +103,14 @@ protected function itemKey(string $key): string public function testAuthoritativeRawReadDispatchesRetrievalFailure(): void { $failure = new RuntimeException('read failed'); - $store = m::mock(Store::class, AuthoritativeRawReadable::class); - $store->expects('getAuthoritativeRaw')->with('foo')->andThrow($failure); + $store = Double::for(Store::class, AuthoritativeRawReadable::class); + $store->expects('getAuthoritativeRaw')->with('foo')->throws($failure); $repository = new Repository($store); $events = []; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $dispatcher->shouldReceive('dispatch')->andReturnUsing(function ($event) use (&$events): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->returns(true); + $dispatcher->allows('dispatch')->resolves(function ($event) use (&$events): void { $events[] = $event; }); $repository->setEventDispatcher($dispatcher); @@ -127,8 +131,8 @@ public function testAuthoritativeRawReadDispatchesRetrievalFailure(): void public function testAuthoritativeRawReadPreservesCancellation(): void { $cancellation = new CanceledException('read canceled'); - $store = m::mock(Store::class, AuthoritativeRawReadable::class); - $store->expects('getAuthoritativeRaw')->with('foo')->andThrow($cancellation); + $store = Double::for(Store::class, AuthoritativeRawReadable::class); + $store->expects('getAuthoritativeRaw')->with('foo')->throws($cancellation); $repository = new Repository($store); @@ -143,28 +147,28 @@ public function testAuthoritativeRawReadPreservesCancellation(): void public function testGetReturnsMultipleValuesFromCacheWhenGivenAnArray(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('many')->with(['foo', 'bar'])->andReturn(['foo' => 'bar', 'bar' => 'baz']); + $repo->getStore()->expects('many')->with(['foo', 'bar'])->returns(['foo' => 'bar', 'bar' => 'baz']); $this->assertEquals(['foo' => 'bar', 'bar' => 'baz'], $repo->get(['foo', 'bar'])); } public function testGetReturnsMultipleValuesFromCacheWhenGivenAnArrayWithDefaultValues(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('many')->with(['foo', 'bar'])->andReturn(['foo' => null, 'bar' => 'baz']); + $repo->getStore()->expects('many')->with(['foo', 'bar'])->returns(['foo' => null, 'bar' => 'baz']); $this->assertEquals(['foo' => 'default', 'bar' => 'baz'], $repo->get(['foo' => 'default', 'bar'])); } public function testGetReturnsMultipleValuesFromCacheWhenGivenAnArrayOfOneTwoThree(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('many')->with(['1', '2', '3'])->andReturn([1 => null, 2 => null, 3 => null]); + $repo->getStore()->expects('many')->with(['1', '2', '3'])->returns([1 => null, 2 => null, 3 => null]); $this->assertEquals([1 => null, 2 => null, 3 => null], $repo->get([1, 2, 3])); } public function testDefaultValueIsReturned(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->times(2)->andReturn(null); + $repo->getStore()->expects('get')->times(2)->returns(null); $this->assertSame('bar', $repo->get('foo', 'bar')); $this->assertSame('baz', $repo->get('boom', function (): string { return 'baz'; @@ -181,9 +185,9 @@ public function testSettingDefaultCacheTime(): void public function testHasMethod(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); - $repo->getStore()->expects('get')->with('bar')->andReturn('bar'); - $repo->getStore()->expects('get')->with('baz')->andReturn(false); + $repo->getStore()->expects('get')->with('foo')->returns(null); + $repo->getStore()->expects('get')->with('bar')->returns('bar'); + $repo->getStore()->expects('get')->with('baz')->returns(false); $this->assertTrue($repo->has('bar')); $this->assertFalse($repo->has('foo')); @@ -199,7 +203,7 @@ public function testHasMethod(): void public function testHasMethodWithArray(array $keys, array $values, bool $expected): void { $repo = $this->getRepository(); - $repo->getStore()->expects('many')->with(array_keys($values))->andReturn($values); + $repo->getStore()->expects('many')->with(array_keys($values))->returns($values); $this->assertSame($expected, $repo->has($keys)); } @@ -207,8 +211,8 @@ public function testHasMethodWithArray(array $keys, array $values, bool $expecte public function testMissingMethod(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); - $repo->getStore()->expects('get')->with('bar')->andReturn('bar'); + $repo->getStore()->expects('get')->with('foo')->returns(null); + $repo->getStore()->expects('get')->with('bar')->returns('bar'); $this->assertTrue($repo->missing('foo')); $this->assertFalse($repo->missing('bar')); @@ -217,7 +221,7 @@ public function testMissingMethod(): void public function testRememberMethodCallsPutAndReturnsDefault(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->andReturn(null); + $repo->getStore()->expects('get')->returns(null); $repo->getStore()->expects('put')->with('foo', 'bar', 10); $result = $repo->remember('foo', 10, function (): string { return 'bar'; @@ -225,7 +229,7 @@ public function testRememberMethodCallsPutAndReturnsDefault(): void $this->assertSame('bar', $result); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->times(2)->andReturn(null); + $repo->getStore()->expects('get')->times(2)->returns(null); $repo->getStore()->expects('put')->with('foo', 'bar', 602); $repo->getStore()->expects('put')->with('baz', 'qux', 598); $result = $repo->remember('foo', CarbonImmutable::now()->addMinutes(10)->addSeconds(2), function (): string { @@ -238,7 +242,7 @@ public function testRememberMethodCallsPutAndReturnsDefault(): void $this->assertSame('qux', $result); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->andReturn(null); + $repo->getStore()->expects('get')->returns(null); $repo->getStore()->expects('put')->with('foo', 'bar', 10); $result = $repo->remember('foo', function (string $value): int { $this->assertSame('bar', $value); @@ -251,8 +255,8 @@ public function testRememberMethodCallsPutAndReturnsDefault(): void public function testRememberWithWarmthReturnsCachedValue(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('bar'); - $repo->getStore()->shouldNotReceive('put'); + $repo->getStore()->expects('get')->with('foo')->returns('bar'); + $repo->getStore()->expects('put')->never(); $result = $repo->rememberWithWarmth('foo', 10, function () { $this->fail('The cache callback should not be called.'); @@ -264,7 +268,7 @@ public function testRememberWithWarmthReturnsCachedValue(): void public function testRememberWithWarmthCallsPutAndReturnsDefault(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); + $repo->getStore()->expects('get')->with('foo')->returns(null); $repo->getStore()->expects('put')->with('foo', 'bar', 10); $result = $repo->rememberWithWarmth('foo', function (string $value): int { @@ -279,8 +283,8 @@ public function testRememberWithWarmthCallsPutAndReturnsDefault(): void public function testRememberWithWarmthTreatsNullableSentinelAsWarm(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(NullSentinel::VALUE); - $repo->getStore()->shouldNotReceive('put'); + $repo->getStore()->expects('get')->with('foo')->returns(NullSentinel::VALUE); + $repo->getStore()->expects('put')->never(); $this->assertSame([null, true], $repo->rememberWithWarmth('foo', 10, function () { $this->fail('The cache callback should not be called.'); @@ -290,7 +294,7 @@ public function testRememberWithWarmthTreatsNullableSentinelAsWarm(): void public function testRememberForeverMethodCallsForeverAndReturnsDefault(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->andReturn(null); + $repo->getStore()->expects('get')->returns(null); $repo->getStore()->expects('forever')->with('foo', 'bar'); $result = $repo->rememberForever('foo', function () { return 'bar'; @@ -301,7 +305,7 @@ public function testRememberForeverMethodCallsForeverAndReturnsDefault(): void public function testGetReturnsIncompleteClassWhenNoHandlerRegistered(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn( + $repo->getStore()->expects('get')->with('foo')->returns( unserialize(serialize(new stdClass), ['allowed_classes' => false]) ); @@ -317,7 +321,7 @@ public function testGetCallsHandlerWithKeyAndClassForIncompleteClass(): void }); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn( + $repo->getStore()->expects('get')->with('foo')->returns( unserialize(serialize(new stdClass), ['allowed_classes' => false]) ); @@ -335,8 +339,8 @@ public function testAuthoritativeRawReadFallsBackToStoreAndHandlesIncompleteClas $handled[] = [$key, $class]; }); - $store = m::mock(Store::class); - $store->expects('get')->with('prefix:foo')->andReturn($incomplete); + $store = Double::for(Store::class); + $store->expects('get')->with('prefix:foo')->returns($incomplete); $repository = new class($store) extends Repository { protected function itemKey(string $key): string @@ -363,7 +367,7 @@ public function handle(string $key, ?string $class): void Repository::handleUnserializableClassUsing([$handler, 'handle']); $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->twice()->with('foo')->andReturn( + $repo->getStore()->expects('get')->times(2)->with('foo')->returns( unserialize(serialize(new stdClass), ['allowed_classes' => false]) ); @@ -385,7 +389,7 @@ public function testManyCallsHandlerForEachIncompleteClass(): void }); $repo = $this->getRepository(); - $repo->getStore()->expects('many')->with(['foo', 'bar'])->andReturn([ + $repo->getStore()->expects('many')->with(['foo', 'bar'])->returns([ 'foo' => unserialize(serialize(new stdClass), ['allowed_classes' => false]), 'bar' => 'baz', ]); @@ -407,15 +411,15 @@ public function testManyEmitsOneFailureWithoutPartialSuccessWhenIncompleteClassH $incomplete = unserialize(serialize(new stdClass), ['allowed_classes' => false]); $repo = $this->getRepository(); - $repo->getStore()->expects('many')->with(['foo', 'bar'])->andReturn([ + $repo->getStore()->expects('many')->with(['foo', 'bar'])->returns([ 'foo' => $incomplete, 'bar' => $incomplete, ]); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch')->andReturnUsing(function ($event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch')->resolves(function ($event) use (&$captured): void { $captured[] = $event; }); $repo->setEventDispatcher($events); @@ -440,7 +444,7 @@ public function testManyEmitsOneFailureWithoutPartialSuccessWhenIncompleteClassH public function testRememberNullableStoresAndReturnsNonNullValue(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); + $repo->getStore()->expects('get')->with('foo')->returns(null); $repo->getStore()->expects('put')->with('foo', 'bar', 10); $result = $repo->rememberNullable('foo', 10, fn () => 'bar'); @@ -451,7 +455,7 @@ public function testRememberNullableStoresAndReturnsNonNullValue(): void public function testRememberNullableStoresSentinelWhenCallbackReturnsNull(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); + $repo->getStore()->expects('get')->with('foo')->returns(null); $repo->getStore()->expects('put')->with('foo', NullSentinel::VALUE, 10); $result = $repo->rememberNullable('foo', 10, fn () => null); @@ -462,8 +466,8 @@ public function testRememberNullableStoresSentinelWhenCallbackReturnsNull(): voi public function testRememberNullableReturnsNullOnSentinelHitWithoutInvokingCallback(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(NullSentinel::VALUE); - $repo->getStore()->shouldNotReceive('put'); + $repo->getStore()->expects('get')->with('foo')->returns(NullSentinel::VALUE); + $repo->getStore()->expects('put')->never(); $invoked = false; $result = $repo->rememberNullable('foo', 10, function () use (&$invoked) { @@ -478,7 +482,7 @@ public function testRememberNullableReturnsNullOnSentinelHitWithoutInvokingCallb public function testRememberNullableReturnsCachedValueOnHit(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('cached'); + $repo->getStore()->expects('get')->with('foo')->returns('cached'); $result = $repo->rememberNullable('foo', 10, fn () => 'new'); @@ -488,7 +492,7 @@ public function testRememberNullableReturnsCachedValueOnHit(): void public function testRememberForeverNullableStoresAndReturnsNonNullValue(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->andReturn(null); + $repo->getStore()->expects('get')->returns(null); $repo->getStore()->expects('forever')->with('foo', 'bar'); $result = $repo->rememberForeverNullable('foo', fn () => 'bar'); @@ -499,7 +503,7 @@ public function testRememberForeverNullableStoresAndReturnsNonNullValue(): void public function testRememberForeverNullableStoresSentinelWhenCallbackReturnsNull(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->andReturn(null); + $repo->getStore()->expects('get')->returns(null); $repo->getStore()->expects('forever')->with('foo', NullSentinel::VALUE); $result = $repo->rememberForeverNullable('foo', fn () => null); @@ -510,8 +514,8 @@ public function testRememberForeverNullableStoresSentinelWhenCallbackReturnsNull public function testRememberForeverNullableReturnsNullOnSentinelHit(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->andReturn(NullSentinel::VALUE); - $repo->getStore()->shouldNotReceive('forever'); + $repo->getStore()->expects('get')->returns(NullSentinel::VALUE); + $repo->getStore()->expects('forever')->never(); $result = $repo->rememberForeverNullable('foo', fn () => 'should-not-run'); @@ -521,7 +525,7 @@ public function testRememberForeverNullableReturnsNullOnSentinelHit(): void public function testSearNullableDelegatesToRememberForeverNullable(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->andReturn(null); + $repo->getStore()->expects('get')->returns(null); $repo->getStore()->expects('forever')->with('foo', NullSentinel::VALUE); $result = $repo->searNullable('foo', fn () => null); @@ -535,10 +539,10 @@ public function testFlexibleNullableStoresAndReturnsNonNullValue(): void $repo->getStore() ->expects('many') ->with(['foo', 'hypervel:cache:flexible:created:foo']) - ->andReturn(['foo' => null, 'hypervel:cache:flexible:created:foo' => null]); + ->returns(['foo' => null, 'hypervel:cache:flexible:created:foo' => null]); $repo->getStore() ->expects('putMany') - ->with(m::on(fn ($values) => $values['foo'] === 'bar'), 20); + ->with(Argument::satisfies(fn ($values) => $values['foo'] === 'bar'), 20); $result = $repo->flexibleNullable('foo', [10, 20], fn () => 'bar'); @@ -551,10 +555,10 @@ public function testFlexibleNullableStoresSentinelWhenCallbackReturnsNull(): voi $repo->getStore() ->expects('many') ->with(['foo', 'hypervel:cache:flexible:created:foo']) - ->andReturn(['foo' => null, 'hypervel:cache:flexible:created:foo' => null]); + ->returns(['foo' => null, 'hypervel:cache:flexible:created:foo' => null]); $repo->getStore() ->expects('putMany') - ->with(m::on(fn ($values) => $values['foo'] === NullSentinel::VALUE), 20); + ->with(Argument::satisfies(fn ($values) => $values['foo'] === NullSentinel::VALUE), 20); $result = $repo->flexibleNullable('foo', [10, 20], fn () => null); @@ -569,7 +573,7 @@ public function testFlexibleNullableReturnsNullOnFreshSentinelHit(): void $repo->getStore() ->expects('many') ->with(['foo', 'hypervel:cache:flexible:created:foo']) - ->andReturn([ + ->returns([ 'foo' => NullSentinel::VALUE, 'hypervel:cache:flexible:created:foo' => $now, ]); @@ -587,7 +591,7 @@ public function testFlexibleNullableReturnsValueOnFreshValueHit(): void $repo->getStore() ->expects('many') ->with(['foo', 'hypervel:cache:flexible:created:foo']) - ->andReturn([ + ->returns([ 'foo' => 'cached', 'hypervel:cache:flexible:created:foo' => $now, ]); @@ -601,17 +605,17 @@ public function testFlexibleSkipsRefreshWhenAuthoritativeMarkerChanged(): void { $created = CarbonImmutable::now()->subSeconds(11)->getTimestamp(); $markerKey = Repository::FLEXIBLE_CREATED_KEY_PREFIX . 'foo'; - $store = m::mock(implode(',', [Store::class, LockProvider::class, AuthoritativeRawReadable::class])); - $lock = m::mock(Lock::class); + $store = Double::for(Store::class, LockProvider::class, AuthoritativeRawReadable::class); + $lock = Double::for(Lock::class); - $store->expects('many')->with(['foo', $markerKey])->andReturn([ + $store->expects('many')->with(['foo', $markerKey])->returns([ 'foo' => 'stale', $markerKey => $created, ]); - $store->expects('lock')->with('hypervel:cache:flexible:lock:foo', 0, null)->andReturn($lock); - $store->expects('getAuthoritativeRaw')->with($markerKey)->andReturn($created + 1); - $store->shouldNotReceive('putMany'); - $lock->expects('get')->with(m::type('callable'))->andReturnUsing(fn ($callback) => $callback()); + $store->expects('lock')->with('hypervel:cache:flexible:lock:foo', 0, null)->returns($lock); + $store->expects('getAuthoritativeRaw')->with($markerKey)->returns($created + 1); + $store->expects('putMany')->never(); + $lock->expects('get')->with(Argument::type('callable'))->resolves(fn ($callback) => $callback()); $repository = new Repository($store); $callbackCalled = false; @@ -806,10 +810,10 @@ public function testPuttingMultipleItemsInCache(): void public function testEmptyPutManyReturnsTrueWithoutStoreOrEvents(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldNotReceive('putMany'); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('hasListeners'); - $events->shouldNotReceive('dispatch'); + $repo->getStore()->expects('putMany')->never(); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $repo->setEventDispatcher($events); $this->assertTrue($repo->putMany([], 60)); @@ -818,7 +822,7 @@ public function testEmptyPutManyReturnsTrueWithoutStoreOrEvents(): void public function testSettingMultipleItemsInCacheArray(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('putMany')->with(['foo' => 'bar', 'bar' => 'baz'], 1)->andReturn(true); + $repo->getStore()->expects('putMany')->with(['foo' => 'bar', 'bar' => 'baz'], 1)->returns(true); $result = $repo->setMultiple(['foo' => 'bar', 'bar' => 'baz'], 1); $this->assertTrue($result); } @@ -826,7 +830,7 @@ public function testSettingMultipleItemsInCacheArray(): void public function testSettingMultipleItemsInCacheIterator(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('putMany')->with(['foo' => 'bar', 'bar' => 'baz'], 1)->andReturn(true); + $repo->getStore()->expects('putMany')->with(['foo' => 'bar', 'bar' => 'baz'], 1)->returns(true); $result = $repo->setMultiple(new ArrayIterator(['foo' => 'bar', 'bar' => 'baz']), 1); $this->assertTrue($result); } @@ -834,15 +838,15 @@ public function testSettingMultipleItemsInCacheIterator(): void public function testPutWithNullTTLRemembersItemForever(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('forever')->with('foo', 'bar')->andReturn(true); + $repo->getStore()->expects('forever')->with('foo', 'bar')->returns(true); $this->assertTrue($repo->put('foo', 'bar')); } public function testPutWithDatetimeInPastOrZeroSecondsRemovesOldItem(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('put')->never(); - $repo->getStore()->expects('forget')->times(2)->andReturn(true); + $repo->getStore()->expects('put')->never(); + $repo->getStore()->expects('forget')->times(2)->returns(true); $result = $repo->put('foo', 'bar', CarbonImmutable::now()->subMinutes(10)); $this->assertTrue($result); $result = $repo->put('foo', 'bar', CarbonImmutable::now()); @@ -852,54 +856,53 @@ public function testPutWithDatetimeInPastOrZeroSecondsRemovesOldItem(): void public function testPutManyWithNullTTLRemembersItemsForever(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('forever')->with('foo', 'bar')->andReturn(true); - $repo->getStore()->expects('forever')->with('bar', 'baz')->andReturn(true); + $repo->getStore()->expects('forever')->with('foo', 'bar')->returns(true); + $repo->getStore()->expects('forever')->with('bar', 'baz')->returns(true); $this->assertTrue($repo->putMany(['foo' => 'bar', 'bar' => 'baz'])); } public function testAddWithStoreFailureReturnsFalse(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('add')->never(); - $repo->getStore()->expects('get')->andReturn(null); - $repo->getStore()->expects('put')->andReturn(false); + $repo->getStore()->expects('get')->returns(null); + $repo->getStore()->expects('put')->returns(false); $this->assertFalse($repo->add('foo', 'bar', 60)); } public function testCacheAddCallsRedisStoreAdd(): void { - $store = m::mock(RedisStore::class); - $store->expects('add')->with('k', 'v', 60)->andReturn(true); + $store = Double::for(RedisStore::class); + $store->expects('add')->with('k', 'v', 60)->returns(true); $repository = new Repository($store); $this->assertTrue($repository->add('k', 'v', 60)); } public function testAddMethodCanAcceptDateIntervals(): void { - $storeWithAdd = m::mock(RedisStore::class); - $storeWithAdd->expects('add')->with('k', 'v', 61)->andReturn(true); + $storeWithAdd = Double::for(RedisStore::class); + $storeWithAdd->expects('add')->with('k', 'v', 61)->returns(true); $repository = new Repository($storeWithAdd); $this->assertTrue($repository->add('k', 'v', DateInterval::createFromDateString('61 seconds'))); - $storeWithoutAdd = m::mock(ArrayStore::class); + $storeWithoutAdd = Double::for(ArrayStore::class); $this->assertFalse(method_exists(ArrayStore::class, 'add'), 'This store should not have add method on it.'); - $storeWithoutAdd->expects('get')->with('k')->andReturn(null); - $storeWithoutAdd->expects('put')->with('k', 'v', 60)->andReturn(true); + $storeWithoutAdd->expects('get')->with('k')->returns(null); + $storeWithoutAdd->expects('put')->with('k', 'v', 60)->returns(true); $repository = new Repository($storeWithoutAdd); $this->assertTrue($repository->add('k', 'v', DateInterval::createFromDateString('60 seconds'))); } public function testAddMethodCanAcceptDateTimeInterface(): void { - $withAddStore = m::mock(RedisStore::class); - $withAddStore->expects('add')->with('k', 'v', 61)->andReturn(true); + $withAddStore = Double::for(RedisStore::class); + $withAddStore->expects('add')->with('k', 'v', 61)->returns(true); $repository = new Repository($withAddStore); $this->assertTrue($repository->add('k', 'v', CarbonImmutable::now()->addSeconds(61))); - $noAddStore = m::mock(ArrayStore::class); + $noAddStore = Double::for(ArrayStore::class); $this->assertFalse(method_exists(ArrayStore::class, 'add'), 'This store should not have add method on it.'); - $noAddStore->expects('get')->with('k')->andReturn(null); - $noAddStore->expects('put')->with('k', 'v', 62)->andReturn(true); + $noAddStore->expects('get')->with('k')->returns(null); + $noAddStore->expects('put')->with('k', 'v', 62)->returns(true); $repository = new Repository($noAddStore); $this->assertTrue($repository->add('k', 'v', CarbonImmutable::now()->addSeconds(62))); } @@ -907,8 +910,8 @@ public function testAddMethodCanAcceptDateTimeInterface(): void public function testAddWithNullTTLRemembersItemForever(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); - $repo->getStore()->expects('forever')->with('foo', 'bar')->andReturn(true); + $repo->getStore()->expects('get')->with('foo')->returns(null); + $repo->getStore()->expects('forever')->with('foo', 'bar')->returns(true); $this->assertTrue($repo->add('foo', 'bar')); } @@ -925,7 +928,8 @@ public function testAddTreatsACachedNullAsPresent(): void public function testAddWithDatetimeInPastOrZeroSecondsReturnsImmediately(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('add', 'get', 'put')->never(); + $repo->getStore()->expects('get')->never(); + $repo->getStore()->expects('put')->never(); $result = $repo->add('foo', 'bar', CarbonImmutable::now()->subMinutes(10)); $this->assertFalse($result); $result = $repo->add('foo', 'bar', CarbonImmutable::now()); @@ -936,9 +940,9 @@ public function testAddWithDatetimeInPastOrZeroSecondsReturnsImmediately(): void public function testCounterFailuresAreReturnedWithoutCoercion(): void { - $store = m::mock(Store::class); - $store->expects('increment')->with('increment', 2)->andReturnFalse(); - $store->expects('decrement')->with('decrement', 3)->andReturnFalse(); + $store = Double::for(Store::class); + $store->expects('increment')->with('increment', 2)->returns(false); + $store->expects('decrement')->with('decrement', 3)->returns(false); $repository = new Repository($store); $this->assertFalse($repository->increment('increment', 2)); @@ -986,15 +990,15 @@ public function testRegisterMacroWithNonStaticCall(): void public function testForgettingCacheKey(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('forget')->with('a-key')->andReturn(true); + $repo->getStore()->expects('forget')->with('a-key')->returns(true); $repo->forget('a-key'); } public function testForgettingWithArray(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('forget')->with('foo')->andReturn(true); - $repo->getStore()->expects('forget')->with('bar')->andReturn(false); + $repo->getStore()->expects('forget')->with('foo')->returns(true); + $repo->getStore()->expects('forget')->with('bar')->returns(false); $this->assertFalse($repo->forget(['foo', TestCacheKey::Bar])); } @@ -1003,14 +1007,14 @@ public function testRemovingCacheKey(): void { // Alias of Forget $repo = $this->getRepository(); - $repo->getStore()->expects('forget')->with('a-key')->andReturn(true); + $repo->getStore()->expects('forget')->with('a-key')->returns(true); $repo->delete('a-key'); } public function testSettingCache(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('put')->with($key = 'foo', $value = 'bar', 1)->andReturn(true); + $repo->getStore()->expects('put')->with($key = 'foo', $value = 'bar', 1)->returns(true); $result = $repo->set($key, $value, 1); $this->assertTrue($result); } @@ -1018,7 +1022,7 @@ public function testSettingCache(): void public function testClearingWholeCache(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('flush')->andReturn(true); + $repo->getStore()->expects('flush')->returns(true); $repo->clear(); } @@ -1028,15 +1032,15 @@ public function testGettingMultipleValuesFromCache(): void $default = 5; $repo = $this->getRepository(); - $repo->getStore()->expects('many')->with(['key1', 'key2', 'key3'])->andReturn(['key1' => 1, 'key2' => null, 'key3' => null]); + $repo->getStore()->expects('many')->with(['key1', 'key2', 'key3'])->returns(['key1' => 1, 'key2' => null, 'key3' => null]); $this->assertEquals(['key1' => 1, 'key2' => 5, 'key3' => 5], $repo->getMultiple($keys, $default)); } public function testRemovingMultipleKeys(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('forget')->with('a-key')->andReturn(true); - $repo->getStore()->expects('forget')->with('a-second-key')->andReturn(true); + $repo->getStore()->expects('forget')->with('a-key')->returns(true); + $repo->getStore()->expects('forget')->with('a-second-key')->returns(true); $this->assertTrue($repo->deleteMultiple(['a-key', 'a-second-key'])); } @@ -1044,20 +1048,20 @@ public function testRemovingMultipleKeys(): void public function testRemovingMultipleKeysFailsIfOneFails(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('forget')->with('a-key')->andReturn(true); - $repo->getStore()->expects('forget')->with('a-second-key')->andReturn(false); + $repo->getStore()->expects('forget')->with('a-key')->returns(true); + $repo->getStore()->expects('forget')->with('a-second-key')->returns(false); $this->assertFalse($repo->deleteMultiple(['a-key', 'a-second-key'])); } public function testAllTagsArePassedToTaggableStore(): void { - $store = m::mock(ArrayStore::class); + $store = Double::for(ArrayStore::class); $repo = new Repository($store); - $taggedCache = m::mock(TaggedCache::class); - $taggedCache->expects('setDefaultCacheTime')->andReturnSelf(); - $store->expects('tags')->with(['foo', 'bar', 'baz'])->andReturn($taggedCache); + $taggedCache = Double::for(TaggedCache::class); + $taggedCache->expects('setDefaultCacheTime')->returns($taggedCache); + $store->expects('tags')->with(['foo', 'bar', 'baz'])->returns($taggedCache); $repo->tags('foo', 'bar', 'baz'); } @@ -1075,9 +1079,9 @@ public function testItThrowsExceptionWhenTaggableStoreReportsUnsupportedTags(): $this->expectException(NotSupportedException::class); $this->expectExceptionMessageIsOrContains('Detailed tag support failure.'); - $store = m::mock(TaggableStore::class); - $store->shouldReceive('supportsTags')->never(); - $store->expects('tags')->with(['foo'])->andThrow( + $store = Double::for(TaggableStore::class); + $store->expects('supportsTags')->never(); + $store->expects('tags')->with(['foo'])->throws( new NotSupportedException('Detailed tag support failure.') ); @@ -1127,7 +1131,7 @@ public function testIntegerTagNamesMatchTheirStringFormsAndCanBeFlushed(): void public function testEventDispatcherIsPassedToStoreFromRepository(): void { $repo = new Repository(new ArrayStore); - $repo->setEventDispatcher(m::mock(Dispatcher::class)); + $repo->setEventDispatcher(new EventDispatcher); $store = $repo->tags('foo'); @@ -1146,9 +1150,9 @@ public function testDefaultCacheLifeTimeIsSetOnTaggableStore(): void public function testFlushLocksDelegatesToStore(): void { - $flushable = m::mock(RedisStore::class); - $flushable->expects('supportsFlushingLocks')->andReturnTrue(); - $flushable->expects('flushLocks')->andReturn(true); + $flushable = Double::for(RedisStore::class); + $flushable->expects('supportsFlushingLocks')->returns(true); + $flushable->expects('flushLocks')->returns(true); $repo = new Repository($flushable); @@ -1165,8 +1169,8 @@ public function testTaggableRepositoriesSupportTags(): void public function testTaggableRepositoriesCanReportUnsupportedTags(): void { - $taggable = m::mock(TaggableStore::class); - $taggable->expects('supportsTags')->andReturnFalse(); + $taggable = Double::for(TaggableStore::class); + $taggable->expects('supportsTags')->returns(false); $taggableRepo = new Repository($taggable); $this->assertFalse($taggableRepo->supportsTags()); @@ -1182,8 +1186,8 @@ public function testNonTaggableRepositoryDoesNotSupportTags(): void public function testFlushableLockRepositorySupportsFlushingLocks(): void { - $flushable = m::mock(RedisStore::class); - $flushable->expects('supportsFlushingLocks')->andReturnTrue(); + $flushable = Double::for(RedisStore::class); + $flushable->expects('supportsFlushingLocks')->returns(true); $flushableRepo = new Repository($flushable); $this->assertTrue($flushableRepo->supportsFlushingLocks()); @@ -1191,8 +1195,8 @@ public function testFlushableLockRepositorySupportsFlushingLocks(): void public function testFlushableLockRepositoryCanReportUnsupportedFlushingLocks(): void { - $flushable = m::mock(RedisStore::class); - $flushable->expects('supportsFlushingLocks')->andReturnFalse(); + $flushable = Double::for(RedisStore::class); + $flushable->expects('supportsFlushingLocks')->returns(false); $flushableRepo = new Repository($flushable); $this->assertFalse($flushableRepo->supportsFlushingLocks()); @@ -1200,7 +1204,7 @@ public function testFlushableLockRepositoryCanReportUnsupportedFlushingLocks(): public function testNonFlushableLockRepositoryDoesNotSupportFlushingLocks(): void { - $nonFlushable = m::mock(Store::class); + $nonFlushable = Double::for(Store::class); $nonFlushableRepo = new Repository($nonFlushable); $this->assertFalse($nonFlushableRepo->supportsFlushingLocks()); @@ -1210,7 +1214,7 @@ public function testItThrowsExceptionWhenStoreDoesNotSupportFlushingLocks(): voi { $this->expectException(BadMethodCallException::class); - $nonFlushable = m::mock(Store::class); + $nonFlushable = Double::for(Store::class); $nonFlushableRepo = new Repository($nonFlushable); $nonFlushableRepo->flushLocks(); @@ -1222,7 +1226,7 @@ public function testTouchWithSecondsTtlCorrectlyProxiesToStore(): void $ttl = 60; $repo = $this->getRepository(); - $repo->getStore()->expects('touch')->with($key, $ttl)->andReturn(true); + $repo->getStore()->expects('touch')->with($key, $ttl)->returns(true); $this->assertTrue($repo->touch($key, $ttl)); } @@ -1234,7 +1238,7 @@ public function testTouchWithDatetimeTtlCorrectlyProxiesToStore(): void CarbonImmutable::setTestNow($now = CarbonImmutable::now()); $repo = $this->getRepository(); - $repo->getStore()->expects('touch')->with($key, $ttl)->andReturn(true); + $repo->getStore()->expects('touch')->with($key, $ttl)->returns(true); $this->assertTrue($repo->touch($key, $now->addSeconds($ttl))); } @@ -1244,15 +1248,15 @@ public function testTouchWithDateIntervalTtlCorrectlyProxiesToStore(): void $ttl = 60; $repo = $this->getRepository(); - $repo->getStore()->expects('touch')->with($key, $ttl)->andReturn(true); + $repo->getStore()->expects('touch')->with($key, $ttl)->returns(true); $this->assertTrue($repo->touch($key, DateInterval::createFromDateString("{$ttl} seconds"))); } public function testTouchWithDatetimeInPastOrZeroSecondsRemovesOldItem(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('touch')->never(); - $repo->getStore()->expects('forget')->times(2)->with('key')->andReturn(true); + $repo->getStore()->expects('touch')->never(); + $repo->getStore()->expects('forget')->times(2)->with('key')->returns(true); $this->assertTrue($repo->touch('key', CarbonImmutable::now()->subMinute())); $this->assertTrue($repo->touch('key', 0)); @@ -1263,7 +1267,7 @@ public function testTouchWorksWithEnumKey(): void $ttl = 60; $repo = $this->getRepository(); - $repo->getStore()->expects('touch')->with('foo', $ttl)->andReturn(true); + $repo->getStore()->expects('touch')->with('foo', $ttl)->returns(true); $this->assertTrue($repo->touch(TestCacheKey::Foo, $ttl)); } @@ -1280,12 +1284,12 @@ public function testAtomicExecutesCallbackAndReturnsResult(): void public function testAtomicPassesLockAndWaitSecondsToLock(): void { - $store = m::mock(Store::class, LockProvider::class); + $store = Double::for(Store::class, LockProvider::class); $repo = new Repository($store); - $lock = m::mock(Lock::class); + $lock = Double::for(Lock::class); - $store->expects('lock')->with('foo', 30, null)->andReturn($lock); - $lock->expects('block')->with(15, m::type('callable'))->andReturnUsing(function ($seconds, $callback) { + $store->expects('lock')->with('foo', 30, null)->returns($lock); + $lock->expects('block')->with(15, Argument::type('callable'))->resolves(function ($seconds, $callback) { return $callback(); }); @@ -1298,12 +1302,12 @@ public function testAtomicPassesLockAndWaitSecondsToLock(): void public function testAtomicPassesOwnerToLock(): void { - $store = m::mock(Store::class, LockProvider::class); + $store = Double::for(Store::class, LockProvider::class); $repo = new Repository($store); - $lock = m::mock(Lock::class); + $lock = Double::for(Lock::class); - $store->expects('lock')->with('foo', 10, 'my-owner')->andReturn($lock); - $lock->expects('block')->with(10, m::type('callable'))->andReturnUsing(function ($seconds, $callback) { + $store->expects('lock')->with('foo', 10, 'my-owner')->returns($lock); + $lock->expects('block')->with(10, Argument::type('callable'))->resolves(function ($seconds, $callback) { return $callback(); }); @@ -1375,11 +1379,11 @@ public function testManyDispatchesEventsForIntegerArrayKeys(): void $repo->put('1', 'cached', 60); $captured = []; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->andReturnUsing( + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->resolves( static fn (string $event): bool => in_array($event, [CacheHit::class, CacheMissed::class], true) ); - $dispatcher->shouldReceive('dispatch')->andReturnUsing(function (CacheHit|CacheMissed $event) use (&$captured): void { + $dispatcher->allows('dispatch')->resolves(function (CacheHit|CacheMissed $event) use (&$captured): void { $captured[] = $event; }); $repo->setEventDispatcher($dispatcher); @@ -1396,7 +1400,7 @@ public function testManyDispatchesEventsForIntegerArrayKeys(): void public function testItGetsAsString(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('bar'); + $repo->getStore()->expects('get')->with('foo')->returns('bar'); $this->assertSame('bar', $repo->string('foo')); } @@ -1406,7 +1410,7 @@ public function testItThrowsExceptionWhenGettingNonStringAsString(): void $this->expectExceptionObject(new InvalidArgumentException('Cache value for key [foo] must be a string, integer given.')); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(123); + $repo->getStore()->expects('get')->with('foo')->returns(123); $repo->string('foo'); } @@ -1414,7 +1418,7 @@ public function testItThrowsExceptionWhenGettingNonStringAsString(): void public function testItGetsAsStringWithDefault(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->twice()->with('foo')->andReturn(null); + $repo->getStore()->expects('get')->times(2)->with('foo')->returns(null); $this->assertSame('default', $repo->string('foo', 'default')); $this->assertSame('resolved', $repo->string('foo', fn (): string => 'resolved')); @@ -1423,7 +1427,7 @@ public function testItGetsAsStringWithDefault(): void public function testItGetsAsInteger(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(123); + $repo->getStore()->expects('get')->with('foo')->returns(123); $this->assertSame(123, $repo->integer('foo')); } @@ -1431,7 +1435,7 @@ public function testItGetsAsInteger(): void public function testItGetsAsIntegerFromNumericString(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('123'); + $repo->getStore()->expects('get')->with('foo')->returns('123'); $this->assertSame(123, $repo->integer('foo')); } @@ -1439,7 +1443,7 @@ public function testItGetsAsIntegerFromNumericString(): void public function testItGetsAsIntegerFromNumericStringable(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(new Stringable('123')); + $repo->getStore()->expects('get')->with('foo')->returns(new Stringable('123')); $this->assertSame(123, $repo->integer('foo')); } @@ -1450,7 +1454,7 @@ public function testIntegerTypedGetterThrowsExceptionForNonInteger(): void $this->expectExceptionMessageIsOrContains('Cache value for key [foo] must be an integer, array given.'); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(['bar']); + $repo->getStore()->expects('get')->with('foo')->returns(['bar']); $repo->integer('foo'); } @@ -1460,14 +1464,14 @@ public function testItThrowsExceptionWhenGettingNonIntegerAsInteger(): void $this->expectExceptionObject(new InvalidArgumentException('Cache value for key [foo] must be an integer, string given.')); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('bar'); + $repo->getStore()->expects('get')->with('foo')->returns('bar'); $repo->integer('foo'); } public function testItGetsAsIntegerWithDefault(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); + $repo->getStore()->expects('get')->with('foo')->returns(null); $this->assertSame(456, $repo->integer('foo', 456)); } @@ -1477,14 +1481,14 @@ public function testItThrowsExceptionWhenGettingFloatStringAsInteger(): void $this->expectExceptionObject(new InvalidArgumentException('Cache value for key [foo] must be an integer, string given.')); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('1.5'); + $repo->getStore()->expects('get')->with('foo')->returns('1.5'); $repo->integer('foo'); } public function testItGetsAsFloat(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(1.5); + $repo->getStore()->expects('get')->with('foo')->returns(1.5); $this->assertSame(1.5, $repo->float('foo')); } @@ -1492,7 +1496,7 @@ public function testItGetsAsFloat(): void public function testItGetsAsFloatFromNumericString(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('1.5'); + $repo->getStore()->expects('get')->with('foo')->returns('1.5'); $this->assertSame(1.5, $repo->float('foo')); } @@ -1500,7 +1504,7 @@ public function testItGetsAsFloatFromNumericString(): void public function testItGetsAsFloatFromNumericStringable(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(new Stringable('1.5')); + $repo->getStore()->expects('get')->with('foo')->returns(new Stringable('1.5')); $this->assertSame(1.5, $repo->float('foo')); } @@ -1511,7 +1515,7 @@ public function testFloatTypedGetterThrowsExceptionForNonFloat(): void $this->expectExceptionMessageIsOrContains('Cache value for key [foo] must be a float, array given.'); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(['bar']); + $repo->getStore()->expects('get')->with('foo')->returns(['bar']); $repo->float('foo'); } @@ -1521,14 +1525,14 @@ public function testItThrowsExceptionWhenGettingNonFloatAsFloat(): void $this->expectExceptionObject(new InvalidArgumentException('Cache value for key [foo] must be a float, string given.')); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('bar'); + $repo->getStore()->expects('get')->with('foo')->returns('bar'); $repo->float('foo'); } public function testItGetsAsFloatWithDefault(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); + $repo->getStore()->expects('get')->with('foo')->returns(null); $this->assertSame(2.5, $repo->float('foo', 2.5)); } @@ -1536,7 +1540,7 @@ public function testItGetsAsFloatWithDefault(): void public function testItGetsAsBoolean(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(true); + $repo->getStore()->expects('get')->with('foo')->returns(true); $this->assertTrue($repo->boolean('foo')); } @@ -1544,7 +1548,7 @@ public function testItGetsAsBoolean(): void public function testBooleanTypedGetterReturnsFalse(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(false); + $repo->getStore()->expects('get')->with('foo')->returns(false); $this->assertFalse($repo->boolean('foo')); } @@ -1555,7 +1559,7 @@ public function testBooleanTypedGetterThrowsExceptionForNonBoolean(): void $this->expectExceptionMessageIsOrContains('Cache value for key [foo] must be a boolean, string given.'); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('true'); + $repo->getStore()->expects('get')->with('foo')->returns('true'); $repo->boolean('foo'); } @@ -1565,14 +1569,14 @@ public function testItThrowsExceptionWhenGettingNonBooleanAsBoolean(): void $this->expectExceptionObject(new InvalidArgumentException('Cache value for key [foo] must be a boolean, string given.')); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('bar'); + $repo->getStore()->expects('get')->with('foo')->returns('bar'); $repo->boolean('foo'); } public function testItGetsAsBooleanWithDefault(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); + $repo->getStore()->expects('get')->with('foo')->returns(null); $this->assertFalse($repo->boolean('foo', false)); } @@ -1580,7 +1584,7 @@ public function testItGetsAsBooleanWithDefault(): void public function testItGetsAsArray(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(['bar', 'baz']); + $repo->getStore()->expects('get')->with('foo')->returns(['bar', 'baz']); $this->assertSame(['bar', 'baz'], $repo->array('foo')); } @@ -1588,7 +1592,7 @@ public function testItGetsAsArray(): void public function testArrayTypedGetterReturnsAssociativeArray(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(['key' => 'value']); + $repo->getStore()->expects('get')->with('foo')->returns(['key' => 'value']); $this->assertSame(['key' => 'value'], $repo->array('foo')); } @@ -1598,7 +1602,7 @@ public function testItThrowsExceptionWhenGettingNonArrayAsArray(): void $this->expectExceptionObject(new InvalidArgumentException('Cache value for key [foo] must be an array, string given.')); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn('bar'); + $repo->getStore()->expects('get')->with('foo')->returns('bar'); $repo->array('foo'); } @@ -1606,7 +1610,7 @@ public function testItThrowsExceptionWhenGettingNonArrayAsArray(): void public function testItGetsAsArrayWithDefault(): void { $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn(null); + $repo->getStore()->expects('get')->with('foo')->returns(null); $this->assertSame(['default'], $repo->array('foo', ['default'])); } @@ -1617,7 +1621,7 @@ public function testTypedGettersReportTypeMismatchesForEnumKeys(string $method, $this->expectExceptionObject(new InvalidArgumentException($message)); $repo = $this->getRepository(); - $repo->getStore()->expects('get')->with('foo')->andReturn($value); + $repo->getStore()->expects('get')->with('foo')->returns($value); $repo->{$method}(TestCacheKey::Foo); } @@ -1639,14 +1643,14 @@ public static function typedGetterTypeMismatchProvider(): array public function testRememberFiresEventsWithRedisStore(): void { - $store = m::mock(RedisStore::class); - $store->shouldNotReceive('withPinnedConnection'); - $store->expects('get')->with('foo')->andReturn(null); - $store->expects('put')->with('foo', 'bar', 10); + $store = Double::for(RedisStore::class); + $store->expects('withPinnedConnection')->never(); + $store->expects('get')->with('foo')->returns(null); + $store->expects('put')->with('foo', 'bar', 10)->returns(true); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch')->times(4); // RetrievingKey, CacheMissed, WritingKey, KeyWritten + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->expects('dispatch')->times(4); // RetrievingKey, CacheMissed, WritingKey, KeyWritten $repository = new Repository($store); $repository->setEventDispatcher($events); @@ -1658,14 +1662,14 @@ public function testRememberFiresEventsWithRedisStore(): void public function testRememberForeverFiresEventsWithRedisStore(): void { - $store = m::mock(RedisStore::class); - $store->shouldNotReceive('withPinnedConnection'); - $store->expects('get')->with('foo')->andReturn(null); - $store->expects('forever')->with('foo', 'bar'); + $store = Double::for(RedisStore::class); + $store->expects('withPinnedConnection')->never(); + $store->expects('get')->with('foo')->returns(null); + $store->expects('forever')->with('foo', 'bar')->returns(true); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch')->times(4); // RetrievingKey, CacheMissed, WritingKey, KeyWritten + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->expects('dispatch')->times(4); // RetrievingKey, CacheMissed, WritingKey, KeyWritten $repository = new Repository($store); $repository->setEventDispatcher($events); @@ -1677,13 +1681,13 @@ public function testRememberForeverFiresEventsWithRedisStore(): void public function testRememberHitFiresEventsWithRedisStore(): void { - $store = m::mock(RedisStore::class); - $store->shouldNotReceive('withPinnedConnection'); - $store->expects('get')->with('foo')->andReturn('cached'); + $store = Double::for(RedisStore::class); + $store->expects('withPinnedConnection')->never(); + $store->expects('get')->with('foo')->returns('cached'); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch')->twice(); // RetrievingKey, CacheHit + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->expects('dispatch')->times(2); // RetrievingKey, CacheHit $repository = new Repository($store); $repository->setEventDispatcher($events); @@ -1695,14 +1699,14 @@ public function testRememberHitFiresEventsWithRedisStore(): void public function testRememberSkipsDispatchWhenCacheEventsHaveNoListeners(): void { - $store = m::mock(RedisStore::class); - $store->shouldNotReceive('withPinnedConnection'); - $store->expects('get')->with('foo')->andReturn(null); + $store = Double::for(RedisStore::class); + $store->expects('withPinnedConnection')->never(); + $store->expects('get')->with('foo')->returns(null); $store->expects('put')->with('foo', 'bar', 10); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->times(4)->andReturn(false); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->times(4)->returns(false); + $events->expects('dispatch')->never(); $repository = new Repository($store); $repository->setEventDispatcher($events); @@ -1714,16 +1718,16 @@ public function testRememberSkipsDispatchWhenCacheEventsHaveNoListeners(): void public function testRememberNullableFiresEventsWithNullPayloadOnCacheMiss(): void { - $store = m::mock(RedisStore::class); - $store->shouldNotReceive('withPinnedConnection'); - $store->expects('get')->with('foo')->andReturn(null); - $store->expects('put')->with('foo', NullSentinel::VALUE, 10)->andReturn(true); + $store = Double::for(RedisStore::class); + $store->expects('withPinnedConnection')->never(); + $store->expects('get')->with('foo')->returns(null); + $store->expects('put')->with('foo', NullSentinel::VALUE, 10)->returns(true); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); @@ -1749,16 +1753,16 @@ public function testRememberNullableFiresEventsWithNullPayloadOnCacheMiss(): voi public function testRememberForeverNullableFiresEventsWithNullPayloadOnCacheMiss(): void { - $store = m::mock(RedisStore::class); - $store->shouldNotReceive('withPinnedConnection'); - $store->expects('get')->with('foo')->andReturn(null); - $store->expects('forever')->with('foo', NullSentinel::VALUE)->andReturn(true); + $store = Double::for(RedisStore::class); + $store->expects('withPinnedConnection')->never(); + $store->expects('get')->with('foo')->returns(null); + $store->expects('forever')->with('foo', NullSentinel::VALUE)->returns(true); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); @@ -1788,16 +1792,16 @@ public function testFlexibleNullableFiresEventsWithNullPayloadOnCacheMiss(): voi $repo->getStore() ->expects('many') ->with(['foo', 'hypervel:cache:flexible:created:foo']) - ->andReturn(['foo' => null, 'hypervel:cache:flexible:created:foo' => null]); + ->returns(['foo' => null, 'hypervel:cache:flexible:created:foo' => null]); $repo->getStore() ->expects('putMany') - ->andReturn(true); + ->returns(true); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); $repo->setEventDispatcher($events); @@ -1828,15 +1832,15 @@ public function testFlexibleNullableFiresEventsWithNullPayloadOnCacheMiss(): voi public function testRememberNullableFiresHitEventWithNullPayloadOnSentinelRetrieval(): void { - $store = m::mock(RedisStore::class); - $store->shouldNotReceive('withPinnedConnection'); - $store->expects('get')->with('foo')->andReturn(NullSentinel::VALUE); + $store = Double::for(RedisStore::class); + $store->expects('withPinnedConnection')->never(); + $store->expects('get')->with('foo')->returns(NullSentinel::VALUE); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); @@ -1865,10 +1869,10 @@ public function testManyFiresCacheHitWithNullPayloadForCachedNullEntry(): void // Capture only the many() read-path events by attaching the dispatcher // after the write. $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); $repo->setEventDispatcher($events); @@ -1886,13 +1890,13 @@ public function testManyFiresCacheHitWithNullPayloadForCachedNullEntry(): void public function testRememberWorksWithoutPinnableStore(): void { - $store = m::mock(ArrayStore::class); - $store->expects('get')->with('foo')->andReturn(null); + $store = Double::for(ArrayStore::class); + $store->expects('get')->with('foo')->returns(null); $store->expects('put')->with('foo', 'bar', 10); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch')->with(m::any())->andReturnNull(); + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch')->with(Argument::any())->returns(null); $repository = new Repository($store); $repository->setEventDispatcher($events); @@ -1909,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(m::mock(Store::class)); + $repository = new Repository(Double::for(Store::class)); $repository->setEventDispatcher($dispatcher); diff --git a/tests/Cache/ClearCommandTest.php b/tests/Cache/ClearCommandTest.php index 83a30f1e9..c056fe014 100644 --- a/tests/Cache/ClearCommandTest.php +++ b/tests/Cache/ClearCommandTest.php @@ -4,15 +4,19 @@ namespace Hypervel\Tests\Cache; -use BadMethodCallException; +use Hypervel\Cache\ArrayStore; use Hypervel\Cache\CacheManager; use Hypervel\Cache\Console\ClearCommand; -use Hypervel\Contracts\Cache\Repository; +use Hypervel\Cache\Repository; +use Hypervel\Contracts\Cache\CanFlushLocks; +use Hypervel\Contracts\Cache\Store; use Hypervel\Filesystem\Filesystem; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Command\Command as SymfonyCommand; use Symfony\Component\Console\Input\ArrayInput; @@ -20,13 +24,15 @@ class ClearCommandTest extends TestCase { + use VerifiesDoubles; + private ClearCommand $command; - private CacheManager&m\MockInterface $cacheManager; + private CacheManager&DoubleInterface $cacheManager; - private Filesystem&m\MockInterface $files; + private Filesystem&DoubleInterface $files; - private Repository&m\MockInterface $cacheRepository; + private Repository $cacheRepository; /** * Set up the command and its dependencies. @@ -38,41 +44,41 @@ protected function setUp(): void $app = new Application; $app->instance('path.storage', __DIR__); - $this->cacheManager = m::mock(CacheManager::class); - $this->files = m::mock(Filesystem::class); - $this->cacheRepository = m::mock(Repository::class); + $this->cacheManager = Double::for(CacheManager::class); + $this->files = Double::for(Filesystem::class); + $this->cacheRepository = new Repository(new ArrayStore); $this->command = new ClearCommand($this->cacheManager, $this->files); $this->command->setHypervel($app); } - #[DataProvider('flushResults')] - public function testClearWithNoStoreArgument(bool $successful, int $exitCode): void + public function testClearWithNoStoreArgument(): void { $this->files->expects('deleteDirectory'); - $this->cacheManager->expects('store')->with(null)->andReturn($this->cacheRepository); - $this->cacheRepository->expects('flush')->andReturn($successful); + $this->cacheRepository->put('foo', 'bar'); + $this->cacheManager->expects('store')->with(null)->returns($this->cacheRepository); + + $this->assertSame(SymfonyCommand::SUCCESS, $this->runCommand($this->command)); - $this->assertSame($exitCode, $this->runCommand($this->command)); + $this->assertNull($this->cacheRepository->get('foo')); } - /** - * Provide successful and failed cache flush results. - */ - public static function flushResults(): array + public function testClearWillFailWhenFlushFails(): void { - return [ - [true, SymfonyCommand::SUCCESS], - [false, SymfonyCommand::FAILURE], - ]; + $store = Double::for(Store::class); + $store->expects('flush')->returns(false); + $this->cacheManager->expects('store')->with(null)->returns(new Repository($store)); + $this->files->expects('deleteDirectory'); + + $this->assertSame(SymfonyCommand::FAILURE, $this->runCommand($this->command)); } #[DataProvider('prohibitedOptions')] public function testProhibitedCommandDoesNotClearCacheOrLocks(array $options): void { ClearCommand::prohibit(); - $this->cacheManager->shouldNotReceive('store'); - $this->files->shouldNotReceive('deleteDirectory'); + $this->cacheManager->expects('store')->never(); + $this->files->expects('deleteDirectory')->never(); $this->assertSame(SymfonyCommand::FAILURE, $this->runCommand($this->command, $options)); } @@ -89,18 +95,20 @@ public function testClearWithStoreArgument(): void { $this->files->expects('deleteDirectory'); - $this->cacheManager->expects('store')->with('foo')->andReturn($this->cacheRepository); - $this->cacheRepository->expects('flush')->andReturnTrue(); + $this->cacheRepository->put('foo', 'bar'); + $this->cacheManager->expects('store')->with('foo')->returns($this->cacheRepository); $this->runCommand($this->command, ['store' => 'foo']); + + $this->assertNull($this->cacheRepository->get('foo')); } public function testClearWithInvalidStoreArgument(): void { - $this->cacheManager->expects('store')->with('bar')->andThrow(InvalidArgumentException::class); - $this->cacheRepository->shouldReceive('flush')->never(); - $this->expectException(InvalidArgumentException::class); + + $this->cacheManager->expects('store')->with('bar')->throws(new InvalidArgumentException); + $this->runCommand($this->command, ['store' => 'bar']); } @@ -108,30 +116,35 @@ public function testClearWithTagsOption(): void { $this->files->expects('deleteDirectory'); - $this->cacheManager->expects('store')->with(null)->andReturn($this->cacheRepository); - $this->cacheRepository->expects('tags')->with(['foo', 'bar'])->andReturn($this->cacheRepository); - $this->cacheRepository->expects('flush')->andReturnTrue(); + $this->cacheRepository->tags(['foo', 'bar'])->put('tagged', 'value'); + $this->cacheRepository->put('untagged', 'value'); + $this->cacheManager->expects('store')->with(null)->returns($this->cacheRepository); $this->runCommand($this->command, ['--tags' => 'foo,bar']); + + $this->assertNull($this->cacheRepository->tags(['foo', 'bar'])->get('tagged')); + $this->assertSame('value', $this->cacheRepository->get('untagged')); } public function testClearWithStoreArgumentAndTagsOption(): void { $this->files->expects('deleteDirectory'); - $this->cacheManager->expects('store')->with('redis')->andReturn($this->cacheRepository); - $this->cacheRepository->expects('tags')->with(['foo'])->andReturn($this->cacheRepository); - $this->cacheRepository->expects('flush')->andReturnTrue(); + $this->cacheRepository->tags(['foo'])->put('tagged', 'value'); + $this->cacheRepository->put('untagged', 'value'); + $this->cacheManager->expects('store')->with('redis')->returns($this->cacheRepository); $this->runCommand($this->command, ['store' => 'redis', '--tags' => 'foo']); + + $this->assertNull($this->cacheRepository->tags(['foo'])->get('tagged')); + $this->assertSame('value', $this->cacheRepository->get('untagged')); } // REMOVED: real-time facade cleanup tests; Hypervel supports explicit facades only. public function testClearWillFlushAopProxyDirectory(): void { - $this->cacheManager->expects('store')->with(null)->andReturn($this->cacheRepository); - $this->cacheRepository->expects('flush')->andReturnTrue(); + $this->cacheManager->expects('store')->with(null)->returns($this->cacheRepository); $this->files->expects('deleteDirectory')->with($this->command->getHypervel()->bootstrapPath('cache/aop')); @@ -140,51 +153,63 @@ public function testClearWillFlushAopProxyDirectory(): void public function testClearLocksWithNoStoreArgument(): void { - $this->cacheManager->expects('store')->with(null)->andReturn($this->cacheRepository); - $this->cacheRepository->expects('flushLocks')->andReturn(true); - $this->cacheRepository->shouldNotReceive('flush'); + $store = $this->lockFlushingStore(); + $store->expects('flushLocks')->returns(true); + $store->expects('flush')->never(); + $this->cacheManager->expects('store')->with(null)->returns(new Repository($store)); - $this->files->shouldNotReceive('deleteDirectory'); + $this->files->expects('deleteDirectory')->never(); $this->assertSame(0, $this->runCommand($this->command, ['--locks' => true])); } public function testClearLocksWithStoreArgument(): void { - $this->cacheManager->expects('store')->with('redis')->andReturn($this->cacheRepository); - $this->cacheRepository->expects('flushLocks')->andReturn(true); - $this->cacheRepository->shouldNotReceive('flush'); + $store = $this->lockFlushingStore(); + $store->expects('flushLocks')->returns(true); + $store->expects('flush')->never(); + $this->cacheManager->expects('store')->with('redis')->returns(new Repository($store)); $this->assertSame(0, $this->runCommand($this->command, ['store' => 'redis', '--locks' => true])); } public function testClearLocksCannotBeUsedWithTags(): void { - $this->cacheManager->shouldNotReceive('store'); - $this->cacheRepository->shouldNotReceive('flush'); - $this->cacheRepository->shouldNotReceive('flushLocks'); + $this->cacheManager->expects('store')->never(); $this->assertSame(1, $this->runCommand($this->command, ['--locks' => true, '--tags' => 'foo'])); } public function testClearLocksWillFailWhenNotSupportedByStore(): void { - $this->cacheManager->expects('store')->with(null)->andReturn($this->cacheRepository); - $this->cacheRepository->expects('flushLocks')->andThrow(new BadMethodCallException); - $this->cacheRepository->shouldNotReceive('flush'); + $store = Double::for(Store::class); + $store->expects('flush')->never(); + $this->cacheManager->expects('store')->with(null)->returns(new Repository($store)); $this->assertSame(1, $this->runCommand($this->command, ['--locks' => true])); } public function testClearLocksWillFailWhenFlushLocksFails(): void { - $this->cacheManager->expects('store')->with(null)->andReturn($this->cacheRepository); - $this->cacheRepository->expects('flushLocks')->andReturn(false); - $this->cacheRepository->shouldNotReceive('flush'); + $store = $this->lockFlushingStore(); + $store->expects('flushLocks')->returns(false); + $store->expects('flush')->never(); + $this->cacheManager->expects('store')->with(null)->returns(new Repository($store)); $this->assertSame(1, $this->runCommand($this->command, ['--locks' => true])); } + /** + * Create a store that supports clearing locks. + */ + protected function lockFlushingStore(): Store&CanFlushLocks&DoubleInterface + { + $store = Double::for(Store::class, CanFlushLocks::class); + $store->allows('supportsFlushingLocks')->returns(true); + + return $store; + } + /** * Run the cache clear command with the given input. */ diff --git a/tests/Cache/Redis/Operations/PutManyTest.php b/tests/Cache/Redis/Operations/PutManyTest.php index fe2783958..cdaf8df1b 100644 --- a/tests/Cache/Redis/Operations/PutManyTest.php +++ b/tests/Cache/Redis/Operations/PutManyTest.php @@ -28,7 +28,7 @@ public function testPutManyUsesLuaScriptInStandardMode(): void $this->assertSame('prefix:baz', $keys[1]); $this->assertSame('prefix:bar', $keys[2]); // Args: [ttl, val1, val2, val3] - $this->assertSame(60, $args[0]); // TTL + $this->assertSame([60, serialize('bar'), serialize('qux'), serialize('norf')], $args); return true; }) diff --git a/tests/Cache/Redis/RedisStoreTest.php b/tests/Cache/Redis/RedisStoreTest.php index 181c796ef..2bdd3d27e 100644 --- a/tests/Cache/Redis/RedisStoreTest.php +++ b/tests/Cache/Redis/RedisStoreTest.php @@ -4,10 +4,12 @@ namespace Hypervel\Tests\Cache\Redis; +use __PHP_Incomplete_Class; use Hypervel\Cache\Redis\AllTaggedCache; use Hypervel\Cache\Redis\AnyTaggedCache; use Hypervel\Cache\RedisLock; use Hypervel\Cache\RedisStore; +use Hypervel\Cache\SerializableClassPolicy; use Hypervel\Cache\TagMode; use Hypervel\Contracts\Redis\Factory as Redis; use Hypervel\Redis\RedisProxy; @@ -17,25 +19,52 @@ use ReflectionClass; use ReflectionNamedType; use ReflectionProperty; +use stdClass; -/** - * Tests for RedisStore core functionality. - * - * Operation-specific tests have been moved to the Operations/ directory. - * This file contains only store-level tests (prefix, connection, tags, locks). - */ class RedisStoreTest extends RedisCacheTestCase { - public function testGetAndSetPrefix(): void + public function testSerializableClassesControlRedisValues(): void + { + $denyingConnection = $this->mockConnection(); + $denyingConnection->expects('get') + ->with('prefix:object') + ->andReturn(serialize(new stdClass)); + $allowingConnection = $this->mockConnection(); + $allowingConnection->expects('get') + ->with('prefix:object') + ->andReturn(serialize(new stdClass)); + + $denyingStore = new RedisStore( + $this->createRedisFactory($denyingConnection), + 'prefix:', + 'default', + false, + ); + $allowingStore = new RedisStore( + $this->createRedisFactory($allowingConnection), + 'prefix:', + 'default', + serializableClasses: [stdClass::class], + ); + + $this->assertInstanceOf(__PHP_Incomplete_Class::class, $denyingStore->get('object')); + $this->assertInstanceOf(stdClass::class, $allowingStore->get('object')); + } + + public function testSerializableClassPolicyControlsRedisValues(): void { $connection = $this->mockConnection(); - $redis = $this->createStore($connection); + $connection->expects('get') + ->with('prefix:object') + ->andReturn(serialize(new stdClass)); + $store = new RedisStore( + $this->createRedisFactory($connection), + 'prefix:', + 'default', + serializableClassPolicy: new SerializableClassPolicy(static fn (): false => false), + ); - $this->assertSame('prefix:', $redis->getPrefix()); - $redis->setPrefix('foo:'); - $this->assertSame('foo:', $redis->getPrefix()); - $redis->setPrefix(''); - $this->assertEmpty($redis->getPrefix()); + $this->assertInstanceOf(__PHP_Incomplete_Class::class, $store->get('object')); } public function testCounterFailuresAreReturnedWithoutCoercion(): void diff --git a/tests/Console/CacheCommandMutexTest.php b/tests/Console/CacheCommandMutexTest.php index a205bbf98..f095f6931 100644 --- a/tests/Console/CacheCommandMutexTest.php +++ b/tests/Console/CacheCommandMutexTest.php @@ -11,18 +11,22 @@ use Hypervel\Contracts\Cache\Repository; use Hypervel\Contracts\Cache\Store; use Hypervel\Testbench\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class CacheCommandMutexTest extends TestCase { + use VerifiesDoubles; + protected CacheCommandMutex $mutex; protected Command $command; - protected Factory&MockInterface $cacheFactory; + protected Factory&DoubleInterface $cacheFactory; - protected Repository&MockInterface $cacheRepository; + protected Repository&DoubleInterface $cacheRepository; /** * Set up the command mutex and its dependencies. @@ -31,8 +35,8 @@ protected function setUp(): void { parent::setUp(); - $this->cacheFactory = m::mock(Factory::class); - $this->cacheRepository = m::mock(Repository::class); + $this->cacheFactory = Double::for(Factory::class); + $this->cacheRepository = Double::for(Repository::class); $this->mutex = new CacheCommandMutex($this->cacheFactory); $this->command = new class extends Command { protected ?string $name = 'command-name'; @@ -42,7 +46,7 @@ protected function setUp(): void public function testCanCreateMutex(): void { $this->mockUsingCacheStore(); - $this->cacheRepository->expects('add')->andReturn(true); + $this->cacheRepository->expects('add')->returns(true); $actual = $this->mutex->create($this->command); $this->assertTrue($actual); @@ -51,7 +55,7 @@ public function testCanCreateMutex(): void public function testCannotCreateMutexIfAlreadyExist(): void { $this->mockUsingCacheStore(); - $this->cacheRepository->expects('add')->andReturn(false); + $this->cacheRepository->expects('add')->returns(false); $actual = $this->mutex->create($this->command); $this->assertFalse($actual); @@ -60,7 +64,7 @@ public function testCannotCreateMutexIfAlreadyExist(): void public function testCanCreateMutexWithCustomConnection(): void { $this->mockUsingCacheStore('test'); - $this->cacheRepository->expects('add')->andReturn(false); + $this->cacheRepository->expects('add')->returns(false); $this->mutex->useStore('test'); $actual = $this->mutex->create($this->command); @@ -70,8 +74,8 @@ public function testCanCreateMutexWithCustomConnection(): void public function testCanCreateMutexWithLockProvider(): void { - $this->cacheFactory->expects('store')->with(null)->andReturn($this->cacheRepository); - $this->cacheRepository->expects('getStore')->andReturn(new ArrayStore); + $this->cacheFactory->expects('store')->with(null)->returns($this->cacheRepository); + $this->cacheRepository->expects('getStore')->returns(new ArrayStore); $actual = $this->mutex->create($this->command); @@ -81,8 +85,8 @@ public function testCanCreateMutexWithLockProvider(): void public function testCannotCreateMutexIfAlreadyExistWithLockProvider(): void { $store = new ArrayStore; - $this->cacheFactory->expects('store')->twice()->with(null)->andReturn($this->cacheRepository); - $this->cacheRepository->expects('getStore')->twice()->andReturn($store); + $this->cacheFactory->expects('store')->times(2)->with(null)->returns($this->cacheRepository); + $this->cacheRepository->expects('getStore')->times(2)->returns($store); $this->mutex->create($this->command); $actual = $this->mutex->create($this->command); @@ -93,8 +97,8 @@ public function testCannotCreateMutexIfAlreadyExistWithLockProvider(): void public function testExistsProbesLockWithoutTakingOwnership(): void { $store = new ArrayStore; - $this->cacheFactory->shouldReceive('store')->andReturn($this->cacheRepository); - $this->cacheRepository->shouldReceive('getStore')->andReturn($store); + $this->cacheFactory->allows('store')->returns($this->cacheRepository); + $this->cacheRepository->allows('getStore')->returns($store); $this->assertFalse($this->mutex->exists($this->command)); $this->assertTrue($this->mutex->create($this->command)); @@ -105,8 +109,8 @@ public function testExistsProbesLockWithoutTakingOwnership(): void public function testCanForgetMutexWithLockProvider(): void { $store = new ArrayStore; - $this->cacheFactory->shouldReceive('store')->andReturn($this->cacheRepository); - $this->cacheRepository->shouldReceive('getStore')->andReturn($store); + $this->cacheFactory->allows('store')->returns($this->cacheRepository); + $this->cacheRepository->allows('getStore')->returns($store); $this->assertTrue($this->mutex->create($this->command)); $this->assertTrue($this->mutex->forget($this->command)); @@ -115,8 +119,8 @@ public function testCanForgetMutexWithLockProvider(): void public function testCanCreateMutexWithCustomConnectionWithLockProvider(): void { - $this->cacheFactory->expects('store')->with('test')->andReturn($this->cacheRepository); - $this->cacheRepository->expects('getStore')->andReturn(new ArrayStore); + $this->cacheFactory->expects('store')->with('test')->returns($this->cacheRepository); + $this->cacheRepository->expects('getStore')->returns(new ArrayStore); $this->mutex->useStore('test'); $actual = $this->mutex->create($this->command); @@ -129,8 +133,8 @@ public function testCanCreateMutexWithCustomConnectionWithLockProvider(): void */ private function mockUsingCacheStore(?string $store = null): void { - $this->cacheFactory->expects('store')->with($store)->andReturn($this->cacheRepository); - $this->cacheRepository->expects('getStore')->andReturn(m::mock(Store::class)); + $this->cacheFactory->expects('store')->with($store)->returns($this->cacheRepository); + $this->cacheRepository->expects('getStore')->returns(Double::for(Store::class)); } public function testCommandMutexNameWithoutIsolatedMutexNameMethod(): void @@ -138,12 +142,8 @@ public function testCommandMutexNameWithoutIsolatedMutexNameMethod(): void $this->mockUsingCacheStore(); $this->cacheRepository->expects('add') - ->withArgs(function (string $key): bool { - $this->assertSame('framework' . DIRECTORY_SEPARATOR . 'command-command-name', $key); - - return true; - }) - ->andReturn(true); + ->with('framework' . DIRECTORY_SEPARATOR . 'command-command-name', Argument::remaining()) + ->returns(true); $this->mutex->create($this->command); } @@ -165,12 +165,8 @@ public function isolatableId(): string $this->mockUsingCacheStore(); $this->cacheRepository->expects('add') - ->withArgs(function (string $key): bool { - $this->assertSame('framework' . DIRECTORY_SEPARATOR . 'command-command-name-isolated', $key); - - return true; - }) - ->andReturn(true); + ->with('framework' . DIRECTORY_SEPARATOR . 'command-command-name-isolated', Argument::remaining()) + ->returns(true); $this->mutex->create($command); } diff --git a/tests/Console/CommandMutexTest.php b/tests/Console/CommandMutexTest.php index 424eb8956..0046af83f 100644 --- a/tests/Console/CommandMutexTest.php +++ b/tests/Console/CommandMutexTest.php @@ -17,8 +17,10 @@ use Hypervel\Testbench\TestCase; use Hypervel\Tests\Cache\Fixtures\ArrayFilesystem; use Hypervel\Tests\Console\Fixtures\FakeCacheFactory; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -30,6 +32,8 @@ class CommandMutexTest extends TestCase { + use VerifiesDoubles; + protected Command $command; protected CommandMutex $commandMutex; @@ -109,13 +113,14 @@ public function testCanRunCommandAgainNonAutomated(): void public function testCommandReleasesTheExactMutexInstanceThatItAcquired(): void { - $acquiredMutex = m::mock(CommandMutex::class); - $unusedMutex = m::mock(CommandMutex::class); + $acquiredMutex = Double::for(CommandMutex::class); + $unusedMutex = Double::for(CommandMutex::class); $resolutions = 0; - $acquiredMutex->shouldReceive('create')->once()->with($this->command)->andReturnTrue(); - $acquiredMutex->shouldReceive('forget')->once()->with($this->command)->andReturnTrue(); - $unusedMutex->shouldReceive('create', 'forget')->never(); + $acquiredMutex->expects('create')->with(Argument::same($this->command))->returns(true); + $acquiredMutex->expects('forget')->with(Argument::same($this->command))->returns(true); + $unusedMutex->expects('create')->never(); + $unusedMutex->expects('forget')->never(); $this->app->bind(CommandMutex::class, function () use ($acquiredMutex, $unusedMutex, &$resolutions) { return $resolutions++ === 0 ? $acquiredMutex : $unusedMutex; @@ -160,8 +165,8 @@ static function () use (&$events, $event): void { } $commandMutex = $this->mockCommandMutex(); - $commandMutex->shouldReceive('create')->once()->with($command)->andReturnTrue(); - $commandMutex->shouldReceive('forget')->once()->with($command)->andReturnTrue(); + $commandMutex->expects('create')->with(Argument::same($command))->returns(true); + $commandMutex->expects('forget')->with(Argument::same($command))->returns(true); $command->run( new ArrayInput(['--isolated' => true]), @@ -177,8 +182,8 @@ static function () use (&$events, $event): void { public function testAfterExecuteFailureStillReleasesMutex(): void { $commandMutex = $this->mockCommandMutex(); - $commandMutex->shouldReceive('create')->once()->andReturnTrue(); - $commandMutex->shouldReceive('forget')->once()->andReturnTrue(); + $commandMutex->expects('create')->returns(true); + $commandMutex->expects('forget')->returns(true); $this->app->make(Dispatcher::class)->listen( AfterExecute::class, @@ -202,8 +207,8 @@ public function __invoke(): void $command->setHypervel($this->app); $commandMutex = $this->mockCommandMutex(); - $commandMutex->shouldReceive('create')->once()->andReturnTrue(); - $commandMutex->shouldReceive('forget')->once()->andThrow(new RuntimeException('mutex release failed')); + $commandMutex->expects('create')->returns(true); + $commandMutex->expects('forget')->throws(new RuntimeException('mutex release failed')); $this->app->make(Dispatcher::class)->listen( AfterExecute::class, @@ -233,8 +238,8 @@ public function __invoke(): void $cleanup = $cleanupThrows ? new RuntimeException('Observer cleanup failed.') : null; $commandMutex = $this->mockCommandMutex(); - $commandMutex->shouldReceive('create')->once()->andReturnTrue(); - $commandMutex->shouldReceive('forget')->once()->andReturnTrue(); + $commandMutex->expects('create')->returns(true); + $commandMutex->expects('forget')->returns(true); $this->app->make(Dispatcher::class)->listen( AfterExecute::class, static function () use ($cancellation, $cleanup): never { @@ -271,8 +276,8 @@ public function __invoke(): void $cleanup = $cleanupThrows ? new RuntimeException('Mutex cleanup failed.') : null; $commandMutex = $this->mockCommandMutex(); - $commandMutex->shouldReceive('create')->once()->andReturnTrue(); - $commandMutex->shouldReceive('forget')->once()->andReturnUsing(static function () use ($cancellation, $cleanup): never { + $commandMutex->expects('create')->returns(true); + $commandMutex->expects('forget')->resolves(static function () use ($cancellation, $cleanup): never { try { throw $cancellation; } finally { @@ -308,8 +313,8 @@ public function __invoke(): void $observed = null; $commandMutex = $this->mockCommandMutex(); - $commandMutex->shouldReceive('create')->once()->andReturnTrue(); - $commandMutex->shouldReceive('forget')->once()->andReturnTrue(); + $commandMutex->expects('create')->returns(true); + $commandMutex->expects('forget')->returns(true); $this->app->make(Dispatcher::class)->listen( AfterExecute::class, function (AfterExecute $event) use (&$observed): void { @@ -330,9 +335,9 @@ function (AfterExecute $event) use (&$observed): void { /** * Replace the bound command mutex with a mock. */ - protected function mockCommandMutex(): CommandMutex&MockInterface + protected function mockCommandMutex(): CommandMutex&DoubleInterface { - $commandMutex = m::mock(CommandMutex::class); + $commandMutex = Double::for(CommandMutex::class); $this->app->instance(CommandMutex::class, $commandMutex); diff --git a/tests/Console/CommandTest.php b/tests/Console/CommandTest.php index d9c766cc1..ff84213bb 100644 --- a/tests/Console/CommandTest.php +++ b/tests/Console/CommandTest.php @@ -30,7 +30,9 @@ use Hypervel\Tests\Console\Fixtures\Commands\FooTraitCommand; use Hypervel\Tests\Console\Fixtures\Commands\SwooleFlagsCommand; use Hypervel\Tests\Console\Fixtures\Commands\Traits\Foo; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use stdClass; use Symfony\Component\Console\Application as ConsoleApplication; @@ -49,6 +51,7 @@ enum CommandInputType: string class CommandTest extends TestCase { use CreatesAnsweredOutputStyles; + use VerifiesDoubles; public function testHookFlags(): void { @@ -61,17 +64,17 @@ public function testHookFlags(): void public function testExceptionPropagatesFromExecute(): void { - $output = m::mock(OutputStyle::class)->shouldIgnoreMissing(); - $application = m::mock(ConsoleApplication::class); - $application->shouldReceive('getHelperSet'); + $output = Double::for(OutputStyle::class); + $application = Double::for(ConsoleApplication::class); + $application->allows('getHelperSet'); $instance = new FooExceptionCommand('foo'); $instance->setHypervel($this->app); $command = new ClassInvoker($instance); $command->setApplication($application); $command->setOutput($output); - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption')->andReturn(true); + $input = Double::for(InputInterface::class); + $input->allows('getOption')->returns(true); $this->expectException(RuntimeException::class); $command->execute($input, $output); @@ -79,11 +82,11 @@ public function testExceptionPropagatesFromExecute(): void public function testExitCodeFromExitExceptionAndNormalCommand(): void { - $output = m::mock(OutputStyle::class)->shouldIgnoreMissing(); - $application = m::mock(ConsoleApplication::class); - $application->shouldReceive('getHelperSet'); - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption')->andReturn(true); + $output = Double::for(OutputStyle::class); + $application = Double::for(ConsoleApplication::class); + $application->allows('getHelperSet'); + $input = Double::for(InputInterface::class); + $input->allows('getOption')->returns(true); /** @var FooExitCommand $command */ $instance = new FooExitCommand; @@ -106,11 +109,11 @@ public function testExitCodeFromExitExceptionAndNormalCommand(): void public function testSetUpTraits(): void { - $output = m::mock(OutputStyle::class)->shouldIgnoreMissing(); - $application = m::mock(ConsoleApplication::class); - $application->shouldReceive('getHelperSet'); - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption')->andReturnFalse(); + $output = Double::for(OutputStyle::class); + $application = Double::for(ConsoleApplication::class); + $application->allows('getHelperSet'); + $input = Double::for(InputInterface::class); + $input->allows('getOption')->returns(false); $command = new FooTraitCommand; $command->setApplication($application); @@ -122,9 +125,9 @@ public function testSetUpTraits(): void public function testSignalHandlersAreRemovedWhenTraitSetupFails(): void { $command = new CommandTestFailingTraitSetupCommand; - $registry = m::mock(SignalRegistry::class); - $registry->expects('register')->with($command, SIGTERM, m::type('callable')); - $registry->expects('unregister')->with($command, null); + $registry = Double::for(SignalRegistry::class); + $registry->expects('register')->with(Argument::same($command), SIGTERM, Argument::type('callable')); + $registry->expects('unregister')->with(Argument::same($command), null); $command->setHypervel($this->app); $command->setSignalRegistryForTest($registry); @@ -236,31 +239,31 @@ public function handle(): never public function testProhibitableCommand(): void { - $application = m::mock(ConsoleApplication::class); - $application->shouldReceive('getHelperSet'); + $application = Double::for(ConsoleApplication::class); + $application->allows('getHelperSet'); - $output = m::mock(OutputStyle::class)->shouldIgnoreMissing(); + $output = Double::for(OutputStyle::class); $instance = new FooProhibitableCommand; $instance->setHypervel($this->app); $command = new ClassInvoker($instance); $command->setApplication($application); $command->setOutput($output); - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption')->andReturn(true); + $input = Double::for(InputInterface::class); + $input->allows('getOption')->returns(true); $result = $command->execute($input, $output); $this->assertSame(FooProhibitableCommand::SUCCESS, $result); FooProhibitableCommand::prohibit(true); - $output = m::mock(OutputStyle::class)->shouldIgnoreMissing(); + $output = Double::for(OutputStyle::class); $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 = m::mock(InputInterface::class); - $input->shouldReceive('getOption')->andReturn(true); + $input = Double::for(InputInterface::class); + $input->allows('getOption')->returns(true); $result = $command->execute($input, $output); $this->assertSame(FooProhibitableCommand::FAILURE, $result); @@ -320,28 +323,29 @@ public function handle(): void } }; - $application = m::mock(Application::class); - $command->setHypervel($application); + $application = Double::for(Application::class, override: true); + $hypervel = $application->instance(); + $command->setHypervel($hypervel); $input = new ArrayInput([]); $output = new NullOutput; $outputStyle = new OutputStyle($input, $output); - $application->expects('make')->with(OutputStyle::class, ['input' => $input, 'output' => $output])->andReturn($outputStyle); - $application->expects('make')->with(Factory::class, ['output' => $outputStyle])->andReturn(new Factory($outputStyle)); - $application->shouldReceive('bound')->andReturn(false); + $application->expects('make')->with(OutputStyle::class, ['input' => $input, 'output' => $output])->returns($outputStyle); + $application->expects('make')->with(Factory::class, ['output' => $outputStyle])->returns(new Factory($outputStyle)); + $application->allows('bound')->returns(false); - $application->expects('call')->with([$command, 'handle'])->andReturnUsing(function () use ($command, $application): void { - $commandCalled = m::mock(Command::class); + $application->expects('call')->with([$command, 'handle'])->resolves(function () use ($command, $application, $hypervel): void { + $commandCalled = Double::for(Command::class); - $application->expects('make')->with(Command::class)->andReturn($commandCalled); + $application->expects('make')->with(Command::class)->returns($commandCalled); $commandCalled->expects('setApplication')->with(null); - $commandCalled->expects('setHypervel')->with($application); + $commandCalled->expects('setHypervel')->with(Argument::same($hypervel)); $commandCalled->expects('run'); $command->call(Command::class); }); - $application->shouldReceive('runningUnitTests')->andReturn(true); + $application->allows('runningUnitTests')->returns(true); $command->run($input, $output); } @@ -501,10 +505,8 @@ public function testTheInputSetterOverwrite(): void public function testTheOutputSetterOverwrite(): void { - $output = m::mock(OutputStyle::class); - $output->expects('writeln')->withArgs(function (...$args) { - return $args[0] === 'foo'; - }); + $output = Double::for(OutputStyle::class); + $output->expects('writeln')->with('foo', Argument::remaining()); $command = new CommandTestStubCommand; $command->setOutput($output); diff --git a/tests/Console/ConsoleApplicationTest.php b/tests/Console/ConsoleApplicationTest.php index c2fc6b87e..768c190a0 100644 --- a/tests/Console/ConsoleApplicationTest.php +++ b/tests/Console/ConsoleApplicationTest.php @@ -14,7 +14,9 @@ use Hypervel\Testbench\TestCase; use Hypervel\Tests\Console\Fixtures\FakeCommandWithArrayInputPrompting; use Hypervel\Tests\Console\Fixtures\FakeCommandWithInputPrompting; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionProperty; use Symfony\Component\Console\Application as SymfonyApplication; use Symfony\Component\Console\Attribute\AsCommand; @@ -27,6 +29,8 @@ class ConsoleApplicationTest extends TestCase { + use VerifiesDoubles; + /** * Create a console application for command resolution. */ @@ -227,8 +231,8 @@ public function testAddSetsHypervelInstance(): void { $artisan = $this->getMockConsole(['addToParent']); - $command = m::mock(Command::class); - $command->shouldReceive('setHypervel')->once()->with(m::type(Application::class)); + $command = Double::for(Command::class); + $command->expects('setHypervel')->with(Argument::type(Application::class)); $artisan->expects($this->once())->method('addToParent')->with($command)->willReturn($command); $result = $artisan->add($command); @@ -575,12 +579,13 @@ private function getCommandLoader(ConsoleApplication $app): ?ContainerCommandLoa */ private function getMockConsole(array $methods): ConsoleApplication { - $app = m::mock(Application::class, ['version' => '1.0']); + $app = Double::for(Application::class, override: true); + $app->allows('version')->returns('1.0'); $events = new EventsDispatcher; return $this->getMockBuilder(ConsoleApplication::class) ->onlyMethods($methods) - ->setConstructorArgs([$app, $events, '1.0']) + ->setConstructorArgs([$app->instance(), $events, '1.0']) ->getMock(); } } diff --git a/tests/Console/Scheduling/EventTest.php b/tests/Console/Scheduling/EventTest.php index 960921df0..333ad71d3 100644 --- a/tests/Console/Scheduling/EventTest.php +++ b/tests/Console/Scheduling/EventTest.php @@ -23,7 +23,9 @@ use Hypervel\Support\Stringable; use Hypervel\Tests\Console\Fixtures\FakeEventMutex; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -57,6 +59,8 @@ enum ScheduledEventTestEnvironment: string class EventTest extends TestCase { + use VerifiesDoubles; + protected ?Container $container = null; /** @@ -75,14 +79,13 @@ protected function setUp(): void public function testSendOutputToWithIsNotFile(): void { - $event = new Event(m::mock(EventMutex::class), 'php -v'); + $event = new Event(Double::for(EventMutex::class), 'php -v'); $event->sendOutputTo($output = 'test.log'); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile') - ->once() + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('isFile') ->with($output) - ->andReturn(false); + ->returns(false); $this->container->instance(Filesystem::class, $filesystem); $event->writeOutput($this->container); @@ -90,24 +93,21 @@ public function testSendOutputToWithIsNotFile(): void public function testSendOutputTo(): void { - $event = new Event(m::mock(EventMutex::class), 'php -v'); + $event = new Event(Double::for(EventMutex::class), 'php -v'); $event->sendOutputTo($output = 'test.log'); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('output') - ->once() - ->andReturn($result = 'PHP 8.3.17 (cli) (built: Feb 11 2025 22:03:03) (NTS)'); + $kernel = Double::for(KernelContract::class); + $kernel->expects('output') + ->returns($result = 'PHP 8.3.17 (cli) (built: Feb 11 2025 22:03:03) (NTS)'); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile') - ->once() + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('isFile') ->with($output) - ->andReturn(true); - $filesystem->shouldReceive('put') - ->once() + ->returns(true); + $filesystem->expects('put') ->with($output, $result) - ->andReturn(strlen($result)); + ->returns(strlen($result)); $this->container->instance(KernelContract::class, $kernel); $this->container->instance(Filesystem::class, $filesystem); @@ -117,22 +117,20 @@ public function testSendOutputTo(): void public function testSendOutputToWithSystemProcess(): void { - $event = new Event(m::mock(EventMutex::class), 'php -v'); + $event = new Event(Double::for(EventMutex::class), 'php -v'); $event->isSystem = true; $event->sendOutputTo($output = 'test.log'); - $process = m::mock(Process::class); - $process->shouldReceive('getOutput') - ->once() - ->andReturn($result = 'PHP 8.3.17 (cli) (built: Feb 11 2025 22:03:03) (NTS)'); + $process = Double::for(Process::class); + $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 = m::mock(Filesystem::class); - $filesystem->shouldReceive('put') - ->once() + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('put') ->with($output, $result) - ->andReturn(strlen($result)); + ->returns(strlen($result)); $this->container->instance(Filesystem::class, $filesystem); @@ -170,7 +168,7 @@ public function testEventRunsWhenMarkedAsEvenWhenPaused(): void public function testNeverCheckedRepeatableEventIsNotReadyToRepeat(): void { - $event = new Event(m::mock(EventMutex::class), 'php -i'); + $event = new Event(Double::for(EventMutex::class), 'php -i'); $event->repeatSeconds = 1; $this->assertFalse($event->shouldRepeatNow()); @@ -206,7 +204,7 @@ protected function execute(ContainerContract $container): int public function testRunResetsSkippedBecauseOverlapping(): void { - $eventMutex = m::mock(EventMutex::class); + $eventMutex = Double::for(EventMutex::class); $event = new class($eventMutex, 'php -i') extends Event { public int $executions = 0; @@ -221,8 +219,8 @@ protected function execute(ContainerContract $container): int } }; - $eventMutex->expects('create')->times(2)->with($event)->andReturn(false, true); - $eventMutex->expects('forget')->with($event); + $eventMutex->expects('create')->times(2)->with(Argument::same($event))->returns(false, true); + $eventMutex->expects('forget')->with(Argument::same($event)); $event->withoutOverlapping(); $this->assertNull($event->run($this->container)); @@ -236,9 +234,9 @@ protected function execute(ContainerContract $container): int public function testReleaseMutexOnTerminationSignalReleasesOwnedMutex(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->once()->andReturnTrue(); - $eventMutex->shouldReceive('forget')->once(); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->expects('create')->returns(true); + $eventMutex->expects('forget'); $event = new Event($eventMutex, 'php -i'); $event->withoutOverlapping(); @@ -250,8 +248,8 @@ public function testReleaseMutexOnTerminationSignalReleasesOwnedMutex(): void public function testReleaseMutexOnTerminationSignalDoesNotReleaseUnownedMutex(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldNotReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->expects('forget')->never(); $event = new Event($eventMutex, 'php -i'); $event->withoutOverlapping(); @@ -261,9 +259,9 @@ public function testReleaseMutexOnTerminationSignalDoesNotReleaseUnownedMutex(): public function testReleaseMutexOnTerminationSignalHonorsReleaseFlag(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->once()->andReturnTrue(); - $eventMutex->shouldNotReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->expects('create')->returns(true); + $eventMutex->expects('forget')->never(); $event = new Event($eventMutex, 'php -i'); $event->withoutOverlapping(releaseOnTerminationSignals: false); @@ -275,9 +273,9 @@ public function testReleaseMutexOnTerminationSignalHonorsReleaseFlag(): void public function testStartFailureRemainsPrimaryWhenMutexCleanupFails(): void { - $mutex = m::mock(EventMutex::class); - $mutex->shouldReceive('create')->once()->andReturnTrue(); - $mutex->shouldReceive('forget')->once()->andThrow(new RuntimeException('mutex cleanup failed')); + $mutex = Double::for(EventMutex::class); + $mutex->expects('create')->returns(true); + $mutex->expects('forget')->throws(new RuntimeException('mutex cleanup failed')); $event = new Event($mutex, 'php -i'); $event->withoutOverlapping(); @@ -296,9 +294,9 @@ public function testStartFailureRemainsPrimaryWhenMutexCleanupFails(): void public function testOutputFailureStillRunsAfterCallbacksAndReleasesMutex(): void { $afterCalled = false; - $mutex = m::mock(EventMutex::class); - $mutex->shouldReceive('create')->once()->andReturnTrue(); - $mutex->shouldReceive('forget')->once(); + $mutex = Double::for(EventMutex::class); + $mutex->expects('create')->returns(true); + $mutex->expects('forget'); $event = new EventTestExecutableEvent($mutex); $event->withoutOverlapping(); @@ -307,9 +305,9 @@ public function testOutputFailureStillRunsAfterCallbacksAndReleasesMutex(): void $afterCalled = true; }); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile')->once()->with($output)->andReturnTrue(); - $filesystem->shouldReceive('put')->once()->with($output, 'output')->andReturnFalse(); + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('isFile')->with($output)->returns(true); + $filesystem->expects('put')->with($output, 'output')->returns(false); $this->container->instance(Filesystem::class, $filesystem); try { @@ -325,9 +323,9 @@ public function testOutputFailureStillRunsAfterCallbacksAndReleasesMutex(): void public function testAfterCallbackFailureRemainsPrimaryWhenMutexCleanupFails(): void { - $mutex = m::mock(EventMutex::class); - $mutex->shouldReceive('create')->once()->andReturnTrue(); - $mutex->shouldReceive('forget')->once()->andThrow(new RuntimeException('mutex cleanup failed')); + $mutex = Double::for(EventMutex::class); + $mutex->expects('create')->returns(true); + $mutex->expects('forget')->throws(new RuntimeException('mutex cleanup failed')); $event = new EventTestExecutableEvent($mutex); $event->withoutOverlapping(); @@ -362,21 +360,21 @@ public function testCancellationDuringCleanupSupersedesAnEarlierFailure(string $ } } }; - $mutex = m::mock(EventMutex::class); - $mutex->shouldReceive('create')->once()->andReturnTrue(); + $mutex = Double::for(EventMutex::class); + $mutex->expects('create')->returns(true); $event = new EventTestExecutableEvent($mutex); $event->withoutOverlapping(); if ($failurePhase === 'output') { $event->sendOutputTo('test.log')->after($cancel); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile')->once()->with('test.log')->andReturnTrue(); - $filesystem->shouldReceive('put')->once()->with('test.log', 'output')->andReturnFalse(); + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('isFile')->with('test.log')->returns(true); + $filesystem->expects('put')->with('test.log', 'output')->returns(false); $this->container->instance(Filesystem::class, $filesystem); - $mutex->shouldReceive('forget')->once(); + $mutex->expects('forget'); } else { $event->{$failurePhase === 'start' ? 'before' : 'after'}(static fn () => throw new RuntimeException('Earlier failure.')); - $mutex->shouldReceive('forget')->once()->andReturnUsing($cancel); + $mutex->expects('forget')->resolves($cancel); } try { @@ -392,8 +390,8 @@ public function testCancellationDuringCleanupSupersedesAnEarlierFailure(string $ public function testExitPublicationFailureStillRunsCallbacksAndReleasesMutex(): void { $afterCalled = false; - $mutex = m::mock(EventMutex::class); - $mutex->shouldReceive('forget')->once(); + $mutex = Double::for(EventMutex::class); + $mutex->expects('forget'); $event = new EventTestFailingExitCodeEvent($mutex); $event->withoutOverlapping = true; @@ -414,24 +412,21 @@ public function testExitPublicationFailureStillRunsCallbacksAndReleasesMutex(): public function testAppendOutput(): void { - $event = new Event(m::mock(EventMutex::class), 'php -v'); + $event = new Event(Double::for(EventMutex::class), 'php -v'); $event->appendOutputTo($output = 'test.log'); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('output') - ->once() - ->andReturn($result = 'PHP 8.3.17 (cli) (built: Feb 11 2025 22:03:03) (NTS)'); + $kernel = Double::for(KernelContract::class); + $kernel->expects('output') + ->returns($result = 'PHP 8.3.17 (cli) (built: Feb 11 2025 22:03:03) (NTS)'); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile') - ->once() + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('isFile') ->with($output) - ->andReturn(true); - $filesystem->shouldReceive('append') - ->once() + ->returns(true); + $filesystem->expects('append') ->with($output, $result) - ->andReturn(strlen($result)); + ->returns(strlen($result)); $this->container->instance(KernelContract::class, $kernel); $this->container->instance(Filesystem::class, $filesystem); @@ -441,15 +436,15 @@ public function testAppendOutput(): void public function testWriteOutputRejectsFailedWrites(): void { - $event = new Event(m::mock(EventMutex::class), 'php -v'); + $event = new Event(Double::for(EventMutex::class), 'php -v'); $event->sendOutputTo($output = 'test.log'); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('output')->once()->andReturn($result = 'output'); + $kernel = Double::for(KernelContract::class); + $kernel->expects('output')->returns($result = 'output'); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile')->once()->with($output)->andReturnTrue(); - $filesystem->shouldReceive('put')->once()->with($output, $result)->andReturnFalse(); + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('isFile')->with($output)->returns(true); + $filesystem->expects('put')->with($output, $result)->returns(false); $this->container->instance(KernelContract::class, $kernel); $this->container->instance(Filesystem::class, $filesystem); @@ -462,15 +457,15 @@ public function testWriteOutputRejectsFailedWrites(): void public function testWriteOutputRejectsPartialWrites(): void { - $event = new Event(m::mock(EventMutex::class), 'php -v'); + $event = new Event(Double::for(EventMutex::class), 'php -v'); $event->appendOutputTo($output = 'test.log'); - $kernel = m::mock(KernelContract::class); - $kernel->shouldReceive('output')->once()->andReturn($result = 'output'); + $kernel = Double::for(KernelContract::class); + $kernel->expects('output')->returns($result = 'output'); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile')->once()->with($output)->andReturnTrue(); - $filesystem->shouldReceive('append')->once()->with($output, $result)->andReturn(3); + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('isFile')->with($output)->returns(true); + $filesystem->expects('append')->with($output, $result)->returns(3); $this->container->instance(KernelContract::class, $kernel); $this->container->instance(Filesystem::class, $filesystem); @@ -483,13 +478,13 @@ public function testWriteOutputRejectsPartialWrites(): void public function testOutputCallbackSurfacesReadFailureAfterFileCheck(): void { - $event = new Event(m::mock(EventMutex::class), 'php -v'); + $event = new Event(Double::for(EventMutex::class), 'php -v'); $event->sendOutputTo($output = 'test.log'); $event->thenWithOutput(fn (Stringable $output) => $output); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile')->once()->with($output)->andReturnTrue(); - $filesystem->shouldReceive('get')->once()->with($output)->andThrow( + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('isFile')->with($output)->returns(true); + $filesystem->expects('get')->with($output)->throws( new FileNotFoundException("Unable to read file at path {$output}.") ); @@ -503,20 +498,19 @@ public function testOutputCallbackSurfacesReadFailureAfterFileCheck(): void public function testEmailOutputUsesTheMailContractCallback(): void { - $event = new Event(m::mock(EventMutex::class), 'php -v'); + $event = new Event(Double::for(EventMutex::class), 'php -v'); $event->sendOutputTo($output = 'test.log'); $event->description('Daily report'); $event->emailOutputTo($addresses = ['taylor@example.com']); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile')->once()->with($output)->andReturnTrue(); - $filesystem->shouldReceive('get')->once()->with($output)->andReturn('captured output'); + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('isFile')->with($output)->returns(true); + $filesystem->expects('get')->with($output)->returns('captured output'); - $mailer = m::mock(Mailer::class); - $mailer->shouldReceive('raw') - ->once() - ->with('captured output', m::type(Closure::class)) - ->andReturnUsing(function (string $text, Closure $callback) use ($addresses) { + $mailer = Double::for(Mailer::class); + $mailer->expects('raw') + ->with('captured output', Argument::type(Closure::class)) + ->resolves(function (string $text, Closure $callback) use ($addresses) { $message = new Message(new Email); $callback($message); @@ -539,10 +533,10 @@ public function testEmailOutputUsesTheMailContractCallback(): void public function testProcessIsRetainedThroughAfterCallbacksAndReleasedAfterSuccess(): void { $outputDuringCallback = null; - $process = m::mock(Process::class); - $process->shouldReceive('getOutput')->once()->andReturn('process output'); + $process = Double::for(Process::class); + $process->expects('getOutput')->returns('process output'); - $event = new EventTestProcessEvent(m::mock(EventMutex::class), $process); + $event = new EventTestProcessEvent(Double::for(EventMutex::class), $process); $event->after(function (Event $event) use (&$outputDuringCallback): void { $outputDuringCallback = $event->getOutput($this->container); }); @@ -556,8 +550,8 @@ public function testProcessIsRetainedThroughAfterCallbacksAndReleasedAfterSucces public function testProcessIsReleasedAfterExecutionFailure(): void { $event = new EventTestProcessEvent( - m::mock(EventMutex::class), - m::mock(Process::class), + Double::for(EventMutex::class), + Double::for(Process::class), new RuntimeException('execution failed') ); @@ -574,17 +568,17 @@ public function testProcessIsReleasedAfterExecutionFailure(): void public function testProcessIsReleasedAfterOutputFailure(): void { $afterCalled = false; - $process = m::mock(Process::class); - $process->shouldReceive('getOutput')->once()->andReturn('process output'); + $process = Double::for(Process::class); + $process->expects('getOutput')->returns('process output'); - $event = new EventTestProcessEvent(m::mock(EventMutex::class), $process); + $event = new EventTestProcessEvent(Double::for(EventMutex::class), $process); $event->sendOutputTo($output = 'test.log'); $event->after(function () use (&$afterCalled): void { $afterCalled = true; }); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('put')->once()->with($output, 'process output')->andReturnFalse(); + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('put')->with($output, 'process output')->returns(false); $this->container->instance(Filesystem::class, $filesystem); try { @@ -605,18 +599,18 @@ public function testOutputCancellationReleasesTheMutexAndProcessWithoutRunningAf $cancellation = new CanceledException('Output write canceled.'); $cleanup = $cleanupThrows ? new RuntimeException('Output cleanup failed.') : null; $afterCalled = false; - $process = m::mock(Process::class); - $process->shouldReceive('getOutput')->once()->andReturn('process output'); - $mutex = m::mock(EventMutex::class); - $mutex->shouldReceive('create')->once()->andReturnTrue(); - $mutex->shouldReceive('forget')->once(); + $process = Double::for(Process::class); + $process->expects('getOutput')->returns('process output'); + $mutex = Double::for(EventMutex::class); + $mutex->expects('create')->returns(true); + $mutex->expects('forget'); $event = new EventTestProcessEvent($mutex, $process); $event->withoutOverlapping()->sendOutputTo('test.log'); $event->after(static function () use (&$afterCalled): void { $afterCalled = true; }); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('put')->once()->with('test.log', 'process output')->andReturnUsing( + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('put')->with('test.log', 'process output')->resolves( static function () use ($cancellation, $cleanup): never { try { throw $cancellation; @@ -643,7 +637,7 @@ static function () use ($cancellation, $cleanup): never { public function testProcessIsReleasedAfterAfterCallbackFailure(): void { - $event = new EventTestProcessEvent(m::mock(EventMutex::class), m::mock(Process::class)); + $event = new EventTestProcessEvent(Double::for(EventMutex::class), Double::for(Process::class)); $event->after(fn () => throw new RuntimeException('after callback failed')); try { @@ -781,12 +775,12 @@ public function testSuccessFailureAndOutputCallbacksCanReceiveEvent(): void $failureEvent = null; $outputEvent = null; $outputValue = null; - $event = new Event(m::mock(EventMutex::class), 'php -i'); + $event = new Event(Double::for(EventMutex::class), 'php -i'); $event->sendOutputTo($output = 'test.log'); - $filesystem = m::mock(Filesystem::class); - $filesystem->shouldReceive('isFile')->twice()->with($output)->andReturnTrue(); - $filesystem->shouldReceive('get')->twice()->with($output)->andReturn('captured output'); + $filesystem = Double::for(Filesystem::class); + $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); $event->onSuccess(function (Event $scheduledEvent) use (&$successEvent): void { @@ -814,7 +808,7 @@ public function testSuccessFailureAndOutputCallbacksCanReceiveEvent(): void public function testTimezoneAcceptsStringBackedEnum(): void { - $event = new Event(m::mock(EventMutex::class), 'php -i'); + $event = new Event(Double::for(EventMutex::class), 'php -i'); $event->timezone(EventTestTimezoneStringEnum::NewYork); @@ -824,7 +818,7 @@ public function testTimezoneAcceptsStringBackedEnum(): void public function testTimezoneAcceptsUnitEnum(): void { - $event = new Event(m::mock(EventMutex::class), 'php -i'); + $event = new Event(Double::for(EventMutex::class), 'php -i'); $event->timezone(EventTestTimezoneUnitEnum::UTC); @@ -834,7 +828,7 @@ public function testTimezoneAcceptsUnitEnum(): void public function testTimezoneAcceptsIntBackedEnum(): void { - $event = new Event(m::mock(EventMutex::class), 'php -i'); + $event = new Event(Double::for(EventMutex::class), 'php -i'); $event->timezone(EventTestTimezoneIntEnum::Zone1); @@ -843,7 +837,7 @@ public function testTimezoneAcceptsIntBackedEnum(): void public function testTimezoneAcceptsDateTimeZoneObject(): void { - $event = new Event(m::mock(EventMutex::class), 'php -i'); + $event = new Event(Double::for(EventMutex::class), 'php -i'); $tz = new DateTimeZone('UTC'); $event->timezone($tz); @@ -854,10 +848,11 @@ public function testTimezoneAcceptsDateTimeZoneObject(): void public function testBasicCronCompilation(): void { - $app = m::mock(ApplicationContract::class); - $app->expects('isDownForMaintenance')->times(3)->andReturn(false); - $app->expects('environment')->times(3)->andReturn('production'); - $app->shouldReceive('call')->andReturnUsing(fn (callable $callback): bool => $callback()); + $appDouble = Double::for(ApplicationContract::class, override: true); + $app = $appDouble->instance(); + $appDouble->expects('isDownForMaintenance')->times(3)->returns(false); + $appDouble->expects('environment')->times(3)->returns('production'); + $appDouble->allows('call')->resolves(fn (callable $callback): bool => $callback()); $event = new Event(new FakeEventMutex, 'php foo'); $this->assertSame('* * * * *', $event->getExpression()); @@ -901,9 +896,10 @@ public function testBasicCronCompilation(): void public function testEventIsDueCheck(): void { - $app = m::mock(ApplicationContract::class); - $app->expects('isDownForMaintenance')->times(2)->andReturn(false); - $app->expects('environment')->times(2)->andReturn('production'); + $appDouble = Double::for(ApplicationContract::class, override: true); + $app = $appDouble->instance(); + $appDouble->expects('isDownForMaintenance')->times(2)->returns(false); + $appDouble->expects('environment')->times(2)->returns('production'); CarbonImmutable::setTestNow(CarbonImmutable::create(2015, 1, 1, 0, 0, 0)); $event = new Event(new FakeEventMutex, 'php foo'); @@ -917,13 +913,14 @@ public function testEventIsDueCheck(): void public function testEventIsDueAtUsesGivenTime(): void { - $app = m::mock(ApplicationContract::class); - $app->shouldReceive('isDownForMaintenance')->andReturn(false); - $app->shouldReceive('environment')->andReturn('production'); + $appDouble = Double::for(ApplicationContract::class, override: true); + $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(m::mock(EventMutex::class), 'php foo'); + $event = new Event(Double::for(EventMutex::class), 'php foo'); $event->dailyAt('13:00'); $this->assertFalse($event->isDueAt($app, CarbonImmutable::parse('2026-05-29 12:59:59'))); @@ -932,11 +929,12 @@ public function testEventIsDueAtUsesGivenTime(): void public function testEventIsDueAtUsesEventTimezone(): void { - $app = m::mock(ApplicationContract::class); - $app->shouldReceive('isDownForMaintenance')->andReturn(false); - $app->shouldReceive('environment')->andReturn('production'); + $appDouble = Double::for(ApplicationContract::class, override: true); + $app = $appDouble->instance(); + $appDouble->allows('isDownForMaintenance')->returns(false); + $appDouble->allows('environment')->returns('production'); - $event = new Event(m::mock(EventMutex::class), 'php foo'); + $event = new Event(Double::for(EventMutex::class), 'php foo'); $event->dailyAt('09:00')->timezone('America/New_York'); $this->assertTrue($event->isDueAt($app, CarbonImmutable::parse('2026-05-29 13:00:00', 'UTC'))); @@ -970,12 +968,13 @@ public function testTimeBetweenChecks(): void public function testTimeBetweenIsEvaluatedUsingTheCurrentTime(): void { - $app = m::mock(ApplicationContract::class); - $app->shouldReceive('call')->andReturnUsing(fn (callable $callback): bool => $callback()); + $appDouble = Double::for(ApplicationContract::class, override: true); + $app = $appDouble->instance(); + $appDouble->allows('call')->resolves(fn (callable $callback): bool => $callback()); CarbonImmutable::setTestNow('2026-05-29 09:00:00'); - $event = new Event(m::mock(EventMutex::class), 'php foo', 'UTC'); + $event = new Event(Double::for(EventMutex::class), 'php foo', 'UTC'); $event->between('8:00', '10:00'); $this->assertTrue($event->filtersPass($app)); diff --git a/tests/Console/Scheduling/ScheduleTest.php b/tests/Console/Scheduling/ScheduleTest.php index e900242d3..0c5be3c15 100644 --- a/tests/Console/Scheduling/ScheduleTest.php +++ b/tests/Console/Scheduling/ScheduleTest.php @@ -29,8 +29,10 @@ use Hypervel\Tests\Console\Fixtures\FakeEventMutex; use Hypervel\Tests\Queue\Fixtures\JobToTestWithSchedule; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -69,11 +71,13 @@ enum ScheduleTestCacheStoreIntEnum: int class ScheduleTest extends TestCase { + use VerifiesDoubles; + protected Container $container; protected EventMutex $eventMutex; - protected MockInterface&SchedulingMutex $schedulingMutex; + protected DoubleInterface&SchedulingMutex $schedulingMutex; protected function setUp(): void { @@ -83,7 +87,7 @@ protected function setUp(): void Container::setInstance($this->container); $this->eventMutex = new FakeEventMutex; $this->container->instance(EventMutex::class, $this->eventMutex); - $this->schedulingMutex = m::mock(SchedulingMutex::class); + $this->schedulingMutex = Double::for(SchedulingMutex::class); $this->container->instance(SchedulingMutex::class, $this->schedulingMutex); } @@ -122,10 +126,9 @@ public function testJobIsNotInstantiatedIfSuppliedAsClassname(): void public function testSynchronousJobResolvesToAFreshInstanceForEachFiring(): void { $dispatched = []; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatchNow') - ->twice() - ->andReturnUsing(function (ScheduleTestMutableJob $job) use (&$dispatched): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatchNow')->times(2) + ->resolves(function (ScheduleTestMutableJob $job) use (&$dispatched): void { self::assertFalse($job->handled); $dispatched[] = $job; @@ -157,10 +160,9 @@ public function testExplicitlySharedClassStringJobIsDispatchedAsTheRegisteredIns { $job = new ScheduleTestMutableJob; ScheduleTestMutableJob::$constructions = 0; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatchNow') - ->once() - ->andReturnUsing(static function (object $dispatched) use ($job): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatchNow') + ->resolves(static function (object $dispatched) use ($job): void { self::assertSame($job, $dispatched); }); @@ -174,10 +176,9 @@ public function testExplicitlySharedClassStringJobIsDispatchedAsTheRegisteredIns public function testSuppliedQueuedJobIsDispatchedAsProvided(): void { $job = new ScheduleTestQueuedJob; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch') - ->once() - ->andReturnUsing(static function (object $dispatched) use ($job): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch') + ->resolves(static function (object $dispatched) use ($job): void { self::assertSame($job, $dispatched); self::assertSame('connection-name', $dispatched->connection); self::assertSame('queue-name', $dispatched->queue); @@ -192,10 +193,9 @@ public function testSuppliedQueuedJobIsDispatchedAsProvided(): void public function testQueuedClassStringDoesNotRetainQueueStateAcrossEvents(): void { $dispatched = []; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch') - ->twice() - ->andReturnUsing(static function (object $job) use (&$dispatched): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->times(2) + ->resolves(static function (object $job) use (&$dispatched): void { $dispatched[] = $job; }); @@ -244,9 +244,10 @@ public function testItCanFilterEventsByEnvironments(): void public function testDueEventsAtUsesGivenTime(bool $alwaysOnOneServer): void { Schedule::alwaysOnOneServer($alwaysOnOneServer); - $app = m::mock(ApplicationContract::class); - $app->shouldReceive('isDownForMaintenance')->andReturn(false); - $app->shouldReceive('environment')->andReturn('production'); + $appDouble = Double::for(ApplicationContract::class, override: true); + $app = $appDouble->instance(); + $appDouble->allows('isDownForMaintenance')->returns(false); + $appDouble->allows('environment')->returns('production'); try { CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-05-29 13:00:00')); @@ -305,11 +306,11 @@ public function testJobAcceptsIntegerBackedEnumForQueueAndConnection(): void public function testUseCacheAcceptsStringBackedEnum(): void { - $eventMutex = m::mock(EventMutex::class, CacheAware::class); - $eventMutex->shouldReceive('useStore')->once()->with('redis'); + $eventMutex = Double::for(EventMutex::class, CacheAware::class); + $eventMutex->expects('useStore')->with('redis'); - $schedulingMutex = m::mock(SchedulingMutex::class, CacheAware::class); - $schedulingMutex->shouldReceive('useStore')->once()->with('redis'); + $schedulingMutex = Double::for(SchedulingMutex::class, CacheAware::class); + $schedulingMutex->expects('useStore')->with('redis'); $this->container->instance(EventMutex::class, $eventMutex); $this->container->instance(SchedulingMutex::class, $schedulingMutex); @@ -320,11 +321,11 @@ public function testUseCacheAcceptsStringBackedEnum(): void public function testUseCacheAcceptsIntegerBackedEnum(): void { - $eventMutex = m::mock(EventMutex::class, CacheAware::class); - $eventMutex->shouldReceive('useStore')->once()->with('1'); + $eventMutex = Double::for(EventMutex::class, CacheAware::class); + $eventMutex->expects('useStore')->with('1'); - $schedulingMutex = m::mock(SchedulingMutex::class, CacheAware::class); - $schedulingMutex->shouldReceive('useStore')->once()->with('1'); + $schedulingMutex = Double::for(SchedulingMutex::class, CacheAware::class); + $schedulingMutex->expects('useStore')->with('1'); $this->container->instance(EventMutex::class, $eventMutex); $this->container->instance(SchedulingMutex::class, $schedulingMutex); @@ -356,16 +357,14 @@ public function testServerShouldRunCachesMutexResultOnlyWithinSameMinute(): void $sameNextMinute = new DateTimeImmutable('2024-01-01 12:31:30'); $this->schedulingMutex - ->shouldReceive('create') - ->once() - ->with($event, $firstMinute) - ->andReturnTrue(); + ->expects('create') + ->with(Argument::same($event), Argument::same($firstMinute)) + ->returns(true); $this->schedulingMutex - ->shouldReceive('create') - ->once() - ->with($event, $nextMinute) - ->andReturnFalse(); + ->expects('create') + ->with(Argument::same($event), Argument::same($nextMinute)) + ->returns(false); $this->assertTrue($schedule->serverShouldRun($event, $firstMinute)); $this->assertTrue($schedule->serverShouldRun($event, $sameMinute)); diff --git a/tests/Container/ContextualAttributeBindingTest.php b/tests/Container/ContextualAttributeBindingTest.php index e6958dc33..15cafbb1e 100644 --- a/tests/Container/ContextualAttributeBindingTest.php +++ b/tests/Container/ContextualAttributeBindingTest.php @@ -42,7 +42,8 @@ use Hypervel\Log\Logger as HypervelLogger; use Hypervel\Log\LogManager; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use Psr\Log\LoggerInterface; use ReflectionParameter; @@ -54,6 +55,8 @@ class ContextualAttributeBindingTest extends TestCase { + use VerifiesDoubles; + public function testDependencyCanBeResolvedFromAttributeBinding(): void { $container = new Container; @@ -211,29 +214,29 @@ public function testAuthedAttribute(): void { $container = new Container; $container->singleton('auth', function (): AuthManager { - $manager = m::mock(AuthManager::class); - $manager->expects('userResolver')->times(4)->andReturn(fn (UnitEnum|string|null $guard = null): ?AuthenticatableContract => $manager->guard($guard)->user()); - $manager->expects('guard')->with('foo')->andReturnUsing(function (): GuardContract { - $guard = m::mock(GuardContract::class); - $guard->expects('user')->andReturn(m::mock(AuthenticatableContract::class)); + $manager = Double::for(AuthManager::class); + $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)); return $guard; }); - $manager->expects('guard')->with('bar')->andReturnUsing(function (): GuardContract { - $guard = m::mock(GuardContract::class); - $guard->expects('user')->andReturn(m::mock(AuthenticatableContract::class)); + $manager->expects('guard')->with('bar')->resolves(function (): GuardContract { + $guard = Double::for(GuardContract::class); + $guard->expects('user')->returns(Double::for(AuthenticatableContract::class)); return $guard; }); - $manager->expects('guard')->with(AuthGuardUnitEnum::unit)->andReturnUsing(function (): GuardContract { - $guard = m::mock(GuardContract::class); - $guard->expects('user')->andReturn(m::mock(AuthenticatableContract::class)); + $manager->expects('guard')->with(AuthGuardUnitEnum::unit)->resolves(function (): GuardContract { + $guard = Double::for(GuardContract::class); + $guard->expects('user')->returns(Double::for(AuthenticatableContract::class)); return $guard; }); - $manager->expects('guard')->with(AuthGuardBackedEnum::Backed)->andReturnUsing(function (): GuardContract { - $guard = m::mock(GuardContract::class); - $guard->expects('user')->andReturn(m::mock(AuthenticatableContract::class)); + $manager->expects('guard')->with(AuthGuardBackedEnum::Backed)->resolves(function (): GuardContract { + $guard = Double::for(GuardContract::class); + $guard->expects('user')->returns(Double::for(AuthenticatableContract::class)); return $guard; }); @@ -254,8 +257,8 @@ public function testAuthenticatedAttributesCanExtractPropertyPaths(): void 'profile' => ['id' => 20], ]); - $manager = m::mock(AuthManager::class); - $manager->shouldReceive('userResolver')->twice()->andReturn(fn (): GenericUser => $user); + $manager = Double::for(AuthManager::class); + $manager->expects('userResolver')->times(2)->returns(fn (): GenericUser => $user); $container->singleton('auth', fn (): AuthManager => $manager); $resolved = $container->make(AuthenticatedPropertyTest::class); @@ -268,8 +271,8 @@ public function testAuthenticatedAttributesCanExtractPropertyPaths(): void public function testAuthenticatedNullIsAuthoritativeForMakeAndCall(): void { $container = new Container; - $manager = m::mock(AuthManager::class); - $manager->shouldReceive('userResolver')->times(3)->andReturn(fn (): null => null); + $manager = Double::for(AuthManager::class); + $manager->expects('userResolver')->times(3)->returns(fn (): null => null); $container->singleton('auth', fn (): AuthManager => $manager); $withoutDefault = $container->make(NullableAuthenticatedWithoutDefault::class); @@ -287,14 +290,14 @@ public function testCacheAttribute(): void { $container = new Container; $container->singleton('cache', function (): CacheManager { - $manager = m::mock(CacheManager::class); - $manager->expects('store')->with('foo')->andReturn(m::mock(CacheRepository::class)); - $manager->expects('store')->with('bar')->andReturn(m::mock(CacheRepository::class)); - $manager->expects('store')->with(CacheStoreUnitEnum::unit)->andReturn(m::mock(CacheRepository::class)); - $manager->expects('store')->with(CacheStoreBackedEnum::Backed)->andReturn(m::mock(CacheRepository::class)); - $manager->expects('store')->with(CacheStoreIntegerBackedEnum::Zero)->andReturn(m::mock(CacheRepository::class)); - $manager->expects('memo')->with('foo')->andReturn(m::mock(CacheRepository::class)); - $manager->expects('memo')->with('bar')->andReturn(m::mock(CacheRepository::class)); + $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)); return $manager; }); @@ -320,10 +323,10 @@ public function testDatabaseAttribute(): void { $container = new Container; $container->singleton('db', function (): DatabaseManager { - $manager = m::mock(DatabaseManager::class); - $manager->expects('connection')->with('foo')->andReturn(new PdoConnection(new PDO('sqlite::memory:'))); - $manager->expects('connection')->with('bar')->andReturn(new PdoConnection(new PDO('sqlite::memory:'))); - $manager->expects('connection')->with(DatabaseConnectionIntegerBackedEnum::Zero)->andReturn(new PdoConnection(new PDO('sqlite::memory:'))); + $manager = Double::for(DatabaseManager::class); + $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:'))); return $manager; }); @@ -337,12 +340,12 @@ public function testAuthAttribute(): void { $container = new Container; $container->singleton('auth', function (): AuthManager { - $manager = m::mock(AuthManager::class); - $manager->expects('guard')->with('foo')->andReturn(m::mock(GuardContract::class)); - $manager->expects('guard')->with('bar')->andReturn(m::mock(GuardContract::class)); - $manager->expects('guard')->with(AuthGuardUnitEnum::unit)->andReturn(m::mock(GuardContract::class)); - $manager->expects('guard')->with(AuthGuardBackedEnum::Backed)->andReturn(m::mock(GuardContract::class)); - $manager->expects('guard')->with(AuthGuardIntegerBackedEnum::Zero)->andReturn(m::mock(GuardContract::class)); + $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)); return $manager; }); @@ -354,19 +357,19 @@ public function testLogAttribute(): void { $container = new Container; $container->singleton('log', function (): LogManager { - $manager = m::mock(LogManager::class); - $manager->expects('channel')->with('foo')->andReturn(m::mock(LoggerInterface::class)); - $manager->expects('channel')->with('bar')->andReturn(m::mock(LoggerInterface::class)); - $manager->expects('channel')->with('unit_channel')->andReturn(m::mock(LoggerInterface::class)); - $manager->expects('channel')->with('7')->andReturn(m::mock(LoggerInterface::class)); + $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 = m::mock(HypervelLogger::class); - $named->expects('withName')->with('tenant')->andReturn(m::mock(HypervelLogger::class)); - $manager->expects('channel')->with('named')->andReturn($named); + $named = Double::for(HypervelLogger::class); + $named->expects('withName')->with('tenant')->returns(Double::for(HypervelLogger::class)); + $manager->expects('channel')->with('named')->returns($named); - $integerNamed = m::mock(HypervelLogger::class); - $integerNamed->expects('withName')->with('9')->andReturn(m::mock(HypervelLogger::class)); - $manager->expects('channel')->with('integer-named')->andReturn($integerNamed); + $integerNamed = Double::for(HypervelLogger::class); + $integerNamed->expects('withName')->with('9')->returns(Double::for(HypervelLogger::class)); + $manager->expects('channel')->with('integer-named')->returns($integerNamed); return $manager; }); @@ -380,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 => m::mock(LoggerInterface::class)); + $manager->extend('custom', fn (): LoggerInterface => Double::for(LoggerInterface::class)); $container->instance('log', $manager); $this->expectException(RuntimeException::class); @@ -393,11 +396,11 @@ public function testRouteParameterAttribute(): void { $container = new Container; $container->singleton('request', function (): Request { - $request = m::mock(Request::class); - $request->expects('route')->with('foo')->andReturn(m::mock(Model::class)); - $request->expects('route')->with('bar')->andReturn('bar'); + $request = Double::for(Request::class, override: true); + $request->expects('route')->with('foo')->returns(Double::for(Model::class)); + $request->expects('route')->with('bar')->returns('bar'); - return $request; + return $request->instance(); }); $this->assertTrue($container->isScoped(RouteParameterTest::class)); @@ -409,11 +412,11 @@ public function testRouteParameterAttributeWithouthParameterName(): void { $container = new Container; $container->singleton('request', function (): Request { - $request = m::mock(Request::class); - $request->expects('route')->with('foo')->andReturn(m::mock(Model::class)); - $request->expects('route')->with('bar')->andReturn('bar'); + $request = Double::for(Request::class, override: true); + $request->expects('route')->with('foo')->returns(Double::for(Model::class)); + $request->expects('route')->with('bar')->returns('bar'); - return $request; + return $request->instance(); }); $container->make(RouteParameterTestWithoutParameterName::class); @@ -425,14 +428,14 @@ public function testRouteParameterCanExtractSupportedPropertyPaths(): void $model = new ContextualRouteModel; $model->setAttribute('id', 40); - $request = m::mock(Request::class); - $request->shouldReceive('route')->with('array')->andReturn(['nested' => ['id' => 10]]); - $request->shouldReceive('route')->with('array-access')->andReturn(new ArrayObject(['id' => 20])); - $request->shouldReceive('route')->with('object')->andReturn((object) ['nested' => (object) ['id' => 30]]); - $request->shouldReceive('route')->with('model')->andReturn($model); - $request->shouldReceive('route')->with('missing')->andReturn(['other' => 50]); - $request->shouldReceive('route')->with('null')->andReturnNull(); - $container->singleton('request', fn (): Request => $request); + $request = Double::for(Request::class, override: true); + $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]]); + $request->allows('route')->with('model')->returns($model); + $request->allows('route')->with('missing')->returns(['other' => 50]); + $request->allows('route')->with('null')->returns(null); + $container->singleton('request', fn (): Request => $request->instance()); $resolved = $container->make(RouteParameterPropertyTest::class); @@ -448,9 +451,9 @@ public function testRouteParameterCanExtractSupportedPropertyPaths(): void public function testRouteParameterPropertyRejectsScalarValues(): void { $container = new Container; - $request = m::mock(Request::class); - $request->shouldReceive('route')->with('post')->andReturn(123); - $container->singleton('request', fn (): Request => $request); + $request = Double::for(Request::class, override: true); + $request->allows('route')->with('post')->returns(123); + $container->singleton('request', fn (): Request => $request->instance()); $this->expectException(BindingResolutionException::class); $this->expectExceptionMessageIs('Cannot extract property path [id] from scalar [int] resolved by [Hypervel\Container\Attributes\RouteParameter].'); @@ -461,9 +464,9 @@ public function testRouteParameterPropertyRejectsScalarValues(): void public function testMissingRouteParameterDoesNotConstructAnEmptyModel(): void { $container = new Container; - $request = m::mock(Request::class); - $request->shouldReceive('route')->with('post')->andReturnNull(); - $container->singleton('request', fn (): Request => $request); + $request = Double::for(Request::class, override: true); + $request->allows('route')->with('post')->returns(null); + $container->singleton('request', fn (): Request => $request->instance()); $this->expectException(TypeError::class); @@ -539,12 +542,12 @@ public function testStorageAttribute(): void { $container = new Container; $container->singleton('filesystem', function (): FilesystemManager { - $manager = m::mock(FilesystemManager::class); - $manager->expects('disk')->with('foo')->andReturn(m::mock(Filesystem::class)); - $manager->expects('disk')->with('bar')->andReturn(m::mock(Filesystem::class)); - $manager->expects('disk')->with(StorageDiskUnitEnum::unit)->andReturn(m::mock(Filesystem::class)); - $manager->expects('disk')->with(StorageDiskBackedEnum::Backed)->andReturn(m::mock(Filesystem::class)); - $manager->expects('disk')->with(StorageDiskIntegerBackedEnum::Zero)->andReturn(m::mock(Filesystem::class)); + $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)); return $manager; }); diff --git a/tests/Database/DatabaseConcernsHasAttributesTest.php b/tests/Database/DatabaseConcernsHasAttributesTest.php index f4b2c2c93..58babc45a 100644 --- a/tests/Database/DatabaseConcernsHasAttributesTest.php +++ b/tests/Database/DatabaseConcernsHasAttributesTest.php @@ -11,7 +11,6 @@ use Hypervel\Database\Eloquent\Model; use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; class DatabaseConcernsHasAttributesTest extends TestCase @@ -32,20 +31,16 @@ public function testWithConstructorArguments(): void public function testRelationsToArray(): void { - $mock = m::mock(HasAttributesWithoutConstructor::class) - ->makePartial() - ->shouldAllowMockingProtectedMethods() - ->expects('getArrayableRelations')->andReturn([ - 'arrayable_relation' => new Collection(['foo' => 'bar']), - 'invalid_relation' => 'invalid', - 'null_relation' => null, - ]) - ->getMock(); + $model = new class extends Model { + }; + $model->setRelation('arrayable_relation', new Collection(['foo' => 'bar'])); + $model->setRelation('invalid_relation', 'invalid'); + $model->setRelation('null_relation', null); $this->assertEquals([ 'arrayable_relation' => ['foo' => 'bar'], 'null_relation' => null, - ], $mock->relationsToArray()); + ], $model->relationsToArray()); } public function testCastingEmptyStringToArrayDoesNotError(): void diff --git a/tests/Database/DatabaseConcernsPreventsCircularRecursionTest.php b/tests/Database/DatabaseConcernsPreventsCircularRecursionTest.php index 6b88313f5..74a107668 100644 --- a/tests/Database/DatabaseConcernsPreventsCircularRecursionTest.php +++ b/tests/Database/DatabaseConcernsPreventsCircularRecursionTest.php @@ -5,9 +5,7 @@ namespace Hypervel\Tests\Database\DatabaseConcernsPreventsCircularRecursionTest; use Hypervel\Database\Eloquent\Concerns\PreventsCircularRecursion; -use Hypervel\Database\Eloquent\Model; use Hypervel\Tests\TestCase; -use Mockery as m; class DatabaseConcernsPreventsCircularRecursionTest extends TestCase { @@ -180,16 +178,12 @@ public function testRecursiveCallsToCircularLinkedListCallsEachInstanceOnce(): v $this->assertEquals(3, $third->instanceStack); } - public function testMockedModelCallToWithoutRecursionMethodWorks(): void + public function testEvaluatedCodeRunsWithoutARecursionCacheEntry(): void { - $mock = m::mock(ModelStub::class)->makePartial(); + // Mocking libraries call this from generated code, which has no stable source location for a recursion key. + $callback = eval('return fn () => $this->withoutRecursion(fn () => 123);'); - // Model toArray method implementation - $toArray = $mock->withoutRecursion( - fn (): array => array_merge($mock->attributesToArray(), $mock->relationsToArray()), - fn (): array => $mock->attributesToArray(), - ); - $this->assertSame([], $toArray); + $this->assertSame(123, $callback->call(new RecursiveMethodStub)); } } @@ -285,7 +279,3 @@ function (): int { ); } } - -class ModelStub extends Model -{ -} diff --git a/tests/Database/DatabaseConnectionFactoryTest.php b/tests/Database/DatabaseConnectionFactoryTest.php index 2f4707fff..5e5c8202c 100755 --- a/tests/Database/DatabaseConnectionFactoryTest.php +++ b/tests/Database/DatabaseConnectionFactoryTest.php @@ -15,14 +15,18 @@ use Hypervel\Database\SQLiteConnection; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PDO; use ReflectionProperty; use stdClass; class DatabaseConnectionFactoryTest extends TestCase { + use VerifiesDoubles; + protected DB $db; /** @@ -318,12 +322,12 @@ public function testReadWriteConnectionSetsReadConnectionConfig(): void public function testReadEndpointMetadataMatchesTheSelectedPdoConfiguration(): void { $container = new Container; - $pdo = m::mock(PDO::class); - $connector = m::mock(ConnectorInterface::class); - $connector->expects('connect')->withArgs( + $pdo = Double::for(PDO::class); + $connector = Double::for(ConnectorInterface::class); + $connector->expects('connect')->with(Argument::satisfies( static fn (array $config): bool => $config['host'] === 'first-reader' && $config['options'][PDO::ATTR_EMULATE_PREPARES] === true - )->andReturn($pdo); + ))->returns($pdo); $container->instance('db.connector.pgsql', $connector); $factory = new AlternatingReadConnectionFactory($container); $connection = $factory->make([ @@ -357,19 +361,19 @@ public function testExceptionIsThrownOnUnsupportedDriver(): void { $this->expectExceptionObject(new InvalidArgumentException('Unsupported driver [foo]')); - $container = m::mock(Container::class); - $container->expects('bound')->andReturn(false); - $factory = new ConnectionFactory($container); + $container = Double::for(Container::class, override: true); + $container->expects('bound')->returns(false); + $factory = new ConnectionFactory($container->instance()); $factory->createConnector(['driver' => 'foo']); } public function testCustomConnectorsCanBeResolvedViaContainer(): void { - $connector = m::mock(ConnectorInterface::class); - $container = m::mock(Container::class); - $container->expects('bound')->with('db.connector.foo')->andReturn(true); - $container->expects('make')->with('db.connector.foo')->andReturn($connector); - $factory = new ConnectionFactory($container); + $connector = Double::for(ConnectorInterface::class); + $container = Double::for(Container::class, override: true); + $container->expects('bound')->with('db.connector.foo')->returns(true); + $container->expects('make')->with('db.connector.foo')->returns($connector); + $factory = new ConnectionFactory($container->instance()); $this->assertSame($connector, $factory->createConnector(['driver' => 'foo'])); } @@ -516,8 +520,8 @@ public function testExtensionCallbackReceivesConfigAndName(): void public function testConfigFirstExtensionCreatesNeutralConnectionWithoutResolvingAConnector(): void { - $container = m::mock(Container::class); - $factory = new ConnectionFactory($container); + $container = Double::for(Container::class, override: true); + $factory = new ConnectionFactory($container->instance()); $receivedConfig = null; $factory->extend('http', function (array $config, ?string $name) use (&$receivedConfig): FactoryNonPdoConnection { @@ -542,6 +546,7 @@ public function testConfigFirstExtensionCreatesNeutralConnectionWithoutResolving $this->assertSame('http', $receivedConfig['driver']); $this->assertSame('https://database.test', $receivedConfig['endpoint']); $this->assertSame('', $receivedConfig['prefix']); + $container->unused(); } public function testConfigFirstExtensionReceivesLiteralUrlCredentials(): void diff --git a/tests/Database/DatabaseConnectionTest.php b/tests/Database/DatabaseConnectionTest.php index 9267e5bb1..f190ab2d7 100755 --- a/tests/Database/DatabaseConnectionTest.php +++ b/tests/Database/DatabaseConnectionTest.php @@ -38,8 +38,10 @@ use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Testbench\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PDO; use PDOException; use PDOStatement; @@ -52,6 +54,8 @@ class DatabaseConnectionTest extends TestCase { + use VerifiesDoubles; + public function testDriverNameFallsBackToTheConnectionIdentity(): void { $pdo = new PDOStub; @@ -106,9 +110,9 @@ public function testConfiglessQueryFailureRetainsTheOriginalDatabaseException(): public function testConfiglessDatabaseEventsRetainTheNullableConnectionName(): void { $queryConnection = new PdoConnection(new PDO('sqlite::memory:')); - $queryConnection->setEventDispatcher($queryEvents = m::mock(Dispatcher::class)); - $queryEvents->expects('hasListeners')->with(QueryExecuted::class)->andReturn(true); - $queryEvents->expects('dispatch')->with(m::on( + $queryConnection->setEventDispatcher($queryEvents = Double::for(Dispatcher::class)); + $queryEvents->expects('hasListeners')->with(QueryExecuted::class)->returns(true); + $queryEvents->expects('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof QueryExecuted && $event->connectionName === null )); @@ -116,9 +120,9 @@ public function testConfiglessDatabaseEventsRetainTheNullableConnectionName(): v $queryConnection->logQuery('select 1', [], 0.0); $transactionConnection = new PdoConnection(new PDO('sqlite::memory:')); - $transactionConnection->setEventDispatcher($transactionEvents = m::mock(Dispatcher::class)); - $transactionEvents->expects('hasListeners')->with(TransactionBeginning::class)->andReturn(true); - $transactionEvents->expects('dispatch')->with(m::on( + $transactionConnection->setEventDispatcher($transactionEvents = Double::for(Dispatcher::class)); + $transactionEvents->expects('hasListeners')->with(TransactionBeginning::class)->returns(true); + $transactionEvents->expects('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof TransactionBeginning && $event->connectionName === null )); @@ -683,10 +687,10 @@ public function testBeganTransactionSkipsDispatchWhenNoListenersAreRegistered(): { $pdo = $this->createStub(PDOStub::class); $connection = $this->getMockConnection([], $pdo); - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class); $connection->setEventDispatcher($events); - $events->expects('hasListeners')->with(TransactionBeginning::class)->andReturn(false); - $events->shouldNotReceive('dispatch'); + $events->expects('hasListeners')->with(TransactionBeginning::class)->returns(false); + $events->expects('dispatch')->never(); $connection->beginTransaction(); } @@ -839,9 +843,9 @@ public function testRunMethodPreservesQueryCancellationWithoutRetryOrLogging(Thr $pdo = $this->createStub(PDOStub::class); $connection = $this->getMockConnection(['tryAgainIfCausedByLostConnection'], $pdo); $connection->expects($this->never())->method('tryAgainIfCausedByLostConnection'); - $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); - $events->shouldNotReceive('hasListeners')->with(QueryFailed::class); - $events->shouldNotReceive('dispatch')->with(m::type(QueryFailed::class)); + $connection->setEventDispatcher($events = Double::for(Dispatcher::class)); + $events->expects('hasListeners')->never()->with(QueryFailed::class); + $events->expects('dispatch')->never()->with(Argument::type(QueryFailed::class)); try { $method->invokeArgs($connection, ['select 1', [], fn () => throw $cancellation]); @@ -875,16 +879,16 @@ public function testRunDispatchesQueryFailedWithTheFinalLogicalFailure(): void Connection::READ_WRITE_TYPE_CONFIG_KEY => 'read', ], ); - $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); + $connection->setEventDispatcher($events = Double::for(Dispatcher::class)); $event = null; - $events->expects('hasListeners')->with(QueryFailed::class)->andReturnTrue(); - $events->expects('dispatch')->withArgs( + $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; }, - ); + )); $exception = null; try { @@ -916,16 +920,16 @@ public function testRunDispatchesTheReconnectorThrowableAsTheFinalFailure(): voi $connection->setReconnector(static function (Connection $connection) use ($reconnectorException): never { throw $reconnectorException; }); - $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); + $connection->setEventDispatcher($events = Double::for(Dispatcher::class)); $event = null; - $events->expects('hasListeners')->with(QueryFailed::class)->andReturnTrue(); - $events->expects('dispatch')->withArgs( + $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; }, - ); + )); $exception = null; try { @@ -947,16 +951,16 @@ public function testRunDispatchesLostConnectionExceptionWhenNoReconnectorExists( { $method = (new ReflectionClass(Connection::class))->getMethod('run'); $connection = $this->getMockConnection(); - $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); + $connection->setEventDispatcher($events = Double::for(Dispatcher::class)); $event = null; - $events->expects('hasListeners')->with(QueryFailed::class)->andReturnTrue(); - $events->expects('dispatch')->withArgs( + $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; }, - ); + )); $exception = null; try { @@ -983,16 +987,16 @@ public function testRunReportsAMissingConnectionDriverFailureAsTheQueryFailure() $connection->setReconnector(static function () use ($driverFailure): never { throw $driverFailure; }); - $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); + $connection->setEventDispatcher($events = Double::for(Dispatcher::class)); $event = null; - $events->expects('hasListeners')->with(QueryFailed::class)->andReturnTrue(); - $events->expects('dispatch')->withArgs( + $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; }, - ); + )); $exception = null; try { @@ -1022,16 +1026,16 @@ public function testRunReportsAFailedLostConnectionReconnectAsTheQueryFailure(): $connection->setReconnector(static function () use ($driverFailure): never { throw $driverFailure; }); - $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); + $connection->setEventDispatcher($events = Double::for(Dispatcher::class)); $event = null; - $events->expects('hasListeners')->with(QueryFailed::class)->andReturnTrue(); - $events->expects('dispatch')->withArgs( + $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; }, - ); + )); $exception = null; try { @@ -1085,9 +1089,9 @@ public function testRunPreservesCancellationDuringAQueryReconnect(Throwable $can $connection->setReconnector(static function () use ($cancellation): never { throw $cancellation; }); - $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); - $events->shouldNotReceive('hasListeners')->with(QueryFailed::class); - $events->shouldNotReceive('dispatch')->with(m::type(QueryFailed::class)); + $connection->setEventDispatcher($events = Double::for(Dispatcher::class)); + $events->expects('hasListeners')->never()->with(QueryFailed::class); + $events->expects('dispatch')->never()->with(Argument::type(QueryFailed::class)); try { $method->invokeArgs($connection, [ @@ -1141,10 +1145,10 @@ public function testRunEmitsOnlyQueryExecutedWhenLostConnectionRetrySucceeds(): $connection = $this->getMockConnection(); $connection->setReconnector(static function (Connection $connection): void { }); - $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); - $events->expects('hasListeners')->with(QueryExecuted::class)->andReturnTrue(); - $events->expects('dispatch')->with(m::type(QueryExecuted::class)); - $events->shouldNotReceive('dispatch')->with(m::type(QueryFailed::class)); + $connection->setEventDispatcher($events = Double::for(Dispatcher::class)); + $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)); $attempts = 0; $result = $method->invokeArgs($connection, [ @@ -1167,9 +1171,9 @@ public function testRunSkipsQueryFailedDispatchWhenNoListenersAreRegistered(): v { $method = (new ReflectionClass(Connection::class))->getMethod('run'); $connection = $this->getMockConnection(); - $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); - $events->expects('hasListeners')->with(QueryFailed::class)->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $connection->setEventDispatcher($events = Double::for(Dispatcher::class)); + $events->expects('hasListeners')->with(QueryFailed::class)->returns(false); + $events->expects('dispatch')->never(); $this->expectException(QueryException::class); @@ -1190,9 +1194,9 @@ public function testStreamingRunsLazilyAndLogsOnlyAfterExhaustion(): void $query = 'select ? as modified'; $bindings = [2]; }); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(QueryExecuted::class)->andReturnTrue(); - $events->expects('dispatch')->andReturnUsing( + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(QueryExecuted::class)->returns(true); + $events->expects('dispatch')->resolves( static function (QueryExecuted $dispatched) use (&$event): void { $event = $dispatched; }, @@ -1275,9 +1279,9 @@ public function testStreamingReportsAMissingConnectionDriverFailureAsTheQueryFai throw $driverFailure; }); $event = null; - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(QueryFailed::class)->andReturnTrue(); - $events->expects('dispatch')->andReturnUsing( + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(QueryFailed::class)->returns(true); + $events->expects('dispatch')->resolves( static function (QueryFailed $dispatched) use (&$event): void { $event = $dispatched; }, @@ -1332,9 +1336,9 @@ public function testStreamingRetriesALostConnectionBeforeTheFirstValue(): void $connection->setReconnector(static function () use (&$reconnects): void { ++$reconnects; }); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(QueryExecuted::class)->andReturnTrue(); - $events->expects('dispatch')->with(m::type(QueryExecuted::class)); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(QueryExecuted::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(QueryExecuted::class)); $connection->setEventDispatcher($events); $stream = $this->runStreamingQuery($connection, static function () use ($connection, &$attempts): Generator { @@ -1365,9 +1369,9 @@ public function testStreamingReportsOneFinalFailureWhenTheRetryAlsoFails(): void ++$reconnects; }); $event = null; - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(QueryFailed::class)->andReturnTrue(); - $events->expects('dispatch')->andReturnUsing( + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(QueryFailed::class)->returns(true); + $events->expects('dispatch')->resolves( static function (QueryFailed $dispatched) use (&$event): void { $event = $dispatched; }, @@ -1402,9 +1406,9 @@ public function testStreamingLateFailureRetainsItsRoleAndNeverRetries(): void $connection->setReconnector(static fn (): never => throw new LogicException('Unexpected retry.')); $failure = new RuntimeException('server has gone away'); $event = null; - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(QueryFailed::class)->andReturnTrue(); - $events->expects('dispatch')->andReturnUsing( + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(QueryFailed::class)->returns(true); + $events->expects('dispatch')->resolves( static function (QueryFailed $dispatched) use (&$event): void { $event = $dispatched; }, @@ -1444,9 +1448,9 @@ public function testAbandonedStreamingCleansUpWithoutSuccess(): void { $connection = new NeutralConnectionForTest; $connection->enableQueryLog(); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('hasListeners'); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $connection->setEventDispatcher($events); $cleaned = false; @@ -1472,9 +1476,9 @@ public function testStreamingConsumerExceptionsCleanUpWithoutQueryEvents(): void { $connection = new NeutralConnectionForTest; $connection->enableQueryLog(); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('hasListeners'); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $connection->setEventDispatcher($events); $failure = new RuntimeException('consumer failed'); $cleaned = false; @@ -1505,9 +1509,9 @@ public function testStreamingCancellationCleansUpWithoutWrappingOrEvents(Throwab { $connection = new NeutralConnectionForTest; $connection->enableQueryLog(); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('hasListeners'); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $connection->setEventDispatcher($events); $cleaned = false; $thrown = null; @@ -1538,9 +1542,9 @@ public function testClosedStreamingCleansUpWithoutWrappingOrEvents(bool $yieldFi $connection = new NeutralConnectionForTest; $connection->enableQueryLog(); $connection->setReconnector(static fn (): never => throw new LogicException('Unexpected retry.')); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('hasListeners'); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $connection->setEventDispatcher($events); $closed = new StreamClosedException('The stream is closed.'); $cleaned = false; @@ -1709,9 +1713,9 @@ protected function newQueryException(string $query, array $bindings, Exception $ }; $connection->enableQueryLog(); $failure = new InvalidArgumentException('Invalid query parameters.'); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->twice()->with(QueryFailed::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->twice()->with(m::on( + $events = Double::for(Dispatcher::class); + $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, )); $connection->setEventDispatcher($events); @@ -1776,8 +1780,8 @@ public function testRunMethodNeverRetriesIfWithinTransaction(): void public function testTableNormalizesIntegerBackedEnumName(): void { $connection = $this->getMockConnection(); - $connection->setQueryGrammar(m::mock(Grammar::class)); - $connection->setPostProcessor(m::mock(Processor::class)); + $connection->setQueryGrammar(Double::for(Grammar::class)); + $connection->setPostProcessor(Double::for(Processor::class)); $builder = $connection->table(DatabaseTableName::Zero); @@ -1786,12 +1790,12 @@ public function testTableNormalizesIntegerBackedEnumName(): void public function testPrepareBindings(): void { - $date = m::mock(DateTime::class); - $date->expects('format')->with('foo')->andReturn('bar'); + $date = Double::for(DateTime::class); + $date->expects('format')->with('foo')->returns('bar'); $bindings = ['test' => $date]; $conn = $this->getMockConnection(); - $grammar = m::mock(Grammar::class); - $grammar->expects('getDateFormat')->andReturn('foo'); + $grammar = Double::for(Grammar::class); + $grammar->expects('getDateFormat')->returns('foo'); $conn->setQueryGrammar($grammar); $result = $conn->prepareBindings($bindings); $this->assertEquals(['test' => 'bar'], $result); @@ -1810,10 +1814,10 @@ public function testLogQueryFiresEventsIfSet(): void public function testLogQuerySkipsDispatchWhenNoListenersAreRegistered(): void { $connection = $this->getMockConnection(); - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class); $connection->setEventDispatcher($events); - $events->expects('hasListeners')->with(QueryExecuted::class)->andReturn(false); - $events->shouldNotReceive('dispatch'); + $events->expects('hasListeners')->with(QueryExecuted::class)->returns(false); + $events->expects('dispatch')->never(); $connection->logQuery('foo', [], null); } @@ -1844,9 +1848,9 @@ public function testBeginPublicationFailureRollsBackAndPreservesTheOriginalFailu $connection = $this->getSqliteTransactionConnection(); $publicationFailure = new RuntimeException('manager begin failure'); $cleanupFailure = new RuntimeException('manager rollback failure'); - $manager = m::mock(DatabaseTransactionsManager::class); - $manager->expects('begin')->with('default', 1)->andThrow($publicationFailure); - $manager->expects('rollback')->with('default', 0)->andThrow($cleanupFailure); + $manager = Double::for(DatabaseTransactionsManager::class); + $manager->expects('begin')->with('default', 1)->throws($publicationFailure); + $manager->expects('rollback')->with('default', 0)->throws($cleanupFailure); $connection->setTransactionManager($manager); try { @@ -1865,9 +1869,9 @@ public function testBeginPublicationCleanupPreservesCancellation(Throwable $canc { $connection = $this->getSqliteTransactionConnection(); $publicationFailure = new RuntimeException('manager begin failure'); - $manager = m::mock(DatabaseTransactionsManager::class); - $manager->expects('begin')->with('default', 1)->andThrow($publicationFailure); - $manager->expects('rollback')->with('default', 0)->andThrow($cancellation); + $manager = Double::for(DatabaseTransactionsManager::class); + $manager->expects('begin')->with('default', 1)->throws($publicationFailure); + $manager->expects('rollback')->with('default', 0)->throws($cancellation); $connection->setTransactionManager($manager); try { @@ -1886,9 +1890,9 @@ public function testBeginPublicationCancellationRemainsPrimaryOverCleanupCancell { $connection = $this->getSqliteTransactionConnection(); $cleanupCancellation = new CanceledException('manager rollback canceled'); - $manager = m::mock(DatabaseTransactionsManager::class); - $manager->expects('begin')->with('default', 1)->andThrow($cancellation); - $manager->expects('rollback')->with('default', 0)->andThrow($cleanupCancellation); + $manager = Double::for(DatabaseTransactionsManager::class); + $manager->expects('begin')->with('default', 1)->throws($cancellation); + $manager->expects('rollback')->with('default', 0)->throws($cleanupCancellation); $connection->setTransactionManager($manager); try { @@ -1908,10 +1912,10 @@ public function testBeganEventFailureRollsBackPublishedTransactionState(): void $manager = new DatabaseTransactionsManager; $connection->setTransactionManager($manager); $failure = new RuntimeException('began listener failure'); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionBeginning::class)->andReturn(true); - $events->expects('dispatch')->with(m::type(TransactionBeginning::class))->andThrow($failure); - $events->expects('hasListeners')->with(TransactionRolledBack::class)->andReturn(false); + $events = Double::for(Dispatcher::class); + $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); $connection->setEventDispatcher($events); try { @@ -1932,11 +1936,11 @@ public function testCommittingEventFailureRollsBackManagedTransaction(): void $manager = new DatabaseTransactionsManager; $connection->setTransactionManager($manager); $failure = new RuntimeException('committing listener failure'); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionBeginning::class)->andReturn(false); - $events->expects('hasListeners')->with(TransactionCommitting::class)->andReturn(true); - $events->expects('dispatch')->with(m::type(TransactionCommitting::class))->andThrow($failure); - $events->expects('hasListeners')->with(TransactionRolledBack::class)->andReturn(false); + $events = Double::for(Dispatcher::class); + $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); + $events->expects('hasListeners')->with(TransactionRolledBack::class)->returns(false); $connection->setEventDispatcher($events); try { @@ -2031,9 +2035,9 @@ public function testManagedTransactionRollbackCleanupPreservesCancellation(Throw { $connection = $this->getSqliteTransactionConnection(); $failure = new RuntimeException('transaction callback failure'); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('rollback')->with('default', 0)->andThrow($cancellation); + $manager->expects('rollback')->with('default', 0)->throws($cancellation); $connection->setTransactionManager($manager); try { @@ -2052,9 +2056,9 @@ public function testManagedTransactionCancellationRemainsPrimaryOverRollbackCanc { $connection = $this->getSqliteTransactionConnection(); $cleanupCancellation = new CanceledException('rollback cleanup canceled'); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('rollback')->with('default', 0)->andThrow($cleanupCancellation); + $manager->expects('rollback')->with('default', 0)->throws($cleanupCancellation); $connection->setTransactionManager($manager); try { @@ -2148,9 +2152,9 @@ public function testNestedDeadlockRollbackCleanupPreservesCancellation(Throwable '', ['name' => 'analytics', 'driver' => 'http'] ); - $manager = m::mock(DatabaseTransactionsManager::class); - $manager->shouldReceive('begin')->twice(); - $manager->expects('rollback')->with('analytics', 1)->andThrow($cancellation); + $manager = Double::for(DatabaseTransactionsManager::class); + $manager->expects('begin')->times(2); + $manager->expects('rollback')->with('analytics', 1)->throws($cancellation); $connection->setTransactionManager($manager); $connection->beginTransaction(); $failure = new QueryException( @@ -2179,9 +2183,9 @@ public function testExplicitCommittingEventFailureLeavesTheTransactionCallerOwne $connection = $this->getSqliteTransactionConnection(); $connection->beginTransaction(); $failure = new RuntimeException('committing listener failure'); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionCommitting::class)->andReturn(true); - $events->expects('dispatch')->with(m::type(TransactionCommitting::class))->andThrow($failure); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(TransactionCommitting::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(TransactionCommitting::class))->throws($failure); $connection->setEventDispatcher($events); try { @@ -2202,19 +2206,19 @@ public function testManagerCommitFailureStillDispatchesCommittedEventAfterPhysic { $connection = $this->getSqliteTransactionConnection(); $failure = new RuntimeException('after commit callback failure'); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('commit')->with('default', 1, 0)->andThrow($failure); + $manager->expects('commit')->with('default', 1, 0)->throws($failure); $connection->setTransactionManager($manager); $connection->beginTransaction(); $eventDispatched = false; - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionCommitting::class)->andReturn(false); - $events->expects('hasListeners')->with(TransactionCommitted::class)->andReturn(true); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(TransactionCommitting::class)->returns(false); + $events->expects('hasListeners')->with(TransactionCommitted::class)->returns(true); $events->expects('dispatch') - ->with(m::type(TransactionCommitted::class)) - ->andReturnUsing(function () use (&$eventDispatched): void { + ->with(Argument::type(TransactionCommitted::class)) + ->resolves(function () use (&$eventDispatched): void { $eventDispatched = true; }); $connection->setEventDispatcher($events); @@ -2235,14 +2239,14 @@ public function testManagerCommitFailureStillDispatchesCommittedEventAfterPhysic public function testManagedTransactionManagerCancellationSkipsCommittedEvent(Throwable $cancellation): void { $connection = $this->getSqliteTransactionConnection(); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('commit')->with('default', 1, 0)->andThrow($cancellation); + $manager->expects('commit')->with('default', 1, 0)->throws($cancellation); $connection->setTransactionManager($manager); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionBeginning::class)->andReturn(false); - $events->expects('hasListeners')->with(TransactionCommitting::class)->andReturn(false); - $events->shouldNotReceive('hasListeners')->with(TransactionCommitted::class); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(TransactionBeginning::class)->returns(false); + $events->expects('hasListeners')->with(TransactionCommitting::class)->returns(false); + $events->expects('hasListeners')->never()->with(TransactionCommitted::class); $connection->setEventDispatcher($events); try { @@ -2261,15 +2265,15 @@ public function testManagedTransactionEventCancellationSupersedesManagerFailure( { $connection = $this->getSqliteTransactionConnection(); $managerFailure = new RuntimeException('manager commit failure'); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('commit')->with('default', 1, 0)->andThrow($managerFailure); + $manager->expects('commit')->with('default', 1, 0)->throws($managerFailure); $connection->setTransactionManager($manager); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionBeginning::class)->andReturn(false); - $events->expects('hasListeners')->with(TransactionCommitting::class)->andReturn(false); - $events->expects('hasListeners')->with(TransactionCommitted::class)->andReturn(true); - $events->expects('dispatch')->with(m::type(TransactionCommitted::class))->andThrow($cancellation); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(TransactionBeginning::class)->returns(false); + $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); $connection->setEventDispatcher($events); try { @@ -2287,14 +2291,14 @@ public function testManagedTransactionEventCancellationSupersedesManagerFailure( public function testExplicitCommitManagerCancellationSkipsCommittedEvent(Throwable $cancellation): void { $connection = $this->getSqliteTransactionConnection(); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('commit')->with('default', 1, 0)->andThrow($cancellation); + $manager->expects('commit')->with('default', 1, 0)->throws($cancellation); $connection->setTransactionManager($manager); $connection->beginTransaction(); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionCommitting::class)->andReturn(false); - $events->shouldNotReceive('hasListeners')->with(TransactionCommitted::class); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(TransactionCommitting::class)->returns(false); + $events->expects('hasListeners')->never()->with(TransactionCommitted::class); $connection->setEventDispatcher($events); try { @@ -2313,15 +2317,15 @@ public function testExplicitCommitEventCancellationSupersedesManagerFailure(Thro { $connection = $this->getSqliteTransactionConnection(); $managerFailure = new RuntimeException('manager commit failure'); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('commit')->with('default', 1, 0)->andThrow($managerFailure); + $manager->expects('commit')->with('default', 1, 0)->throws($managerFailure); $connection->setTransactionManager($manager); $connection->beginTransaction(); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionCommitting::class)->andReturn(false); - $events->expects('hasListeners')->with(TransactionCommitted::class)->andReturn(true); - $events->expects('dispatch')->with(m::type(TransactionCommitted::class))->andThrow($cancellation); + $events = Double::for(Dispatcher::class); + $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); $connection->setEventDispatcher($events); try { @@ -2382,9 +2386,9 @@ public function testLostConnectionCommitCleanupPreservesCancellation(Throwable $ new PDOException('server has gone away') ); $connection = $this->getMockConnection([], $pdo); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('test', 1); - $manager->expects('rollback')->with('test', 0)->andThrow($cancellation); + $manager->expects('rollback')->with('test', 0)->throws($cancellation); $connection->setTransactionManager($manager); try { @@ -2411,9 +2415,9 @@ public function testCommitRollbackCleanupPreservesCancellationWithoutRetry(Throw $pdo->expects($this->once())->method('inTransaction')->willReturn(true); $pdo->expects($this->once())->method('rollBack'); $connection = $this->getMockConnection([], $pdo); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('test', 1); - $manager->expects('rollback')->with('test', 0)->andThrow($cancellation); + $manager->expects('rollback')->with('test', 0)->throws($cancellation); $connection->setTransactionManager($manager); $callbackCalls = 0; @@ -2442,9 +2446,9 @@ public function testCommitCancellationRemainsPrimaryOverRollbackCancellation(): $pdo->expects($this->once())->method('inTransaction')->willReturn(true); $pdo->expects($this->once())->method('rollBack'); $connection = $this->getMockConnection([], $pdo); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('test', 1); - $manager->expects('rollback')->with('test', 0)->andThrow($cleanupCancellation); + $manager->expects('rollback')->with('test', 0)->throws($cleanupCancellation); $connection->setTransactionManager($manager); try { @@ -2461,18 +2465,18 @@ public function testManagerRollbackFailureStillDispatchesRolledBackEvent(): void { $connection = $this->getSqliteTransactionConnection(); $failure = new RuntimeException('manager rollback failure'); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('rollback')->with('default', 0)->andThrow($failure); + $manager->expects('rollback')->with('default', 0)->throws($failure); $connection->setTransactionManager($manager); $connection->beginTransaction(); $eventDispatched = false; - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionRolledBack::class)->andReturn(true); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(TransactionRolledBack::class)->returns(true); $events->expects('dispatch') - ->with(m::type(TransactionRolledBack::class)) - ->andReturnUsing(function () use (&$eventDispatched): void { + ->with(Argument::type(TransactionRolledBack::class)) + ->resolves(function () use (&$eventDispatched): void { $eventDispatched = true; }); $connection->setEventDispatcher($events); @@ -2493,13 +2497,13 @@ public function testManagerRollbackFailureStillDispatchesRolledBackEvent(): void public function testExplicitRollbackManagerCancellationSkipsRolledBackEvent(Throwable $cancellation): void { $connection = $this->getSqliteTransactionConnection(); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('rollback')->with('default', 0)->andThrow($cancellation); + $manager->expects('rollback')->with('default', 0)->throws($cancellation); $connection->setTransactionManager($manager); $connection->beginTransaction(); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('hasListeners')->with(TransactionRolledBack::class); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->never()->with(TransactionRolledBack::class); $connection->setEventDispatcher($events); try { @@ -2518,14 +2522,14 @@ public function testExplicitRollbackEventCancellationSupersedesManagerFailure(Th { $connection = $this->getSqliteTransactionConnection(); $managerFailure = new RuntimeException('manager rollback failure'); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('default', 1); - $manager->expects('rollback')->with('default', 0)->andThrow($managerFailure); + $manager->expects('rollback')->with('default', 0)->throws($managerFailure); $connection->setTransactionManager($manager); $connection->beginTransaction(); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionRolledBack::class)->andReturn(true); - $events->expects('dispatch')->with(m::type(TransactionRolledBack::class))->andThrow($cancellation); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(TransactionRolledBack::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(TransactionRolledBack::class))->throws($cancellation); $connection->setEventDispatcher($events); try { @@ -2546,9 +2550,9 @@ public function testRolledBackEventFailureOccursAfterManagerCleanup(): void $connection->setTransactionManager($manager); $connection->beginTransaction(); $failure = new RuntimeException('rolled back listener failure'); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(TransactionRolledBack::class)->andReturn(true); - $events->expects('dispatch')->with(m::type(TransactionRolledBack::class))->andThrow($failure); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(TransactionRolledBack::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(TransactionRolledBack::class))->throws($failure); $connection->setEventDispatcher($events); try { @@ -2575,9 +2579,9 @@ public function testLostConnectionRollbackCleanupPreservesCancellation(Throwable new PDOException('server has gone away') ); $connection = $this->getMockConnection([], $pdo); - $manager = m::mock(DatabaseTransactionsManager::class); + $manager = Double::for(DatabaseTransactionsManager::class); $manager->expects('begin')->with('test', 1); - $manager->expects('rollback')->with('test', 0)->andThrow($cancellation); + $manager->expects('rollback')->with('test', 0)->throws($cancellation); $connection->setTransactionManager($manager); $connection->beginTransaction(); @@ -2595,8 +2599,8 @@ public function testLostConnectionRollbackCleanupPreservesCancellation(Throwable public function testPretendOnlyLogsQueries(): void { $connection = $this->getMockConnection(); - $grammar = m::mock(Grammar::class); - $grammar->shouldReceive('substituteBindingsIntoRawSql')->andReturnUsing(fn ($query) => $query); + $grammar = Double::for(Grammar::class); + $grammar->allows('substituteBindingsIntoRawSql')->resolves(fn ($query) => $query); $connection->setQueryGrammar($grammar); $queries = $connection->pretend(function ($connection) { $connection->select('foo bar', ['baz']); @@ -2692,9 +2696,9 @@ public function testOlapSetsWorkloadOnReadAndWriteConnections(): void public function testOlapLeavesOtherMySqlServersUnchanged(): void { - $pdo = m::mock(PDO::class); - $pdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->andReturn('8.0.34'); - $pdo->shouldNotReceive('exec'); + $pdo = Double::for(PDO::class); + $pdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.34'); + $pdo->expects('exec')->never(); $connection = new MySqlConnection($pdo); $this->assertSame($connection, $connection->olap(static fn ($connection) => $connection)); @@ -2702,8 +2706,8 @@ public function testOlapLeavesOtherMySqlServersUnchanged(): void public function testNestedOlapScopesRestoreTheWorkloadOnlyAfterTheOuterCallback(): void { - $pdo = m::mock(PDO::class); - $pdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->andReturn('8.0.34-vitess'); + $pdo = Double::for(PDO::class); + $pdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.34-vitess'); $connection = new MySqlConnection($pdo); $queries = $connection->pretend(function () use ($connection): void { @@ -2723,18 +2727,18 @@ public function testNestedOlapScopesRestoreTheWorkloadOnlyAfterTheOuterCallback( public function testOlapReappliesTheWorkloadBeforeRetryingALostConnection(): void { - $original = m::mock(PDO::class); - $original->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->andReturn('8.0.34-vitess'); - $original->expects('exec')->with("set workload = 'olap'"); - $original->expects('prepare')->with('select total')->andThrow(new PDOException('server has gone away')); - $replacement = m::mock(PDO::class); - $replacement->expects('exec')->with("set workload = 'olap'")->ordered(); - $statement = m::mock(PDOStatement::class); - $statement->expects('setFetchMode')->with(PDO::FETCH_OBJ); - $statement->expects('execute'); - $statement->expects('fetchAll')->andReturn([42]); - $replacement->expects('prepare')->with('select total')->andReturn($statement)->ordered(); - $replacement->expects('exec')->with("set workload = 'oltp'")->ordered(); + $original = Double::for(PDO::class); + $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->expects('exec')->with("set workload = 'olap'")->returns(0)->ordered(); + $statement = Double::for(PDOStatement::class); + $statement->expects('setFetchMode')->with(PDO::FETCH_OBJ)->returns(true); + $statement->expects('execute')->returns(true); + $statement->expects('fetchAll')->returns([42]); + $replacement->expects('prepare')->with('select total')->returns($statement)->ordered(); + $replacement->expects('exec')->with("set workload = 'oltp'")->returns(0)->ordered(); $connection = new MySqlConnection($original); $reconnects = 0; $connection->setReconnector(static function (MySqlConnection $connection) use ($replacement, &$reconnects): void { @@ -2750,27 +2754,48 @@ public function testOlapReappliesTheWorkloadBeforeRetryingALostConnection(): voi #[TestWith([true], 'read query')] public function testOlapRecoversItsWorkloadAndEndpointAfterAFailedReconnect(bool $read): void { - $original = m::mock(PDO::class); - $original->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->andReturn('8.0.34-vitess'); - $original->expects('exec')->with("set workload = 'olap'"); - $originalRead = m::mock(PDO::class); - $originalRead->expects('exec')->with("set workload = 'olap'"); - $replacement = m::mock(PDO::class); - $replacement->expects('exec')->with("set workload = 'olap'")->globally()->ordered(); - $replacementRead = m::mock(PDO::class); - $replacementRead->expects('exec')->with("set workload = 'olap'")->globally()->ordered(); + $calls = []; + $original = Double::for(PDO::class); + $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->expects('exec')->with("set workload = 'olap'")->returns(0); + $replacement = Double::for(PDO::class); + $replacement->expects('exec')->with("set workload = 'olap'")->resolves(function () use (&$calls): int { + $calls[] = 'write:olap'; + + return 0; + }); + $replacementRead = Double::for(PDO::class); + $replacementRead->expects('exec')->with("set workload = 'olap'")->resolves(function () use (&$calls): int { + $calls[] = 'read:olap'; + + return 0; + }); if ($read) { - $statement = m::mock(PDOStatement::class); - $statement->expects('setFetchMode')->with(PDO::FETCH_OBJ); - $statement->expects('execute'); - $statement->expects('fetchAll')->andReturn([42]); - $replacementRead->expects('prepare')->with('select total')->andReturn($statement)->globally()->ordered(); - $replacement->shouldNotReceive('prepare'); + $statement = Double::for(PDOStatement::class); + $statement->expects('setFetchMode')->with(PDO::FETCH_OBJ)->returns(true); + $statement->expects('execute')->returns(true); + $statement->expects('fetchAll')->returns([42]); + $replacementRead->expects('prepare')->with('select total')->resolves(function () use (&$calls, $statement): PDOStatement { + $calls[] = 'read:query'; + + return $statement; + }); + $replacement->expects('prepare')->never(); } - $replacement->expects('exec')->with("set workload = 'oltp'")->globally()->ordered(); - $replacementRead->expects('exec')->with("set workload = 'oltp'")->globally()->ordered(); + $replacement->expects('exec')->with("set workload = 'oltp'")->resolves(function () use (&$calls): int { + $calls[] = 'write:oltp'; + + return 0; + }); + $replacementRead->expects('exec')->with("set workload = 'oltp'")->resolves(function () use (&$calls): int { + $calls[] = 'read:oltp'; + + return 0; + }); $connection = (new MySqlConnection($original))->setReadPdo($originalRead); $failure = new RuntimeException('Database unavailable.'); $reconnects = 0; @@ -2798,18 +2823,25 @@ public function testOlapRecoversItsWorkloadAndEndpointAfterAFailedReconnect(bool } }); + $this->assertSame([ + 'write:olap', + 'read:olap', + ...($read ? ['read:query'] : []), + 'write:oltp', + 'read:oltp', + ], $calls); $this->assertSame(2, $reconnects); $this->assertSame($replacementRead, $connection->getReadPdo()); } public function testPartialOlapSetupPreventsReusingEitherSession(): void { - $writePdo = m::mock(PDO::class); - $writePdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->andReturn('8.0.34-vitess'); - $writePdo->expects('exec')->with("set workload = 'olap'"); - $readPdo = m::mock(PDO::class); + $writePdo = Double::for(PDO::class); + $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); $failure = new PDOException('Workload change refused.'); - $readPdo->expects('exec')->with("set workload = 'olap'")->andThrow($failure); + $readPdo->expects('exec')->with("set workload = 'olap'")->throws($failure); $connection = (new MySqlConnection($writePdo))->setReadPdo($readPdo); try { @@ -2825,9 +2857,9 @@ public function testPartialOlapSetupPreventsReusingEitherSession(): void public function testOlapRestorationFailurePreservesCancellationAndDiscardsTheSession(): void { - $pdo = m::mock(PDO::class); - $pdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->andReturn('8.0.34-vitess'); - $pdo->expects('exec')->with("set workload = 'olap'"); + $pdo = Double::for(PDO::class); + $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); $cancellation = new CanceledException('Analytics canceled.'); $failure = new RuntimeException('Restore hook failed.'); @@ -3365,7 +3397,7 @@ protected function getMockConnection($methods = [], $pdo = null) if ($methods === []) { $connection = new PdoConnection($pdo, 'test_db', '', ['name' => 'test', 'driver' => 'mysql']); - $connection->setSchemaGrammar(m::mock(SchemaGrammar::class)); + $connection->setSchemaGrammar(Double::for(SchemaGrammar::class)); $connection->enableQueryLog(); return $connection; @@ -3373,7 +3405,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(m::mock(SchemaGrammar::class)); + $connection->method('getDefaultSchemaGrammar')->willReturn(Double::for(SchemaGrammar::class)); $connection->enableQueryLog(); return $connection; diff --git a/tests/Database/DatabaseConnectorTest.php b/tests/Database/DatabaseConnectorTest.php index 922f49b96..041c1d8a5 100755 --- a/tests/Database/DatabaseConnectorTest.php +++ b/tests/Database/DatabaseConnectorTest.php @@ -14,7 +14,8 @@ use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PDOException; use PHPUnit\Framework\Attributes\DataProvider; @@ -25,6 +26,8 @@ class DatabaseConnectorTest extends TestCase { + use VerifiesDoubles; + public function testOptionResolution(): void { $connector = new Connector; @@ -49,11 +52,11 @@ public function testConnectionsRejectNonExceptionErrorModes(int $mode): void public function testMySqlConnectCallsCreateConnectionWithProperArguments(string $dsn, array $config): void { $connector = $this->getMockBuilder(MySqlConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock(); - $connection = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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`;')->andReturn(true); - $connection->expects('exec')->with("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci', SESSION sql_mode='';")->andReturn(true); + $connection->expects('exec')->with('use `bar`;')->returns(0); + $connection->expects('exec')->with("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci', SESSION sql_mode='';")->returns(0); $result = $connector->connect($config); $this->assertSame($result, $connection); @@ -136,10 +139,10 @@ public function testMySqlEscapesBackticksInTheSelectedDatabaseName(): void { $config = ['host' => 'foo', 'database' => 'app`tenant', 'modes' => []]; $connector = $this->getMockBuilder(MySqlConnector::class)->onlyMethods(['createConnection'])->getMock(); - $connection = m::mock(PDO::class); + $connection = Double::for(PDO::class); $connector->expects($this->once())->method('createConnection')->willReturn($connection); - $connection->expects('exec')->with('use `app``tenant`;')->andReturn(true); - $connection->expects('exec')->with("SET SESSION sql_mode='';")->andReturn(true); + $connection->expects('exec')->with('use `app``tenant`;')->returns(0); + $connection->expects('exec')->with("SET SESSION sql_mode='';")->returns(0); $this->assertSame($connection, $connector->connect($config)); } @@ -150,12 +153,12 @@ 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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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`;')->andReturn(true); - $connection->expects('exec')->with('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;')->andReturn(true); - $connection->expects('exec')->with("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci', SESSION sql_mode='';")->andReturn(true); + $connection->expects('exec')->with('use `bar`;')->returns(0); + $connection->expects('exec')->with('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;')->returns(0); + $connection->expects('exec')->with("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci', SESSION sql_mode='';")->returns(0); $result = $connector->connect($config); $this->assertSame($result, $connection); @@ -172,11 +175,11 @@ public function testMySqlLockTimeoutIsCombinedWithConnectionSettings(): void ]; $connector = $this->getMockBuilder(MySqlConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock(); - $connection = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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`;')->andReturn(true); - $connection->expects('exec')->with("SET NAMES 'utf8', SESSION innodb_lock_wait_timeout=2, SESSION lock_wait_timeout=2, SESSION sql_mode='NO_ENGINE_SUBSTITUTION';")->andReturn(true); + $connection->expects('exec')->with('use `bar`;')->returns(0); + $connection->expects('exec')->with("SET NAMES 'utf8', SESSION innodb_lock_wait_timeout=2, SESSION lock_wait_timeout=2, SESSION sql_mode='NO_ENGINE_SUBSTITUTION';")->returns(0); $this->assertSame($connection, $connector->connect($config)); } @@ -197,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(m::mock(PDO::class)); + $connector->expects($this->once())->method('createConnection')->willReturn(Double::for(PDO::class)); try { $connector->connect(['host' => 'localhost', 'database' => '']); @@ -213,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -226,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -258,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -349,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -362,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -375,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -388,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -401,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -414,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -427,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -448,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection'])->getMock(); $connector->expects($this->once())->method('createConnection')->with($dsn, $config, $connector->getOptions($config))->willReturn($connection); @@ -460,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -473,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -486,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -499,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -512,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -525,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -547,7 +550,7 @@ public function testPostgresCombinesMultipleStartupParamsInDsn(): void 'synchronous_commit' => 'on', ]; $connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock(); - $connection = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -560,7 +563,7 @@ public function testSQLiteMemoryDatabasesMayBeConnectedTo(): void $dsn = 'sqlite::memory:'; $config = ['database' => ':memory:']; $connector = $this->getMockBuilder(SQLiteConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock(); - $connection = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -658,7 +661,7 @@ public function testSQLiteRelativePathResolvesAgainstApplicationRoot(): void $config = ['database' => basename(__FILE__)]; $dsn = 'sqlite:' . __FILE__; $connector = $this->getMockBuilder(SQLiteConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock(); - $connection = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -671,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -684,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 = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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); @@ -698,7 +701,7 @@ public function testSQLiteFileDatabasesMayBeConnectedTo(): void $dsn = 'sqlite:' . __DIR__; $config = ['database' => __DIR__]; $connector = $this->getMockBuilder(SQLiteConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock(); - $connection = m::mock(PDO::class); + $connection = Double::for(PDO::class); $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/DatabaseEloquentAsVectorCastTest.php b/tests/Database/DatabaseEloquentAsVectorCastTest.php index 9a8f48ac3..084e5c1ba 100644 --- a/tests/Database/DatabaseEloquentAsVectorCastTest.php +++ b/tests/Database/DatabaseEloquentAsVectorCastTest.php @@ -15,11 +15,14 @@ use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseEloquentAsVectorCastTest extends TestCase { + use VerifiesDoubles; + public function testGetDecodesBinaryVector(): void { $this->useGrammar(MariaDbGrammar::class); @@ -193,12 +196,12 @@ public static function storedVectorProvider(): array */ protected function useGrammar(string $grammar): Grammar { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new $grammar($connection); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); + $connection->allows('getQueryGrammar')->returns($grammar); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->andReturn($connection); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->returns($connection); Model::setConnectionResolver($resolver); diff --git a/tests/Database/DatabaseEloquentBelongsToManyCreateOrFirstTest.php b/tests/Database/DatabaseEloquentBelongsToManyCreateOrFirstTest.php index c447baebc..a8c6b187f 100644 --- a/tests/Database/DatabaseEloquentBelongsToManyCreateOrFirstTest.php +++ b/tests/Database/DatabaseEloquentBelongsToManyCreateOrFirstTest.php @@ -6,9 +6,9 @@ use Closure; use Exception; +use Hypervel\Database\Capsule\Manager as DB; use Hypervel\Database\Connection; use Hypervel\Database\ConnectionResolverInterface; -use Hypervel\Database\Eloquent\Builder; use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\Relations\BelongsToMany; use Hypervel\Database\Eloquent\Relations\MorphToMany; @@ -16,51 +16,60 @@ use Hypervel\Database\UniqueConstraintViolationException; use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; class DatabaseEloquentBelongsToManyCreateOrFirstTest extends TestCase { + use VerifiesDoubles; + + /** + * Set up the database schema. + */ protected function setUp(): void { parent::setUp(); CarbonImmutable::setTestNow('2023-01-01 00:00:00'); + + $db = new DB; + + $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:']); + $db->bootEloquent(); + $db->setAsGlobal(); + + $pdo = $db->getConnection()->getPdo(); + + $pdo->exec('create table "related_table" ( + "id" integer primary key autoincrement not null, + "attr" varchar not null unique, + "val" varchar null, + "created_at" datetime null, + "updated_at" datetime null + )'); + $pdo->exec('create table "pivot_table" ( + "source_id" integer not null, + "related_id" integer not null, + unique ("source_id", "related_id") + )'); } #[DataProvider('createOrFirstValues')] public function testCreateOrFirstMethodCreatesNewRelated(Closure|array $values): void { - $source = new SourceModel; - $source->id = 123; - $this->mockConnectionForModels( - [$source, new RelatedModel], - 'SQLite', - [456], - ); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $source->getConnection()->expects('insert')->with( - 'insert into "related_table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); + $result = $this->related()->createOrFirst(['attr' => 'foo'], $values); - $source->getConnection()->expects('insert')->with( - 'insert into "pivot_table" ("related_id", "source_id") values (?, ?)', - [456, 123], - )->andReturnTrue(); - - $result = $source->related()->createOrFirst(['attr' => 'foo'], $values); $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame([[123, 1]], $this->pivots()); } public static function createOrFirstValues(): array @@ -73,103 +82,61 @@ public static function createOrFirstValues(): array public function testCreateOrFirstMethodAssociatesExistingRelated(): void { - $source = new SourceModel; - $source->id = 123; - $this->mockConnectionForModels( - [$source, new RelatedModel], - 'SQLite', - ); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $sql = 'insert into "related_table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)'; - $bindings = ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; + $this->seedRelated(['attr' => 'foo', 'val' => 'bar']); - $source->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); + $result = $this->related()->createOrFirst(['attr' => 'foo'], ['val' => 'baz']); - $source->getConnection() - ->expects('select') - ->with('select * from "related_table" where ("attr" = ?) limit 1', ['foo'], false, []) - ->andReturn([[ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertEquals([ + 'id' => 1, + 'attr' => 'foo', + 'val' => 'bar', + 'created_at' => '2023-01-01T00:00:00.000000Z', + 'updated_at' => '2023-01-01T00:00:00.000000Z', + ], $result->toArray()); + $this->assertSame(1, $this->relatedRows()); + $this->assertSame([[123, 1]], $this->pivots()); + } - $source->getConnection()->expects('select')->with( - 'select exists(select * from "pivot_table" where "pivot_table"."source_id" = ? and "pivot_table"."related_id" in (?)) as "exists"', - [123, 456], - false, - )->andReturn([['exists' => 0]]); + public function testFirstOrCreateMethodRetrievesExistingRelatedAlreadyAssociated(): void + { + $this->seedRelated(['attr' => 'foo', 'val' => 'bar']); + $this->seedPivot(123, 1); - $source->getConnection()->expects('insert')->with( - 'insert into "pivot_table" ("related_id", "source_id") values (?, ?)', - [456, 123], - )->andReturnTrue(); + $result = $this->related()->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); - $result = $source->related()->createOrFirst(['attr' => 'foo'], ['val' => 'bar']); $this->assertFalse($result->wasRecentlyCreated); $this->assertEquals([ - // Pivot is not loaded when related model is newly created. - 'id' => 456, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', + 'pivot' => ['source_id' => 123, 'related_id' => 1], ], $result->toArray()); + $this->assertSame([[123, 1]], $this->pivots()); } - public function testFirstOrCreateMethodRetrievesExistingRelatedAlreadyAssociated(): void + public function testCreateOrFirstMethodRetrievesExistingRelatedAssociatedJustNow(): void { - $source = new SourceModel; - $source->id = 123; - $source->exists = true; - $this->mockConnectionForModels( - [$source, new RelatedModel], - 'SQLite', - ); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); + // Recovery checks the existing pivot without loading it onto the returned model. + $this->seedRelated(['attr' => 'foo', 'val' => 'bar']); + $this->seedPivot(123, 1); - $source->getConnection() - ->expects('select') - ->with( - 'select "related_table".*, "pivot_table"."source_id" as "pivot_source_id", "pivot_table"."related_id" as "pivot_related_id" from "related_table" inner join "pivot_table" on "related_table"."id" = "pivot_table"."related_id" where "pivot_table"."source_id" = ? and ("attr" = ?) limit 1', - [123, 'foo'], - true, - [], - ) - ->andReturn([[ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - 'pivot_source_id' => 123, - 'pivot_related_id' => 456, - ]]); + $result = $this->related()->createOrFirst(['attr' => 'foo'], ['val' => 'baz']); - $result = $source->related()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); $this->assertFalse($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', - 'pivot' => [ - 'source_id' => 123, - 'related_id' => 456, - ], ], $result->toArray()); + $this->assertSame([[123, 1]], $this->pivots()); } - public function testCreateOrFirstMethodRetrievesExistingRelatedAssociatedJustNow(): void + public function testCreateOrFirstMethodReturnsExistingRelatedAfterAttachCollision(): void { $source = new SourceModel; $source->id = 123; @@ -178,8 +145,8 @@ public function testCreateOrFirstMethodRetrievesExistingRelatedAssociatedJustNow [$source, new RelatedModel], 'SQLite', ); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); + $source->getConnection()->allows('transactionLevel')->returns(0); + $source->getConnection()->allows('getWritableName')->returns('sqlite'); $sql = 'insert into "related_table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)'; $bindings = ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; @@ -187,12 +154,12 @@ public function testCreateOrFirstMethodRetrievesExistingRelatedAssociatedJustNow $source->getConnection() ->expects('insert') ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); + ->throws(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); $source->getConnection() ->expects('select') ->with('select * from "related_table" where ("attr" = ?) limit 1', ['foo'], false, []) - ->andReturn([[ + ->returns([[ 'id' => 456, 'attr' => 'foo', 'val' => 'bar', @@ -206,17 +173,17 @@ public function testCreateOrFirstMethodRetrievesExistingRelatedAssociatedJustNow $source->getConnection() ->expects('insert') ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); + ->throws(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); $source->getConnection() ->expects('select') - ->twice() + ->times(2) ->with( 'select exists(select * from "pivot_table" where "pivot_table"."source_id" = ? and "pivot_table"."related_id" in (?)) as "exists"', [123, 456], false, ) - ->andReturn([['exists' => 0]], [['exists' => 1]]); + ->returns([['exists' => 0]], [['exists' => 1]]); $result = $source->related()->createOrFirst(['attr' => 'foo'], ['val' => 'bar']); $this->assertFalse($result->wasRecentlyCreated); @@ -235,13 +202,13 @@ public function testCreateOrFirstMethodRethrowsAttachViolationWhenExactPivotIsMi $source->id = 123; $source->exists = true; $this->mockConnectionForModels([$source, new RelatedModel], 'SQLite'); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); + $source->getConnection()->allows('transactionLevel')->returns(0); + $source->getConnection()->allows('getWritableName')->returns('sqlite'); $relatedSql = 'insert into "related_table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)'; $relatedBindings = ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - $source->getConnection()->expects('insert')->with($relatedSql, $relatedBindings)->andThrow( + $source->getConnection()->expects('insert')->with($relatedSql, $relatedBindings)->throws( new UniqueConstraintViolationException('sqlite', $relatedSql, $relatedBindings, new Exception) ); $source->getConnection()->expects('select')->with( @@ -249,7 +216,7 @@ public function testCreateOrFirstMethodRethrowsAttachViolationWhenExactPivotIsMi ['foo'], false, [], - )->andReturn([[ + )->returns([[ 'id' => 456, 'attr' => 'foo', 'val' => 'bar', @@ -261,12 +228,12 @@ public function testCreateOrFirstMethodRethrowsAttachViolationWhenExactPivotIsMi $pivotBindings = [456, 123]; $attachException = new UniqueConstraintViolationException('sqlite', $pivotSql, $pivotBindings, new Exception); - $source->getConnection()->expects('insert')->with($pivotSql, $pivotBindings)->andThrow($attachException); + $source->getConnection()->expects('insert')->with($pivotSql, $pivotBindings)->throws($attachException); $source->getConnection()->expects('select')->with( 'select exists(select * from "pivot_table" where "pivot_table"."source_id" = ? and "pivot_table"."related_id" in (?)) as "exists"', [123, 456], false, - )->twice()->andReturn([['exists' => 0]]); + )->times(2)->returns([['exists' => 0]]); try { $source->related()->createOrFirst(['attr' => 'foo'], ['val' => 'bar']); @@ -278,60 +245,22 @@ public function testCreateOrFirstMethodRethrowsAttachViolationWhenExactPivotIsMi public function testFirstOrCreateMethodRetrievesExistingRelatedAndAssociatesIt(): void { - $source = new SourceModel; - $source->id = 123; - $source->exists = true; - $this->mockConnectionForModels( - [$source, new RelatedModel], - 'SQLite', - ); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); + $this->seedRelated(['attr' => 'foo', 'val' => 'bar']); - $source->getConnection() - ->expects('select') - ->with( - 'select "related_table".*, "pivot_table"."source_id" as "pivot_source_id", "pivot_table"."related_id" as "pivot_related_id" from "related_table" inner join "pivot_table" on "related_table"."id" = "pivot_table"."related_id" where "pivot_table"."source_id" = ? and ("attr" = ?) limit 1', - [123, 'foo'], - true, - [], - ) - ->andReturn([]); + $result = $this->related()->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); - $source->getConnection() - ->expects('select') - ->with( - 'select * from "related_table" where ("attr" = ?) limit 1', - ['foo'], - true, - [], - ) - ->andReturn([[ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $source->getConnection() - ->expects('insert') - ->with( - 'insert into "pivot_table" ("related_id", "source_id") values (?, ?)', - [456, 123], - ) - ->andReturnTrue(); - - $result = $source->related()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame('bar', $result->val); $this->assertEquals([ - // Pivot is not loaded when related model is newly created. - 'id' => 456, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->relatedRows()); + $this->assertSame([[123, 1]], $this->pivots()); } public function testFirstOrCreateMethodReturnsExistingRelatedWhenExactPivotExistsAfterAttachCollision(): void @@ -340,22 +269,22 @@ public function testFirstOrCreateMethodReturnsExistingRelatedWhenExactPivotExist $source->id = 123; $source->exists = true; $this->mockConnectionForModels([$source, new RelatedModel], 'SQLite'); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); + $source->getConnection()->allows('transactionLevel')->returns(0); + $source->getConnection()->allows('getWritableName')->returns('sqlite'); $source->getConnection()->expects('select')->with( 'select "related_table".*, "pivot_table"."source_id" as "pivot_source_id", "pivot_table"."related_id" as "pivot_related_id" from "related_table" inner join "pivot_table" on "related_table"."id" = "pivot_table"."related_id" where "pivot_table"."source_id" = ? and ("attr" = ?) limit 1', [123, 'foo'], true, [], - )->andReturn([]); + )->returns([]); $source->getConnection()->expects('select')->with( 'select * from "related_table" where ("attr" = ?) limit 1', ['foo'], true, [], - )->andReturn([[ + )->returns([[ 'id' => 456, 'attr' => 'foo', 'val' => 'bar', @@ -366,7 +295,7 @@ public function testFirstOrCreateMethodReturnsExistingRelatedWhenExactPivotExist $sql = 'insert into "pivot_table" ("related_id", "source_id") values (?, ?)'; $bindings = [456, 123]; - $source->getConnection()->expects('insert')->with($sql, $bindings)->andThrow( + $source->getConnection()->expects('insert')->with($sql, $bindings)->throws( new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception) ); @@ -374,7 +303,7 @@ public function testFirstOrCreateMethodReturnsExistingRelatedWhenExactPivotExist 'select exists(select * from "pivot_table" where "pivot_table"."source_id" = ? and "pivot_table"."related_id" in (?)) as "exists"', [123, 456], false, - )->andReturn([['exists' => 1]]); + )->returns([['exists' => 1]]); $result = $source->related()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); @@ -388,22 +317,22 @@ public function testFirstOrCreateMethodRethrowsAttachViolationWhenExactPivotIsMi $source->id = 123; $source->exists = true; $this->mockConnectionForModels([$source, new RelatedModel], 'SQLite'); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); + $source->getConnection()->allows('transactionLevel')->returns(0); + $source->getConnection()->allows('getWritableName')->returns('sqlite'); $source->getConnection()->expects('select')->with( 'select "related_table".*, "pivot_table"."source_id" as "pivot_source_id", "pivot_table"."related_id" as "pivot_related_id" from "related_table" inner join "pivot_table" on "related_table"."id" = "pivot_table"."related_id" where "pivot_table"."source_id" = ? and ("attr" = ?) limit 1', [123, 'foo'], true, [], - )->andReturn([]); + )->returns([]); $source->getConnection()->expects('select')->with( 'select * from "related_table" where ("attr" = ?) limit 1', ['foo'], true, [], - )->andReturn([[ + )->returns([[ 'id' => 456, 'attr' => 'foo', 'val' => 'bar', @@ -415,12 +344,12 @@ public function testFirstOrCreateMethodRethrowsAttachViolationWhenExactPivotIsMi $bindings = [456, 123]; $attachException = new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception); - $source->getConnection()->expects('insert')->with($sql, $bindings)->andThrow($attachException); + $source->getConnection()->expects('insert')->with($sql, $bindings)->throws($attachException); $source->getConnection()->expects('select')->with( 'select exists(select * from "pivot_table" where "pivot_table"."source_id" = ? and "pivot_table"."related_id" in (?)) as "exists"', [123, 456], false, - )->andReturn([['exists' => 0]]); + )->returns([['exists' => 0]]); try { $source->related()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); @@ -430,276 +359,104 @@ public function testFirstOrCreateMethodRethrowsAttachViolationWhenExactPivotIsMi } } - public function testFirstOrCreateMethodFallsBackToCreateOrFirst(): void + public function testFirstOrCreateMethodAssociatesRelatedOwnedByAnotherSource(): void { - $source = new class extends SourceModel { - protected function newBelongsToMany(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null): BelongsToMany - { - $relation = m::mock(BelongsToMany::class)->makePartial(); - $relation->__construct(...func_get_args()); - $instance = new RelatedModel([ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - 'pivot' => [ - 'source_id' => 123, - 'related_id' => 456, - ], - ]); - $instance->exists = true; - $instance->wasRecentlyCreated = false; - $instance->syncOriginal(); - $relation - ->expects('createOrFirst') - ->with(['attr' => 'foo'], ['val' => 'bar'], [], true) - ->andReturn($instance); - - return $relation; - } - }; - $source->id = 123; - $source->exists = true; - $this->mockConnectionForModels( - [$source, new RelatedModel], - 'SQLite', - ); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); + $this->seedRelated(['attr' => 'foo', 'val' => 'bar']); + $this->seedPivot(999, 1); - $source->getConnection() - ->expects('select') - ->with( - 'select "related_table".*, "pivot_table"."source_id" as "pivot_source_id", "pivot_table"."related_id" as "pivot_related_id" from "related_table" inner join "pivot_table" on "related_table"."id" = "pivot_table"."related_id" where "pivot_table"."source_id" = ? and ("attr" = ?) limit 1', - [123, 'foo'], - true, - [], - ) - ->andReturn([]); + $result = $this->related()->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); - $source->getConnection() - ->expects('select') - ->with( - 'select * from "related_table" where ("attr" = ?) limit 1', - ['foo'], - true, - [], - ) - ->andReturn([]); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame(1, $this->relatedRows()); + $this->assertSame([[999, 1], [123, 1]], $this->pivots()); + } - $result = $source->related()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + public function testFirstOrCreateMethodFallsBackToCreateOrFirst(): void + { + $result = $this->related()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', - 'pivot' => [ - 'source_id' => 123, - 'related_id' => 456, - ], ], $result->toArray()); + $this->assertSame(1, $this->relatedRows()); + $this->assertSame([[123, 1]], $this->pivots()); } public function testUpdateOrCreateMethodCreatesNewRelated(): void { - $source = new class extends SourceModel { - protected function newBelongsToMany(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null): BelongsToMany - { - $relation = m::mock(BelongsToMany::class)->makePartial(); - $relation->__construct(...func_get_args()); - $instance = new RelatedModel([ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]); - $instance->exists = true; - $instance->wasRecentlyCreated = true; - $instance->syncOriginal(); - $relation - ->expects('firstOrCreate') - ->with(['attr' => 'foo'], ['val' => 'baz'], [], true) - ->andReturn($instance); - - return $relation; - } - }; - $source->id = 123; - $this->mockConnectionForModels( - [$source, new RelatedModel], - 'SQLite', - ); + $result = $this->related()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); - $result = $source->related()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); - $this->assertEquals([ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertTrue($result->wasRecentlyCreated); + $this->assertSame('baz', $result->val); + $this->assertSame('baz', DB::table('related_table')->value('val')); + $this->assertSame([[123, 1]], $this->pivots()); } public function testUpdateOrCreateMethodUpdatesExistingRelated(): void { - $source = new class extends SourceModel { - protected function newBelongsToMany(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null): BelongsToMany - { - $relation = m::mock(BelongsToMany::class)->makePartial(); - $relation->__construct(...func_get_args()); - $instance = new RelatedModel([ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]); - $instance->exists = true; - $instance->wasRecentlyCreated = false; - $instance->syncOriginal(); - $relation - ->expects('firstOrCreate') - ->with(['attr' => 'foo'], ['val' => 'baz'], [], true) - ->andReturn($instance); - - return $relation; - } - }; - $source->id = 123; - $this->mockConnectionForModels( - [$source, new RelatedModel], - 'SQLite', - ); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); + $this->seedRelated(['attr' => 'foo', 'val' => 'bar']); + $this->seedPivot(123, 1); - $source->getConnection() - ->expects('update') - ->with( - 'update "related_table" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 456], - ) - ->andReturn(1); + $result = $this->related()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); - $result = $source->related()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); - $this->assertEquals([ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'baz', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame('baz', $result->val); + $this->assertSame('baz', DB::table('related_table')->value('val')); + $this->assertSame(1, $this->relatedRows()); + $this->assertSame([[123, 1]], $this->pivots()); } - public function testUpdateOrCreateMethodAcceptsClosureValuesAndCreates(): void + public function testUpdateOrCreateMethodUpdatesRelatedOwnedByAnotherSourceAndAssociatesIt(): void { - $source = new class extends SourceModel { - protected function newBelongsToMany(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null): BelongsToMany - { - $relation = m::mock(BelongsToMany::class)->makePartial(); - $relation->__construct(...func_get_args()); - $instance = new RelatedModel([ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]); - $instance->exists = true; - $instance->wasRecentlyCreated = true; - $instance->syncOriginal(); - $relation - ->expects('firstOrCreate') - ->withArgs(function ($attributes, $values, $joining, $touch) { - return $attributes === ['attr' => 'foo'] - && $values instanceof Closure - && $joining === [] - && $touch === true; - }) - ->andReturn($instance); - - return $relation; - } - }; - $source->id = 123; - $this->mockConnectionForModels( - [$source, new RelatedModel], - 'SQLite', - ); + $this->seedRelated(['attr' => 'foo', 'val' => 'bar']); + $this->seedPivot(999, 1); + + $result = $this->related()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame('baz', DB::table('related_table')->value('val')); + $this->assertSame([[999, 1], [123, 1]], $this->pivots()); + } + public function testUpdateOrCreateMethodAcceptsClosureValuesAndCreates(): void + { $callCount = 0; - $result = $source->related()->updateOrCreate(['attr' => 'foo'], function () use (&$callCount) { + + $result = $this->related()->updateOrCreate(['attr' => 'foo'], function () use (&$callCount) { ++$callCount; return ['val' => 'baz']; }); - // Closure is forwarded to firstOrCreate which would resolve it on the create path. - // Because we mocked firstOrCreate above, the closure was never invoked here. - $this->assertSame(0, $callCount); - $this->assertSame('bar', $result->val); + $this->assertTrue($result->wasRecentlyCreated); + $this->assertSame(1, $callCount); + $this->assertSame('baz', $result->val); + $this->assertSame('baz', DB::table('related_table')->value('val')); } public function testUpdateOrCreateMethodAcceptsClosureValuesAndUpdates(): void { - $source = new class extends SourceModel { - protected function newBelongsToMany(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null): BelongsToMany - { - $relation = m::mock(BelongsToMany::class)->makePartial(); - $relation->__construct(...func_get_args()); - $instance = new RelatedModel([ - 'id' => 456, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]); - $instance->exists = true; - $instance->wasRecentlyCreated = false; - $instance->syncOriginal(); - $relation - ->expects('firstOrCreate') - ->withArgs(function ($attributes, $values, $joining, $touch) { - return $attributes === ['attr' => 'foo'] - && $values instanceof Closure - && $joining === [] - && $touch === true; - }) - ->andReturn($instance); - - return $relation; - } - }; - $source->id = 123; - $this->mockConnectionForModels( - [$source, new RelatedModel], - 'SQLite', - ); - $source->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $source->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $source->getConnection() - ->expects('update') - ->with( - 'update "related_table" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 456], - ) - ->andReturn(1); + $this->seedRelated(['attr' => 'foo', 'val' => 'bar']); + $this->seedPivot(123, 1); $callCount = 0; - $result = $source->related()->updateOrCreate(['attr' => 'foo'], function () use (&$callCount) { + + $result = $this->related()->updateOrCreate(['attr' => 'foo'], function () use (&$callCount) { ++$callCount; return ['val' => 'baz']; }); - // On the update path firstOrCreate was mocked away, so the closure - // is only resolved once for the fill() call. + $this->assertFalse($result->wasRecentlyCreated); $this->assertSame(1, $callCount); $this->assertSame('baz', $result->val); + $this->assertSame('baz', DB::table('related_table')->value('val')); } #[TestWith([false])] @@ -732,7 +489,7 @@ public function testPivotMembershipCheckIncludesEveryConfiguredPivotConstraint(b 'select exists(select * from "pivot_table" where ("status" = ? and "kind" in (?, ?) and "expired_at" is null and "score" between ? and ?) and "pivot_table"."source_id" = ? and "pivot_table"."related_id" in (?)) as "exists"', ['active', 'primary', 'secondary', 10, 20, 123, $customRelatedKey ? 'related-code' : 456], false, - )->andReturn([['exists' => 1]]); + )->returns([['exists' => 1]]); $this->assertTrue($relation->hasAttached($related)); } @@ -761,38 +518,90 @@ public function testPivotMembershipCheckIncludesMorphDiscriminator(): void 'select exists(select * from "pivot_table" where "pivot_table"."source_id" = ? and "source_type" = ? and "pivot_table"."related_id" in (?)) as "exists"', [123, SourceModel::class, 456], false, - )->andReturn([['exists' => 1]]); + )->returns([['exists' => 1]]); $this->assertTrue($relation->hasAttached($related)); } - protected function mockConnectionForModels(array $models, string $database, array $lastInsertIds = []): void + /** + * Create the relationship for the source model. + */ + protected function related(): BelongsToMany + { + $source = new SourceModel; + $source->id = 123; + $source->exists = true; + + return $source->related(); + } + + /** + * Insert a related record with the frozen timestamps. + */ + protected function seedRelated(array $attributes): void + { + DB::table('related_table')->insert($attributes + [ + 'created_at' => '2023-01-01 00:00:00', + 'updated_at' => '2023-01-01 00:00:00', + ]); + } + + /** + * Attach a related record to the given source. + */ + protected function seedPivot(int $source, int $related): void + { + DB::table('pivot_table')->insert(['source_id' => $source, 'related_id' => $related]); + } + + /** + * Get the stored source and related key pairs. + * + * @return list + */ + protected function pivots(): array + { + return DB::table('pivot_table')->orderBy('rowid')->get() + ->map(fn ($row) => [(int) $row->source_id, (int) $row->related_id]) + ->all(); + } + + /** + * Count the stored related records. + */ + protected function relatedRows(): int + { + return DB::table('related_table')->count(); + } + + /** + * Bind controlled connections for pivot collision and query regressions. + */ + protected function mockConnectionForModels(array $models, string $database): void { $grammarClass = 'Hypervel\Database\Query\Grammars\\' . $database . 'Grammar'; $processorClass = 'Hypervel\Database\Query\Processors\\' . $database . 'Processor'; $processor = new $processorClass; - $connection = m::mock(Connection::class, ['getPostProcessor' => $processor]); + $connection = Double::for(Connection::class); + $connection->allows('getPostProcessor')->returns($processor); $grammar = new $grammarClass($connection); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor) { + $connection->allows('getQueryGrammar')->returns($grammar); + $connection->allows('getTablePrefix')->returns(''); + $connection->allows('query')->resolves(function () use ($connection, $grammar, $processor) { return new BaseBuilder($connection, $grammar, $processor); }); - $connection->shouldReceive('table')->andReturnUsing( + $connection->allows('table')->resolves( fn ($table, $as = null) => $connection->query()->from($table, $as) ); - $connection->shouldReceive('getDatabaseName')->andReturn('database'); - $resolver = m::mock(ConnectionResolverInterface::class, ['connection' => $connection]); + $connection->allows('getDatabaseName')->returns('database'); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->returns($connection); foreach ($models as $model) { /** @var Model $model */ $class = get_class($model); $class::setConnectionResolver($resolver); } - - foreach ($lastInsertIds as $id) { - $connection->expects('getLastInsertId')->andReturn($id); - } } } @@ -815,6 +624,9 @@ class SourceModel extends Model protected array $guarded = []; + /** + * Define the related models. + */ public function related(): BelongsToMany { return $this->belongsToMany( diff --git a/tests/Database/DatabaseEloquentBelongsToManyWithCastedAttributesTest.php b/tests/Database/DatabaseEloquentBelongsToManyWithCastedAttributesTest.php deleted file mode 100644 index 93e686260..000000000 --- a/tests/Database/DatabaseEloquentBelongsToManyWithCastedAttributesTest.php +++ /dev/null @@ -1,121 +0,0 @@ -getRelation(); - $model1 = m::mock(Model::class); - $model1->shouldReceive('hasAttribute')->passthru(); - $model1->shouldReceive('getAttribute')->with('parent_key')->andReturn(1); - $model1->shouldReceive('getAttribute')->with('foo')->passthru(); - $model1->shouldReceive('hasGetMutator')->andReturn(false); - $model1->shouldReceive('hasAttributeMutator')->andReturn(false); - $model1->shouldReceive('hasRelationAutoloadCallback')->andReturn(false); - $model1->shouldReceive('getCasts')->andReturn([]); - $model1->shouldReceive('getRelationValue', 'relationLoaded', 'relationResolver', 'setRelation', 'isRelation')->passthru(); - - $model2 = m::mock(Model::class); - $model2->shouldReceive('hasAttribute')->passthru(); - $model2->shouldReceive('getAttribute')->with('parent_key')->andReturn(2); - $model2->shouldReceive('getAttribute')->with('foo')->passthru(); - $model2->shouldReceive('hasGetMutator')->andReturn(false); - $model2->shouldReceive('hasAttributeMutator')->andReturn(false); - $model2->shouldReceive('hasRelationAutoloadCallback')->andReturn(false); - $model2->shouldReceive('getCasts')->andReturn([]); - $model2->shouldReceive('getRelationValue', 'relationLoaded', 'relationResolver', 'setRelation', 'isRelation')->passthru(); - - $result1 = (object) [ - 'pivot' => (object) [ - 'foreign_key' => new class { - public function __toString() - { - return '1'; - } - }, - ], - ]; - - $models = $relation->match([$model1, $model2], Collection::wrap($result1), 'foo'); - $this->assertNull($models[1]->foo); - $this->assertSame(1, $models[0]->foo->count()); - $this->assertContains($result1, $models[0]->foo); - } - - public function testModelsWithNullParentKeysAreNotMatchedToEmptyStringPivotKeys(): void - { - $relation = $this->getRelation(); - - $model = new class extends Model { - protected array $attributes = ['parent_key' => null]; - }; - - $result = (object) [ - 'pivot' => (object) ['foreign_key' => ''], - ]; - - $relation->match([$model], Collection::wrap($result), 'foo'); - - $this->assertFalse($model->relationLoaded('foo')); - } - - public function testModelsWithNullPivotKeysAreNotMatchedToEmptyStringParentKeys(): void - { - $relation = $this->getRelation(); - - $model = new class extends Model { - protected array $attributes = ['parent_key' => '']; - }; - - $result = (object) [ - 'pivot' => (object) ['foreign_key' => null], - ]; - - $relation->match([$model], Collection::wrap($result), 'foo'); - - $this->assertFalse($model->relationLoaded('foo')); - } - - protected function getRelation() - { - $builder = m::mock(Builder::class); - $related = m::mock(Model::class); - $related->shouldReceive('newCollection')->passthru(); - $related->shouldReceive('resolveCollectionFromAttribute')->passthru(); - $builder->shouldReceive('getModel')->andReturn($related); - $related->shouldReceive('qualifyColumn'); - $builder->shouldReceive('join', 'where'); - $builder->shouldReceive('getQuery')->andReturn( - m::mock(QueryBuilder::class, ['getGrammar' => new Grammar(m::mock(Connection::class))]) - ); - - return new BelongsToMany( - $builder, - new ModelStub, - 'relation', - 'foreign_key', - 'id', - 'parent_key', - 'related_key' - ); - } -} - -class ModelStub extends Model -{ - public string $foreign_key = 'foreign.value'; -} diff --git a/tests/Database/DatabaseEloquentBelongsToManyWithDefaultAttributesTest.php b/tests/Database/DatabaseEloquentBelongsToManyWithDefaultAttributesTest.php deleted file mode 100644 index 03ccb2ad5..000000000 --- a/tests/Database/DatabaseEloquentBelongsToManyWithDefaultAttributesTest.php +++ /dev/null @@ -1,83 +0,0 @@ -getRelationArguments()); - $relation->withPivotValue(['is_admin' => 1]); - } - - public function testWithPivotValueMethodSetsDefaultArgumentsForInsertion(): void - { - $relation = $this->getMockBuilder(BelongsToMany::class)->onlyMethods(['touchIfTouching'])->setConstructorArgs($this->getRelationArguments())->getMock(); - $relation->expects($this->once())->method('touchIfTouching'); - $relation->withPivotValue(['is_admin' => 1]); - - $query = m::mock(QueryBuilder::class); - $query->expects('from')->with('club_user')->andReturn($query); - $query->expects('insert')->with([['club_id' => 1, 'user_id' => 1, 'is_admin' => 1]])->andReturn(true); - $relation->getQuery()->getQuery()->expects('newQuery')->andReturn($query); - - $relation->attach(1); - } - - /** - * Get the arguments for the relationship. - */ - public function getRelationArguments(): array - { - $parent = m::mock(Model::class); - $parent->shouldReceive('getKey')->andReturn(1); - $parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at'); - $parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at'); - $parent->shouldReceive('getAttribute')->with('id')->andReturn(1); - - $builder = m::mock(Builder::class); - $related = m::mock(Model::class); - $builder->shouldReceive('getModel')->andReturn($related); - - $related->shouldReceive('getTable')->andReturn('users'); - $related->shouldReceive('getKeyName')->andReturn('id'); - $related->shouldReceive('qualifyColumn')->with('id')->andReturn('users.id'); - - $builder->expects('join')->with('club_user', 'users.id', '=', 'club_user.user_id'); - $builder->expects('where')->with('club_user.club_id', '=', 1)->andReturnSelf(); - $builder->expects('where')->with('club_user.is_admin', '=', 1, 'and')->andReturnSelf(); - - $mockQueryBuilder = m::mock(QueryBuilder::class); - $builder->shouldReceive('getQuery')->andReturn($mockQueryBuilder); - $mockQueryBuilder->shouldReceive('getGrammar')->andReturn(new Grammar(m::mock(Connection::class))); - $connection = m::mock(ConnectionInterface::class); - $connection->shouldReceive('table')->andReturnUsing( - fn (string $table): QueryBuilder => $mockQueryBuilder->newQuery()->from($table) - ); - $mockQueryBuilder->shouldReceive('getConnection')->andReturn($connection); - - return [ - $builder, - $parent, - 'club_user', - 'club_id', - 'user_id', - 'id', - 'id', - null, - false, - ]; - } -} diff --git a/tests/Database/DatabaseEloquentBelongsToTest.php b/tests/Database/DatabaseEloquentBelongsToTest.php index 8cd205947..e41dfc5d7 100755 --- a/tests/Database/DatabaseEloquentBelongsToTest.php +++ b/tests/Database/DatabaseEloquentBelongsToTest.php @@ -14,11 +14,14 @@ use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\Database\Fixtures\Enums\Bar; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; class DatabaseEloquentBelongsToTest extends TestCase { + use VerifiesDoubles; + protected Builder $builder; protected Model $related; @@ -29,8 +32,8 @@ public function testBelongsToWithDefault(): void // while still having real Model behavior for attribute handling $relation = $this->getRelationWithPartialMock()->withDefault(); - $this->builder->expects('first')->andReturnNull(); - $this->related->expects('newInstance')->andReturnSelf(); + $this->builder->expects('first')->returns(null); + $this->related->expects('newInstance')->returns($this->related); $result = $relation->getResults(); @@ -43,8 +46,8 @@ public function testBelongsToWithDynamicDefault(): void $newModel->username = 'taylor'; }); - $this->builder->expects('first')->andReturnNull(); - $this->related->expects('newInstance')->andReturnSelf(); + $this->builder->expects('first')->returns(null); + $this->related->expects('newInstance')->returns($this->related); $result = $relation->getResults(); @@ -57,8 +60,8 @@ public function testBelongsToWithArrayDefault(): void { $relation = $this->getRelationWithPartialMock()->withDefault(['username' => 'taylor']); - $this->builder->expects('first')->andReturnNull(); - $this->related->expects('newInstance')->andReturnSelf(); + $this->builder->expects('first')->returns(null); + $this->related->expects('newInstance')->returns($this->related); $result = $relation->getResults(); @@ -95,7 +98,7 @@ public function testIdsInEagerConstraintsCanBeBackedEnum(): void public function testRelationIsProperlyInitialized(): void { $relation = $this->getRelation(); - $model = m::mock(Model::class); + $model = Double::for(Model::class); $model->expects('setRelation')->with('foo', null); $models = $relation->initRelation([$model], 'foo'); @@ -306,14 +309,14 @@ protected function getRelationWithRealQuery(string $keyType = 'int'): BelongsTo */ protected function getRelation(?Model $parent = null, string $keyType = 'int'): BelongsTo { - $this->builder = m::mock(Builder::class); + $this->builder = Double::for(Builder::class); $this->builder->expects('where')->with('relation.id', '=', 'foreign.value'); - $this->related = m::mock(Model::class); - $this->related->shouldReceive('getKeyType')->andReturn($keyType); - $this->related->shouldReceive('getKeyName')->andReturn('id'); - $this->related->shouldReceive('getTable')->andReturn('relation'); - $this->related->shouldReceive('qualifyColumn')->andReturnUsing(fn (string $column): string => "relation.{$column}"); - $this->builder->expects('getModel')->andReturn($this->related); + $this->related = Double::for(Model::class); + $this->related->allows('getKeyType')->returns($keyType); + $this->related->allows('getKeyName')->returns('id'); + $this->related->allows('getTable')->returns('relation'); + $this->related->allows('qualifyColumn')->resolves(fn (string $column): string => "relation.{$column}"); + $this->builder->expects('getModel')->returns($this->related); $parent = $parent ?: new ModelStub; return new BelongsTo($this->builder, $parent, 'foreign_key', 'id', 'relation'); @@ -328,14 +331,14 @@ protected function getRelation(?Model $parent = null, string $keyType = 'int'): */ protected function getRelationWithPartialMock(?Model $parent = null): BelongsTo { - $this->builder = m::mock(Builder::class); + $this->builder = Double::for(Builder::class); $this->builder->expects('where')->with('relation.id', '=', 'foreign.value'); - $this->related = m::mock(ModelStub::class)->makePartial(); - $this->related->shouldReceive('getKeyType')->andReturn('int'); - $this->related->shouldReceive('getKeyName')->andReturn('id'); - $this->related->shouldReceive('getTable')->andReturn('relation'); - $this->related->shouldReceive('qualifyColumn')->andReturnUsing(fn (string $column): string => "relation.{$column}"); - $this->builder->expects('getModel')->andReturn($this->related); + $this->related = Double::for(new ModelStub)->passthru(); + $this->related->allows('getKeyType')->returns('int'); + $this->related->allows('getKeyName')->returns('id'); + $this->related->allows('getTable')->returns('relation'); + $this->related->allows('qualifyColumn')->resolves(fn (string $column): string => "relation.{$column}"); + $this->builder->expects('getModel')->returns($this->related); $parent = $parent ?: new ModelStub; return new BelongsTo($this->builder, $parent, 'foreign_key', 'id', 'relation'); diff --git a/tests/Database/DatabaseEloquentBuilderCreateOrFirstTest.php b/tests/Database/DatabaseEloquentBuilderCreateOrFirstTest.php index 5f96d4a8f..6eacf65fc 100755 --- a/tests/Database/DatabaseEloquentBuilderCreateOrFirstTest.php +++ b/tests/Database/DatabaseEloquentBuilderCreateOrFirstTest.php @@ -4,644 +4,316 @@ namespace Hypervel\Tests\Database\DatabaseEloquentBuilderCreateOrFirstTest; +use ArrayObject; use Closure; -use Exception; -use Hypervel\Database\Connection; -use Hypervel\Database\ConnectionResolverInterface; +use Hypervel\Database\Capsule\Manager as DB; +use Hypervel\Database\Eloquent\Builder; use Hypervel\Database\Eloquent\Model; -use Hypervel\Database\Query\Builder; -use Hypervel\Database\Query\Expression; -use Hypervel\Database\UniqueConstraintViolationException; +use Hypervel\Database\Events\QueryExecuted; +use Hypervel\Events\Dispatcher; use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseEloquentBuilderCreateOrFirstTest extends TestCase { + /** + * Set up independent writer and replica databases. + */ protected function setUp(): void { parent::setUp(); CarbonImmutable::setTestNow('2023-01-01 00:00:00'); + + $db = new DB; + + $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:']); + + // Reads come from a replica that has not caught up with the writer yet... + $db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'read' => ['database' => ':memory:'], + 'write' => ['database' => ':memory:'], + ], 'replicated'); + + $db->setEventDispatcher(new Dispatcher); + $db->bootEloquent(); + $db->setAsGlobal(); + + $schema = 'create table "records" ( + "id" integer primary key autoincrement not null, + "attr" varchar not null unique, + "val" varchar null, + "count" integer not null default 0, + "created_at" datetime null, + "updated_at" datetime null + )'; + + $db->getConnection()->getPdo()->exec($schema); + $db->getConnection('replicated')->getPdo()->exec($schema); + $db->getConnection('replicated')->getReadPdo()->exec($schema); } #[DataProvider('createOrFirstValues')] public function testCreateOrFirstMethodCreatesNewRecord(Closure|array $values): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite', [123]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); + $result = $this->modelQuery()->createOrFirst(['attr' => 'foo'], $values); - $model->getConnection()->expects('insert')->with( - 'insert into "table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->newQuery()->createOrFirst(['attr' => 'foo'], $values); $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 123, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->rows()); } public function testCreateOrFirstMethodRetrievesExistingRecord(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $sql = 'insert into "table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)'; - $bindings = ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $model->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], false, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $result = $model->newQuery()->createOrFirst(['attr' => 'foo'], ['val' => 'bar']); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar']); + + $result = $this->modelQuery()->createOrFirst(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertSame(1, $result->id); + $this->assertSame('bar', $result->val); + $this->assertSame(1, $this->rows()); } public function testFirstOrCreateMethodRetrievesExistingRecord(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $result = $model->newQuery()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar']); + + $result = $this->modelQuery()->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertSame(1, $result->id); + $this->assertSame('bar', $result->val); + $this->assertSame(1, $this->rows()); } public function testFirstOrCreateMethodCreatesNewRecord(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite', [123]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->newQuery()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $result = $this->modelQuery()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 123, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->rows()); } public function testFirstOrCreateMethodRetrievesRecordCreatedJustNow(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $sql = 'insert into "table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)'; - $bindings = ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $model->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], false, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $result = $model->newQuery()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + // The replica has not seen the record yet, so the insert collides and the writer is asked again... + $this->seedWriter(['attr' => 'foo', 'val' => 'bar']); + + $result = $this->modelQuery('replicated')->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertSame(1, $result->id); + $this->assertSame('bar', $result->val); + $this->assertSame(1, $this->rows('replicated')); + } + + public function testFirstOrCreateDoesNotTouchTheWriterWhenTheReplicaHasTheRecord(): void + { + $this->seedReplica(['attr' => 'foo', 'val' => 'bar']); + $queries = $this->recordQueries('replicated'); + + $result = $this->modelQuery('replicated')->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); + + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame('bar', $result->val); + $this->assertNotContains('write', array_column($queries->getArrayCopy(), 1)); + } + + public function testUpdateOrCreateLeavesOtherColumnsAndCreatedAtAlone(): void + { + $this->seedRecord(['attr' => 'foo', 'val' => 'bar', 'count' => 5, 'created_at' => '2022-12-31 00:00:00', 'updated_at' => '2022-12-31 00:00:00']); + + $this->modelQuery()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + + $record = (array) DB::connection()->table('records')->first(); + $this->assertSame('baz', $record['val']); + $this->assertEquals(5, $record['count']); + $this->assertSame('2022-12-31 00:00:00', $record['created_at']); + $this->assertSame('2023-01-01 00:00:00', $record['updated_at']); } public function testUpdateOrCreateMethodUpdatesExistingRecord(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $model->getConnection() - ->expects('update') - ->with( - 'update "table" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 123], - ) - ->andReturn(1); - - $result = $model->newQuery()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar']); + + $result = $this->modelQuery()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'baz', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertSame(1, $result->id); + $this->assertSame('baz', $result->val); + $this->assertSame('baz', $this->fresh()->val); + $this->assertSame(1, $this->rows()); } public function testUpdateOrCreateMethodCreatesNewRecord(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite', [123]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->newQuery()->updateOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $result = $this->modelQuery()->updateOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 123, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->rows()); } public function testUpdateOrCreateMethodUpdatesRecordCreatedJustNow(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $sql = 'insert into "table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)'; - $bindings = ['foo', 'baz', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $model->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], false, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $model->getConnection() - ->expects('update') - ->with( - 'update "table" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 123], - ) - ->andReturn(1); - - $result = $model->newQuery()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->seedWriter(['attr' => 'foo', 'val' => 'bar']); + + $result = $this->modelQuery('replicated')->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'baz', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertSame(1, $result->id); + $this->assertSame('baz', $result->val); + $this->assertSame('baz', $this->fresh('replicated', onWriter: true)->val); + $this->assertSame(1, $this->rows('replicated')); } public function testIncrementOrCreateMethodIncrementsExistingRecord(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'count' => 1, - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $model->getConnection() - ->expects('raw') - ->with('"count" + 1') - ->andReturn(new Expression('2')); - - $model->getConnection() - ->expects('update') - ->with( - 'update "table" set "count" = 2, "updated_at" = ? where "id" = ?', - ['2023-01-01 00:00:00', 123], - ) - ->andReturn(1); - - $result = $model->newQuery()->incrementOrCreate(['attr' => 'foo'], 'count'); + $this->seedRecord(['attr' => 'foo', 'count' => 1]); + + $result = $this->modelQuery()->incrementOrCreate(['attr' => 'foo'], 'count'); + $this->assertFalse($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'count' => 2, - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertSame(1, $result->id); + $this->assertEquals(2, $result->count); + $this->assertEquals(2, $this->fresh()->count); } public function testIncrementOrCreateMethodCreatesNewRecord(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite', [123]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "table" ("attr", "count", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', '1', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->newQuery()->incrementOrCreate(['attr' => 'foo']); + $result = $this->modelQuery()->incrementOrCreate(['attr' => 'foo']); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 123, + 'id' => 1, 'attr' => 'foo', 'count' => 1, 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertEquals(1, $this->fresh()->count); } public function testIncrementOrCreateMethodIncrementParametersArePassed(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'count' => 1, - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $model->getConnection() - ->expects('raw') - ->with('"count" + 2') - ->andReturn(new Expression('3')); - - $model->getConnection() - ->expects('update') - ->with( - 'update "table" set "count" = 3, "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 123], - ) - ->andReturn(1); - - $result = $model->newQuery()->incrementOrCreate(['attr' => 'foo'], step: 2, extra: ['val' => 'baz']); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar', 'count' => 1]); + + $result = $this->modelQuery()->incrementOrCreate(['attr' => 'foo'], step: 2, extra: ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'count' => 3, - 'val' => 'baz', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertEquals(3, $result->count); + $this->assertSame('baz', $result->val); + $this->assertEquals(3, $this->fresh()->count); + $this->assertSame('baz', $this->fresh()->val); } public function testIncrementOrCreateMethodExtraParametersArePassedWhenCreating(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite', [123]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "table" ("attr", "val", "count", "updated_at", "created_at") values (?, ?, ?, ?, ?)', - ['foo', 'baz', '1', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->newQuery()->incrementOrCreate(['attr' => 'foo'], step: 2, extra: ['val' => 'baz']); + $result = $this->modelQuery()->incrementOrCreate(['attr' => 'foo'], step: 2, extra: ['val' => 'baz']); + $this->assertTrue($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'baz', - 'count' => 1, - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertSame('baz', $result->val); + $this->assertSame(1, $result->count); + $this->assertEquals(1, $this->fresh()->count); + $this->assertSame('baz', $this->fresh()->val); } public function testIncrementOrCreateMethodRetrievesRecordCreatedJustNow(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $sql = 'insert into "table" ("attr", "count", "updated_at", "created_at") values (?, ?, ?, ?)'; - $bindings = ['foo', '1', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $model->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], false, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'count' => 1, - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $model->getConnection() - ->expects('raw') - ->with('"count" + 1') - ->andReturn(new Expression('2')); - - $model->getConnection() - ->expects('update') - ->with( - 'update "table" set "count" = 2, "updated_at" = ? where "id" = ?', - ['2023-01-01 00:00:00', 123], - ) - ->andReturn(1); - - $result = $model->newQuery()->incrementOrCreate(['attr' => 'foo']); + $this->seedWriter(['attr' => 'foo', 'count' => 1]); + + $result = $this->modelQuery('replicated')->incrementOrCreate(['attr' => 'foo']); + $this->assertFalse($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'count' => 2, - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertSame(1, $result->id); + $this->assertEquals(2, $result->count); + $this->assertEquals(2, $this->fresh('replicated', onWriter: true)->count); } #[DataProvider('createOrFirstValues')] public function testUpdateOrCreateMethodAcceptsClosureValuesAndCreates(Closure|array $values): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite', [123]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->newQuery()->updateOrCreate(['attr' => 'foo'], $values); + $result = $this->modelQuery()->updateOrCreate(['attr' => 'foo'], $values); $this->assertTrue($result->wasRecentlyCreated); - $this->assertEquals([ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ], $result->toArray()); + $this->assertSame('foo', $result->attr); + $this->assertSame('bar', $result->val); + $this->assertSame('bar', $this->fresh()->val); } public function testUpdateOrCreateMethodAcceptsClosureValuesAndUpdates(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $model->getConnection() - ->expects('update') - ->with( - 'update "table" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 123], - ) - ->andReturn(1); - - $result = $model->newQuery()->updateOrCreate(['attr' => 'foo'], fn () => ['val' => 'baz']); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar']); + + $result = $this->modelQuery()->updateOrCreate(['attr' => 'foo'], fn () => ['val' => 'baz']); $this->assertFalse($result->wasRecentlyCreated); $this->assertSame('baz', $result->val); + $this->assertSame('baz', $this->fresh()->val); } public function testUpdateOrCreateInvokesClosureExactlyOnceWhenCreating(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite', [123]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "table" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - $callCount = 0; - $model->newQuery()->updateOrCreate(['attr' => 'foo'], function () use (&$callCount) { + + $result = $this->modelQuery()->updateOrCreate(['attr' => 'foo'], function () use (&$callCount) { ++$callCount; return ['val' => 'bar']; }); $this->assertSame(1, $callCount); + $this->assertSame('bar', $result->val); } public function testUpdateOrCreateInvokesClosureExactlyOnceWhenUpdating(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $model->getConnection() - ->expects('update') - ->with( - 'update "table" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 123], - ) - ->andReturn(1); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar']); $callCount = 0; - $model->newQuery()->updateOrCreate(['attr' => 'foo'], function () use (&$callCount) { + + $result = $this->modelQuery()->updateOrCreate(['attr' => 'foo'], function () use (&$callCount) { ++$callCount; return ['val' => 'baz']; }); $this->assertSame(1, $callCount); + $this->assertSame('baz', $result->val); } #[DataProvider('createOrFirstValues')] public function testFirstOrNewMethodAcceptsClosureValuesAndInstantiates(Closure|array $values): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([]); - - $result = $model->newQuery()->firstOrNew(['attr' => 'foo'], $values); + $result = $this->modelQuery()->firstOrNew(['attr' => 'foo'], $values); $this->assertFalse($result->exists); $this->assertSame('foo', $result->attr); $this->assertSame('bar', $result->val); + $this->assertSame(0, $this->rows()); } /** @@ -657,24 +329,10 @@ public static function createOrFirstValues(): array public function testFirstOrNewDoesNotInvokeClosureWhenRecordExists(): void { - $model = new TestModel; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "table" where ("attr" = ?) limit 1', ['foo'], true, []) - ->andReturn([[ - 'id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar']); $callCount = 0; - $result = $model->newQuery()->firstOrNew(['attr' => 'foo'], function () use (&$callCount) { + $result = $this->modelQuery()->firstOrNew(['attr' => 'foo'], function () use (&$callCount) { ++$callCount; return ['val' => 'should-not-be-called']; @@ -686,35 +344,79 @@ public function testFirstOrNewDoesNotInvokeClosureWhenRecordExists(): void } /** - * Mock the model's database connection. + * Create a model query on the given connection. + */ + protected function modelQuery(string $connection = 'default'): Builder + { + return (new TestModel)->setConnection($connection)->newQuery(); + } + + /** + * Insert a record on the default connection. + */ + protected function seedRecord(array $attributes): void + { + $this->seedWriter($attributes, 'default'); + } + + /** + * Insert a record on the writer. + */ + protected function seedWriter(array $attributes, string $connection = 'replicated'): void + { + DB::connection($connection)->table('records')->insert($attributes + [ + 'created_at' => '2023-01-01 00:00:00', + 'updated_at' => '2023-01-01 00:00:00', + ]); + } + + /** + * Insert a record directly on the replica. */ - protected function mockConnectionForModel(Model $model, string $database, array $lastInsertIds = []): void + protected function seedReplica(array $attributes): void { - $grammarClass = 'Hypervel\Database\Query\Grammars\\' . $database . 'Grammar'; - $processorClass = 'Hypervel\Database\Query\Processors\\' . $database . 'Processor'; - $processor = new $processorClass; - $connection = m::mock(Connection::class, ['getPostProcessor' => $processor]); - $grammar = new $grammarClass($connection); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor) { - return new Builder($connection, $grammar, $processor); + DB::connection('replicated')->getReadPdo()->exec(sprintf( + 'insert into "records" ("attr", "val", "created_at", "updated_at") values (%s)', + implode(', ', array_map(fn ($value) => "'{$value}'", [$attributes['attr'], $attributes['val'], '2023-01-01 00:00:00', '2023-01-01 00:00:00'])) + )); + } + + /** + * Record the verb and read/write side of each query the connection reports. + */ + protected function recordQueries(string $connection): ArrayObject + { + $queries = new ArrayObject; + + DB::connection($connection)->listen(function (QueryExecuted $query) use ($queries) { + $queries[] = [strtok($query->sql, ' '), $query->readWriteType]; }); - $connection->shouldReceive('getDatabaseName')->andReturn('database'); - $resolver = m::mock(ConnectionResolverInterface::class, ['connection' => $connection]); - $class = get_class($model); - $class::setConnectionResolver($resolver); + return $queries; + } + + /** + * Retrieve the stored record from the selected connection role. + */ + protected function fresh(string $connection = 'default', bool $onWriter = false): TestModel + { + $query = $this->modelQuery($connection); - foreach ($lastInsertIds as $id) { - $connection->expects('getLastInsertId')->andReturn($id); - } + return ($onWriter ? $query->useWritePdo() : $query)->where('attr', 'foo')->firstOrFail(); + } + + /** + * Count the records stored on the writer. + */ + protected function rows(string $connection = 'default'): int + { + return DB::connection($connection)->table('records')->useWritePdo()->count(); } } class TestModel extends Model { - protected ?string $table = 'table'; + protected ?string $table = 'records'; protected array $guarded = []; } diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php index 44e3189e2..67938a8b7 100755 --- a/tests/Database/DatabaseEloquentBuilderTest.php +++ b/tests/Database/DatabaseEloquentBuilderTest.php @@ -34,7 +34,9 @@ use Hypervel\Tests\Database\Concerns\InteractsWithInMemoryConnection; use Hypervel\Tests\Database\Fixtures\Enums\Bar; use InvalidArgumentException; -use Mockery as m; +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; @@ -45,16 +47,17 @@ class DatabaseEloquentBuilderTest extends TestCase { use InteractsWithInMemoryConnection; + use VerifiesDoubles; public function testFindMethod(): void { - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); $builder->setModel($model); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 'bar', 'and'); - $expectedModel = m::mock(Model::class); - $builder->expects('first')->with(['column'])->andReturn($expectedModel); + $expectedModel = Double::for(Model::class); + $builder->expects('first')->with(['column'])->returns($expectedModel); $result = $builder->find('bar', ['column']); $this->assertSame($expectedModel, $result); @@ -66,26 +69,26 @@ public function testFindMethod(): void #[TestWith(['findOr'])] public function testFindMethodsUseModelPrimaryKey(string $method): void { - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->setModel($model); $target = (new Stub)->forceFill(['id' => 1, 'other_id' => 2]); $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 1, 'and'); - $builder->expects('first')->with(['column'])->andReturn($target); + $builder->expects('first')->with(['column'])->returns($target); $this->assertSame($target, $builder->{$method}($target, ['column'])); } public function testFindOrFailThrowsForMissingModelArgument(): void { - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->setModel($model); $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 1, 'and'); - $builder->expects('first')->with(['column'])->andReturn(null); + $builder->expects('first')->with(['column'])->returns(null); $this->expectExceptionObject((new ModelNotFoundException)->setModel(get_class($model), 1)); @@ -94,13 +97,13 @@ public function testFindOrFailThrowsForMissingModelArgument(): void public function testFindSoleMethod(): void { - $builder = m::mock(Builder::class . '[sole]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); $builder->setModel($model); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 'bar', 'and'); - $expectedModel = m::mock(Model::class); - $builder->expects('sole')->with(['column'])->andReturn($expectedModel); + $expectedModel = Double::for(Model::class); + $builder->expects('sole')->with(['column'])->returns($expectedModel); $result = $builder->findSole('bar', ['column']); $this->assertSame($expectedModel, $result); @@ -109,87 +112,53 @@ public function testFindSoleMethod(): void public function testFindManyMethod(): void { // ids are not empty - $builder = m::mock(Builder::class . '[get]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->setModel($model); $builder->getQuery()->expects('whereIntegerInRaw')->with('foo_table.foo', ['one', 'two'], 'and', false); $expectedCollection = new Collection(['baz']); - $builder->expects('get')->with(['column'])->andReturn($expectedCollection); + $builder->expects('get')->with(['column'])->returns($expectedCollection); $result = $builder->findMany(['one', 'two'], ['column']); $this->assertEquals($expectedCollection, $result); // ids are empty array - $builder = m::mock(Builder::class . '[get]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); $emptyCollection = new Collection; - $model->expects('newCollection')->withNoArgs()->andReturn($emptyCollection); - $model->shouldReceive('getKeyType')->andReturn('int'); + $model->expects('newCollection')->with(Argument::none())->returns($emptyCollection); + $model->allows('getKeyType')->returns('int'); $builder->setModel($model); - $builder->getQuery()->shouldNotReceive('whereIntegerInRaw'); - $builder->shouldNotReceive('get'); + $builder->getQuery()->expects('whereIntegerInRaw')->never(); + $builder->expects('get')->never(); $result = $builder->findMany([], ['column']); $this->assertSame($emptyCollection, $result); // ids are empty collection - $builder = m::mock(Builder::class . '[get]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); $emptyCollection2 = new Collection; - $model->expects('newCollection')->withNoArgs()->andReturn($emptyCollection2); + $model->expects('newCollection')->with(Argument::none())->returns($emptyCollection2); $builder->setModel($model); - $builder->getQuery()->shouldNotReceive('whereIn'); - $builder->shouldNotReceive('get'); + $builder->getQuery()->expects('whereIn')->never(); + $builder->expects('get')->never(); $result = $builder->findMany(collect(), ['column']); $this->assertSame($emptyCollection2, $result); } - public function testFindOrNewMethodModelFound(): void - { - $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); - $expectedModel = m::mock(Model::class); - $model->expects('findOrNew')->andReturn($expectedModel); - - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); - $builder->setModel($model); - $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 'bar', 'and'); - $builder->expects('first')->with(['column'])->andReturn($expectedModel); - - $expected = $model->findOrNew('bar', ['column']); - $result = $builder->find('bar', ['column']); - $this->assertEquals($expected, $result); - } - - public function testFindOrNewMethodModelNotFound(): void - { - $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); - $model->expects('findOrNew')->andReturn(m::mock(Model::class)); - - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); - $builder->setModel($model); - $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 'bar', 'and'); - $builder->expects('first')->with(['column'])->andReturn(null); - - $result = $model->findOrNew('bar', ['column']); - $findResult = $builder->find('bar', ['column']); - $this->assertNull($findResult); - $this->assertInstanceOf(Model::class, $result); - } - public function testFindOrFailMethodThrowsModelNotFoundException(): void { $this->expectException(ModelNotFoundException::class); - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->setModel($model); $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 'bar', 'and'); - $builder->expects('first')->with(['column'])->andReturn(null); + $builder->expects('first')->with(['column'])->returns(null); $builder->findOrFail('bar', ['column']); } @@ -216,13 +185,13 @@ public function testFindOrFailMethodWithManyThrowsModelNotFoundException(): void $this->expectException(ModelNotFoundException::class); $model = $this->getMockModel(); - $model->expects('getKey')->andReturn(1); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKey')->returns(1); + $model->expects('getKeyType')->returns('int'); - $builder = m::mock(Builder::class . '[get]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $builder->setModel($model); $builder->getQuery()->expects('whereIntegerInRaw')->with('foo_table.foo', [1, 2], 'and', false); - $builder->expects('get')->with(['column'])->andReturn(new Collection([$model])); + $builder->expects('get')->with(['column'])->returns(new Collection([$model])); $builder->findOrFail([1, 2], ['column']); } @@ -231,13 +200,13 @@ public function testFindOrFailMethodWithManyUsingCollectionThrowsModelNotFoundEx $this->expectException(ModelNotFoundException::class); $model = $this->getMockModel(); - $model->expects('getKey')->andReturn(1); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKey')->returns(1); + $model->expects('getKeyType')->returns('int'); - $builder = m::mock(Builder::class . '[get]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $builder->setModel($model); $builder->getQuery()->expects('whereIntegerInRaw')->with('foo_table.foo', [1, 2], 'and', false); - $builder->expects('get')->with(['column'])->andReturn(new Collection([$model])); + $builder->expects('get')->with(['column'])->returns(new Collection([$model])); $builder->findOrFail(new Collection([1, 2]), ['column']); } @@ -248,12 +217,12 @@ public function testFindOrFailWithEnumIds(BackedEnum $id, int|string $value, boo $model = new Stub; $model->setAttribute($model->getKeyName(), $value); - $builder = m::mock(Builder::class . '[find]', [$connection->query()]); + $builder = Double::for(new Builder($connection->query()))->passthru(); $builder->setModel($model); $models = new Collection([$model]); $ids = [$id, $id, $value]; $ids = $useCollection ? new BaseCollection($ids) : $ids; - $builder->expects('find')->with($ids, ['column'])->andReturn($models); + $builder->expects('find')->with($ids, ['column'])->returns($models); $this->assertSame($models, $builder->findOrFail($ids, ['column'])); } @@ -266,11 +235,11 @@ public function testFindOrFailWithMissingEnumIds(BackedEnum $id, int|string $val $model->setKeyType('string'); $model->setAttribute($model->getKeyName(), 'existing'); - $builder = m::mock(Builder::class . '[find]', [$connection->query()]); + $builder = Double::for(new Builder($connection->query()))->passthru(); $builder->setModel($model); $ids = ['existing', $id]; $ids = $useCollection ? new BaseCollection($ids) : $ids; - $builder->expects('find')->with($ids, ['*'])->andReturn(new Collection([$model])); + $builder->expects('find')->with($ids, ['*'])->returns(new Collection([$model])); try { $builder->findOrFail($ids); @@ -292,103 +261,25 @@ public static function enumIdsProvider(): iterable } } - public function testFindOrMethod(): void - { - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); - $model = $this->getMockModel(); - $model->expects('getKeyType')->times(3)->andReturn('int'); - $builder->setModel($model); - $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 1, 'and')->times(2); - $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 2, 'and'); - $builder->expects('first')->andReturn($model); - $builder->expects('first')->with(['column'])->andReturn($model); - $builder->expects('first')->andReturn(null); - - $this->assertSame($model, $builder->findOr(1, fn (): string => 'callback result')); - $this->assertSame($model, $builder->findOr(1, ['column'], fn (): string => 'callback result')); - $this->assertSame('callback result', $builder->findOr(2, fn (): string => 'callback result')); - } - - public function testFindOrMethodWithMany(): void - { - $builder = m::mock(Builder::class . '[get]', [$this->getMockQueryBuilder()]); - $model1 = $this->getMockModel(); - $model2 = $this->getMockModel(); - $model1->expects('getKeyType')->times(3)->andReturn('int'); - $model2->shouldReceive('getKeyType')->andReturn('int'); - $model1->expects('newCollection')->andReturn(new Collection); - $builder->setModel($model1); - $builder->getQuery()->expects('whereIntegerInRaw')->with('foo_table.foo', [1, 2], 'and', false)->times(2); - $builder->getQuery()->expects('whereIntegerInRaw')->with('foo_table.foo', [1, 2, 3], 'and', false); - $builder->expects('get')->andReturn(new Collection([$model1, $model2])); - $builder->expects('get')->with(['column'])->andReturn(new Collection([$model1, $model2])); - $builder->expects('get')->andReturn(new Collection([$model1, $model2])); - - $result = $builder->findOr([1, 2], fn (): string => 'callback result'); - $this->assertInstanceOf(Collection::class, $result); - $this->assertSame($model1, $result[0]); - $this->assertSame($model2, $result[1]); - - $result = $builder->findOr([1, 2], ['column'], fn (): string => 'callback result'); - $this->assertInstanceOf(Collection::class, $result); - $this->assertSame($model1, $result[0]); - $this->assertSame($model2, $result[1]); - - $result = $builder->findOr([1, 2, 3], fn (): string => 'callback result'); - $this->assertSame('callback result', $result); - - $result = $builder->findOr([], fn (): string => 'callback result'); - $this->assertInstanceOf(Collection::class, $result); - $this->assertCount(0, $result); - } - - public function testFindOrMethodWithManyUsingCollection(): void - { - $builder = m::mock(Builder::class . '[get]', [$this->getMockQueryBuilder()]); - $model1 = $this->getMockModel(); - $model2 = $this->getMockModel(); - $model1->expects('getKeyType')->times(3)->andReturn('int'); - $model2->shouldReceive('getKeyType')->andReturn('int'); - $builder->setModel($model1); - $builder->getQuery()->expects('whereIntegerInRaw')->with('foo_table.foo', [1, 2], 'and', false)->times(2); - $builder->getQuery()->expects('whereIntegerInRaw')->with('foo_table.foo', [1, 2, 3], 'and', false); - $builder->expects('get')->andReturn(new Collection([$model1, $model2])); - $builder->expects('get')->with(['column'])->andReturn(new Collection([$model1, $model2])); - $builder->expects('get')->andReturn(new Collection([$model1, $model2])); - - $result = $builder->findOr(new Collection([1, 2]), fn (): string => 'callback result'); - $this->assertInstanceOf(Collection::class, $result); - $this->assertSame($model1, $result[0]); - $this->assertSame($model2, $result[1]); - - $result = $builder->findOr(new Collection([1, 2]), ['column'], fn (): string => 'callback result'); - $this->assertInstanceOf(Collection::class, $result); - $this->assertSame($model1, $result[0]); - $this->assertSame($model2, $result[1]); - - $result = $builder->findOr(new Collection([1, 2, 3]), fn (): string => 'callback result'); - $this->assertSame('callback result', $result); - } - public function testFirstOrFailMethodThrowsModelNotFoundException(): void { $this->expectException(ModelNotFoundException::class); - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $builder->setModel($this->getMockModel()); - $builder->expects('first')->with(['column'])->andReturn(null); + $builder->expects('first')->with(['column'])->returns(null); $builder->firstOrFail(['column']); } public function testFindWithMany(): void { - $builder = m::mock(Builder::class . '[get]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->getQuery()->expects('whereIntegerInRaw')->with('foo_table.foo', [1, 2], 'and', false); $builder->setModel($model); $expectedCollection = new Collection(['baz']); - $builder->expects('get')->with(['column'])->andReturn($expectedCollection); + $builder->expects('get')->with(['column'])->returns($expectedCollection); $result = $builder->find([1, 2], ['column']); $this->assertSame($expectedCollection, $result); @@ -397,13 +288,13 @@ public function testFindWithMany(): void public function testFindWithManyUsingCollection(): void { $ids = collect([1, 2]); - $builder = m::mock(Builder::class . '[get]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->getQuery()->expects('whereIntegerInRaw')->with('foo_table.foo', [1, 2], 'and', false); $builder->setModel($model); $expectedCollection = new Collection(['baz']); - $builder->expects('get')->with(['column'])->andReturn($expectedCollection); + $builder->expects('get')->with(['column'])->returns($expectedCollection); $result = $builder->find($ids, ['column']); $this->assertSame($expectedCollection, $result); @@ -422,9 +313,9 @@ public function testFirstMethod(): void public function testQualifyColumn(): void { - $builder = new Builder(m::mock(BaseBuilder::class)); + $builder = new Builder(Double::for(BaseBuilder::class)); $builder->expects('from')->with('foo_table'); - $builder->getQuery()->allows('getFromAlias')->andReturnNull(); + $builder->getQuery()->allows('getFromAlias')->returns(null); $builder->setModel(new StubStringPrimaryKey); @@ -433,9 +324,9 @@ public function testQualifyColumn(): void public function testQualifyColumns(): void { - $builder = new Builder(m::mock(BaseBuilder::class)); + $builder = new Builder(Double::for(BaseBuilder::class)); $builder->expects('from')->with('foo_table'); - $builder->getQuery()->allows('getFromAlias')->andReturnNull(); + $builder->getQuery()->allows('getFromAlias')->returns(null); $builder->setModel(new StubStringPrimaryKey); @@ -444,7 +335,8 @@ public function testQualifyColumns(): void public function testQualifyColumnWithTableAlias(): void { - $connection = m::mock(Connection::class, ['getTablePrefix' => '']); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); $query = new BaseBuilder($connection, new Grammar($connection), new Processor); $builder = new Builder($query); $builder->setModel(new StubStringPrimaryKey); @@ -470,11 +362,11 @@ public function testQualifyColumnWithTableAlias(): void public function testGetMethodLoadsModelsAndHydratesEagerRelations(): void { - $builder = m::mock(Builder::class . '[getModels,eagerLoadRelations]', [$this->getMockQueryBuilder()]); - $builder->expects('getModels')->with(['foo'])->andReturn(['bar']); - $builder->expects('eagerLoadRelations')->with(['bar'])->andReturn(['bar', 'baz']); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); + $builder->expects('getModels')->with(['foo'])->returns(['bar']); + $builder->expects('eagerLoadRelations')->with(['bar'])->returns(['bar', 'baz']); $builder->setModel($this->getMockModel()); - $builder->getModel()->expects('newCollection')->with(['bar', 'baz'])->andReturn(new Collection(['bar', 'baz'])); + $builder->getModel()->expects('newCollection')->with(['bar', 'baz'])->returns(new Collection(['bar', 'baz'])); $results = $builder->get(['foo']); $this->assertEquals(['bar', 'baz'], $results->all()); @@ -482,11 +374,11 @@ public function testGetMethodLoadsModelsAndHydratesEagerRelations(): void public function testGetMethodDoesntHydrateEagerRelationsWhenNoResultsAreReturned(): void { - $builder = m::mock(Builder::class . '[getModels,eagerLoadRelations]', [$this->getMockQueryBuilder()]); - $builder->expects('getModels')->with(['foo'])->andReturn([]); - $builder->shouldReceive('eagerLoadRelations')->never(); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); + $builder->expects('getModels')->with(['foo'])->returns([]); + $builder->expects('eagerLoadRelations')->never(); $builder->setModel($this->getMockModel()); - $builder->getModel()->expects('newCollection')->with([])->andReturn(new Collection([])); + $builder->getModel()->expects('newCollection')->with([])->returns(new Collection([])); $results = $builder->get(['foo']); $this->assertSame([], $results->all()); @@ -494,28 +386,28 @@ public function testGetMethodDoesntHydrateEagerRelationsWhenNoResultsAreReturned public function testValueMethodWithModelFound(): void { - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $mockModel = new class extends Model {}; $mockModel->name = 'foo'; - $builder->expects('first')->with(['name'])->andReturn($mockModel); + $builder->expects('first')->with(['name'])->returns($mockModel); $this->assertSame('foo', $builder->value('name')); } public function testValueMethodWithModelNotFound(): void { - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); - $builder->expects('first')->with(['name'])->andReturn(null); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); + $builder->expects('first')->with(['name'])->returns(null); $this->assertNull($builder->value('name')); } public function testValueOrFailMethodWithModelFound(): void { - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); - $mockModel = m::mock(Model::class)->makePartial(); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); + $mockModel = new Stub; $mockModel->forceFill(['name' => 'foo']); - $builder->expects('first')->with(['name'])->andReturn($mockModel); + $builder->expects('first')->with(['name'])->returns($mockModel); $this->assertSame('foo', $builder->valueOrFail('name')); } @@ -524,12 +416,12 @@ public function testValueOrFailMethodWithModelNotFoundThrowsModelNotFoundExcepti { $this->expectException(ModelNotFoundException::class); - $builder = m::mock(Builder::class . '[first]', [$this->getMockQueryBuilder()]); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->setModel($model); $builder->getQuery()->expects('where')->with('foo_table.foo', '=', 'bar', 'and'); - $builder->expects('first')->with(['column'])->andReturn(null); + $builder->expects('first')->with(['column'])->returns(null); $builder->whereKey('bar')->valueOrFail('column'); } @@ -653,9 +545,9 @@ public function testChunkDoesNotMutateTheOriginalBuilder(): void $model = new Stub; $connection = $this->mockConnectionForModel($model, ''); - $connection->shouldReceive('getName')->andReturn('default'); - $connection->shouldReceive('getWritableName')->andReturn('default'); - $connection->shouldReceive('select')->andReturn( + $connection->allows('getName')->returns('default'); + $connection->allows('getWritableName')->returns('default'); + $connection->allows('select')->returns( [(object) ['id' => 1], (object) ['id' => 2]], [(object) ['id' => 3]], [(object) ['id' => 1], (object) ['id' => 2]], @@ -716,9 +608,9 @@ public function testLazyDoesNotMutateTheOriginalBuilder(): void $model = new Stub; $connection = $this->mockConnectionForModel($model, ''); - $connection->shouldReceive('getName')->andReturn('default'); - $connection->shouldReceive('getWritableName')->andReturn('default'); - $connection->shouldReceive('select')->andReturn( + $connection->allows('getName')->returns('default'); + $connection->allows('getWritableName')->returns('default'); + $connection->allows('select')->returns( [(object) ['id' => 1], (object) ['id' => 2]], [(object) ['id' => 3]], [(object) ['id' => 1], (object) ['id' => 2]], @@ -855,14 +747,14 @@ public function testPagingPreservesBinaryBindingsForSelectedAliases(string $meth public function testPluckReturnsTheMutatedAttributesOfAModel(): void { $builder = $this->getBuilder(); - $builder->getQuery()->expects('pluck')->with('name', '')->andReturn(new BaseCollection(['bar', 'baz'])); - $model = m::mock(PluckStub::class)->makePartial(); - $model->shouldReceive('getKeyName')->andReturn('foo'); - $model->shouldReceive('getTable')->andReturn('foo_table'); - $model->shouldReceive('getQualifiedKeyName')->andReturn('foo_table.foo'); - $model->expects('hasAnyGetMutator')->with('name')->andReturn(true); - $model->expects('newFromBuilder')->with(['name' => 'bar'])->andReturn(m::mock(PluckStub::class)->makePartial()->setRawAttributes(['name' => 'bar'])); - $model->expects('newFromBuilder')->with(['name' => 'baz'])->andReturn(m::mock(PluckStub::class)->makePartial()->setRawAttributes(['name' => 'baz'])); + $builder->getQuery()->expects('pluck')->with('name', null)->returns(new BaseCollection(['bar', 'baz'])); + $model = Double::for(new PluckStub)->passthru(); + $model->allows('getKeyName')->returns('foo'); + $model->allows('getTable')->returns('foo_table'); + $model->allows('getQualifiedKeyName')->returns('foo_table.foo'); + $model->expects('hasAnyGetMutator')->with('name')->returns(true); + $model->expects('newFromBuilder')->with(['name' => 'bar'])->returns(Double::for(new PluckStub)->passthru()->setRawAttributes(['name' => 'bar'])); + $model->expects('newFromBuilder')->with(['name' => 'baz'])->returns(Double::for(new PluckStub)->passthru()->setRawAttributes(['name' => 'baz'])); $builder->setModel($model); $this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck('name')->all()); @@ -871,15 +763,15 @@ public function testPluckReturnsTheMutatedAttributesOfAModel(): void public function testPluckReturnsTheCastedAttributesOfAModel(): void { $builder = $this->getBuilder(); - $builder->getQuery()->expects('pluck')->with('name', '')->andReturn(new BaseCollection(['bar', 'baz'])); - $model = m::mock(PluckStub::class)->makePartial(); - $model->shouldReceive('getKeyName')->andReturn('foo'); - $model->shouldReceive('getTable')->andReturn('foo_table'); - $model->shouldReceive('getQualifiedKeyName')->andReturn('foo_table.foo'); - $model->expects('hasAnyGetMutator')->with('name')->andReturn(false); - $model->expects('hasCast')->with('name')->andReturn(true); - $model->expects('newFromBuilder')->with(['name' => 'bar'])->andReturn(m::mock(PluckStub::class)->makePartial()->setRawAttributes(['name' => 'bar'])); - $model->expects('newFromBuilder')->with(['name' => 'baz'])->andReturn(m::mock(PluckStub::class)->makePartial()->setRawAttributes(['name' => 'baz'])); + $builder->getQuery()->expects('pluck')->with('name', null)->returns(new BaseCollection(['bar', 'baz'])); + $model = Double::for(new PluckStub)->passthru(); + $model->allows('getKeyName')->returns('foo'); + $model->allows('getTable')->returns('foo_table'); + $model->allows('getQualifiedKeyName')->returns('foo_table.foo'); + $model->expects('hasAnyGetMutator')->with('name')->returns(false); + $model->expects('hasCast')->with('name')->returns(true); + $model->expects('newFromBuilder')->with(['name' => 'bar'])->returns(Double::for(new PluckStub)->passthru()->setRawAttributes(['name' => 'bar'])); + $model->expects('newFromBuilder')->with(['name' => 'baz'])->returns(Double::for(new PluckStub)->passthru()->setRawAttributes(['name' => 'baz'])); $builder->setModel($model); $this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck('name')->all()); @@ -888,16 +780,16 @@ public function testPluckReturnsTheCastedAttributesOfAModel(): void public function testPluckReturnsTheDateAttributesOfAModel(): void { $builder = $this->getBuilder(); - $builder->getQuery()->expects('pluck')->with('created_at', '')->andReturn(new BaseCollection(['2010-01-01 00:00:00', '2011-01-01 00:00:00'])); - $model = m::mock(PluckDatesStub::class)->makePartial(); - $model->shouldReceive('getKeyName')->andReturn('foo'); - $model->shouldReceive('getTable')->andReturn('foo_table'); - $model->shouldReceive('getQualifiedKeyName')->andReturn('foo_table.foo'); - $model->expects('hasAnyGetMutator')->with('created_at')->andReturn(false); - $model->expects('hasCast')->with('created_at')->andReturn(false); - $model->expects('getDates')->andReturn(['created_at']); - $model->expects('newFromBuilder')->with(['created_at' => '2010-01-01 00:00:00'])->andReturn(m::mock(PluckDatesStub::class)->makePartial()->setRawAttributes(['created_at' => '2010-01-01 00:00:00'])); - $model->expects('newFromBuilder')->with(['created_at' => '2011-01-01 00:00:00'])->andReturn(m::mock(PluckDatesStub::class)->makePartial()->setRawAttributes(['created_at' => '2011-01-01 00:00:00'])); + $builder->getQuery()->expects('pluck')->with('created_at', null)->returns(new BaseCollection(['2010-01-01 00:00:00', '2011-01-01 00:00:00'])); + $model = Double::for(new PluckDatesStub)->passthru(); + $model->allows('getKeyName')->returns('foo'); + $model->allows('getTable')->returns('foo_table'); + $model->allows('getQualifiedKeyName')->returns('foo_table.foo'); + $model->expects('hasAnyGetMutator')->with('created_at')->returns(false); + $model->expects('hasCast')->with('created_at')->returns(false); + $model->expects('getDates')->returns(['created_at']); + $model->expects('newFromBuilder')->with(['created_at' => '2010-01-01 00:00:00'])->returns(Double::for(new PluckDatesStub)->passthru()->setRawAttributes(['created_at' => '2010-01-01 00:00:00'])); + $model->expects('newFromBuilder')->with(['created_at' => '2011-01-01 00:00:00'])->returns(Double::for(new PluckDatesStub)->passthru()->setRawAttributes(['created_at' => '2011-01-01 00:00:00'])); $builder->setModel($model); $this->assertEquals(['date_2010-01-01 00:00:00', 'date_2011-01-01 00:00:00'], $builder->pluck('created_at')->all()); @@ -905,17 +797,17 @@ public function testPluckReturnsTheDateAttributesOfAModel(): void public function testQualifiedPluckReturnsTheMutatedAttributesOfAModel(): void { - $model = m::mock(PluckStub::class)->makePartial(); - $model->shouldReceive('getKeyName')->andReturn('foo'); - $model->shouldReceive('getTable')->andReturn('foo_table'); - $model->shouldReceive('getQualifiedKeyName')->andReturn('foo_table.foo'); - $model->expects('qualifyColumn')->times(2)->with('name')->andReturn('foo_table.name'); - $model->expects('hasAnyGetMutator')->with('name')->andReturn(true); - $model->expects('newFromBuilder')->with(['name' => 'bar'])->andReturn(m::mock(PluckStub::class)->makePartial()->setRawAttributes(['name' => 'bar'])); - $model->expects('newFromBuilder')->with(['name' => 'baz'])->andReturn(m::mock(PluckStub::class)->makePartial()->setRawAttributes(['name' => 'baz'])); + $model = Double::for(new PluckStub)->passthru(); + $model->allows('getKeyName')->returns('foo'); + $model->allows('getTable')->returns('foo_table'); + $model->allows('getQualifiedKeyName')->returns('foo_table.foo'); + $model->expects('qualifyColumn')->times(2)->with('name')->returns('foo_table.name'); + $model->expects('hasAnyGetMutator')->with('name')->returns(true); + $model->expects('newFromBuilder')->with(['name' => 'bar'])->returns(Double::for(new PluckStub)->passthru()->setRawAttributes(['name' => 'bar'])); + $model->expects('newFromBuilder')->with(['name' => 'baz'])->returns(Double::for(new PluckStub)->passthru()->setRawAttributes(['name' => 'baz'])); $builder = $this->getBuilder(); - $builder->getQuery()->expects('pluck')->with($model->qualifyColumn('name'), '')->andReturn(new BaseCollection(['bar', 'baz'])); + $builder->getQuery()->expects('pluck')->with($model->qualifyColumn('name'), null)->returns(new BaseCollection(['bar', 'baz'])); $builder->setModel($model); $this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck($model->qualifyColumn('name'))->all()); @@ -923,18 +815,18 @@ public function testQualifiedPluckReturnsTheMutatedAttributesOfAModel(): void public function testQualifiedPluckReturnsTheCastedAttributesOfAModel(): void { - $model = m::mock(PluckStub::class)->makePartial(); - $model->shouldReceive('getKeyName')->andReturn('foo'); - $model->shouldReceive('getTable')->andReturn('foo_table'); - $model->shouldReceive('getQualifiedKeyName')->andReturn('foo_table.foo'); - $model->expects('qualifyColumn')->times(2)->with('name')->andReturn('foo_table.name'); - $model->expects('hasAnyGetMutator')->with('name')->andReturn(false); - $model->expects('hasCast')->with('name')->andReturn(true); - $model->expects('newFromBuilder')->with(['name' => 'bar'])->andReturn(m::mock(PluckStub::class)->makePartial()->setRawAttributes(['name' => 'bar'])); - $model->expects('newFromBuilder')->with(['name' => 'baz'])->andReturn(m::mock(PluckStub::class)->makePartial()->setRawAttributes(['name' => 'baz'])); + $model = Double::for(new PluckStub)->passthru(); + $model->allows('getKeyName')->returns('foo'); + $model->allows('getTable')->returns('foo_table'); + $model->allows('getQualifiedKeyName')->returns('foo_table.foo'); + $model->expects('qualifyColumn')->times(2)->with('name')->returns('foo_table.name'); + $model->expects('hasAnyGetMutator')->with('name')->returns(false); + $model->expects('hasCast')->with('name')->returns(true); + $model->expects('newFromBuilder')->with(['name' => 'bar'])->returns(Double::for(new PluckStub)->passthru()->setRawAttributes(['name' => 'bar'])); + $model->expects('newFromBuilder')->with(['name' => 'baz'])->returns(Double::for(new PluckStub)->passthru()->setRawAttributes(['name' => 'baz'])); $builder = $this->getBuilder(); - $builder->getQuery()->expects('pluck')->with($model->qualifyColumn('name'), '')->andReturn(new BaseCollection(['bar', 'baz'])); + $builder->getQuery()->expects('pluck')->with($model->qualifyColumn('name'), null)->returns(new BaseCollection(['bar', 'baz'])); $builder->setModel($model); $this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck($model->qualifyColumn('name'))->all()); @@ -942,19 +834,19 @@ public function testQualifiedPluckReturnsTheCastedAttributesOfAModel(): void public function testQualifiedPluckReturnsTheDateAttributesOfAModel(): void { - $model = m::mock(PluckDatesStub::class)->makePartial(); - $model->shouldReceive('getKeyName')->andReturn('foo'); - $model->shouldReceive('getTable')->andReturn('foo_table'); - $model->shouldReceive('getQualifiedKeyName')->andReturn('foo_table.foo'); - $model->expects('qualifyColumn')->times(2)->with('created_at')->andReturn('foo_table.created_at'); - $model->expects('hasAnyGetMutator')->with('created_at')->andReturn(false); - $model->expects('hasCast')->with('created_at')->andReturn(false); - $model->expects('getDates')->andReturn(['created_at']); - $model->expects('newFromBuilder')->with(['created_at' => '2010-01-01 00:00:00'])->andReturn(m::mock(PluckDatesStub::class)->makePartial()->setRawAttributes(['created_at' => '2010-01-01 00:00:00'])); - $model->expects('newFromBuilder')->with(['created_at' => '2011-01-01 00:00:00'])->andReturn(m::mock(PluckDatesStub::class)->makePartial()->setRawAttributes(['created_at' => '2011-01-01 00:00:00'])); + $model = Double::for(new PluckDatesStub)->passthru(); + $model->allows('getKeyName')->returns('foo'); + $model->allows('getTable')->returns('foo_table'); + $model->allows('getQualifiedKeyName')->returns('foo_table.foo'); + $model->expects('qualifyColumn')->times(2)->with('created_at')->returns('foo_table.created_at'); + $model->expects('hasAnyGetMutator')->with('created_at')->returns(false); + $model->expects('hasCast')->with('created_at')->returns(false); + $model->expects('getDates')->returns(['created_at']); + $model->expects('newFromBuilder')->with(['created_at' => '2010-01-01 00:00:00'])->returns(Double::for(new PluckDatesStub)->passthru()->setRawAttributes(['created_at' => '2010-01-01 00:00:00'])); + $model->expects('newFromBuilder')->with(['created_at' => '2011-01-01 00:00:00'])->returns(Double::for(new PluckDatesStub)->passthru()->setRawAttributes(['created_at' => '2011-01-01 00:00:00'])); $builder = $this->getBuilder(); - $builder->getQuery()->expects('pluck')->with($model->qualifyColumn('created_at'), '')->andReturn(new BaseCollection(['2010-01-01 00:00:00', '2011-01-01 00:00:00'])); + $builder->getQuery()->expects('pluck')->with($model->qualifyColumn('created_at'), null)->returns(new BaseCollection(['2010-01-01 00:00:00', '2011-01-01 00:00:00'])); $builder->setModel($model); $this->assertEquals(['date_2010-01-01 00:00:00', 'date_2011-01-01 00:00:00'], $builder->pluck($model->qualifyColumn('created_at'))->all()); @@ -963,11 +855,11 @@ public function testQualifiedPluckReturnsTheDateAttributesOfAModel(): void public function testPluckWithoutModelGetterJustReturnsTheAttributesFoundInDatabase(): void { $builder = $this->getBuilder(); - $builder->getQuery()->expects('pluck')->with('name', '')->andReturn(new BaseCollection(['bar', 'baz'])); + $builder->getQuery()->expects('pluck')->with('name', null)->returns(new BaseCollection(['bar', 'baz'])); $builder->setModel($this->getMockModel()); - $builder->getModel()->expects('hasAnyGetMutator')->with('name')->andReturn(false); - $builder->getModel()->expects('hasCast')->with('name')->andReturn(false); - $builder->getModel()->expects('getDates')->andReturn(['created_at']); + $builder->getModel()->expects('hasAnyGetMutator')->with('name')->returns(false); + $builder->getModel()->expects('hasCast')->with('name')->returns(false); + $builder->getModel()->expects('getDates')->returns(['created_at']); $this->assertEquals(['bar', 'baz'], $builder->pluck('name')->all()); } @@ -977,7 +869,7 @@ public function testLocalMacrosAreCalledOnBuilder(): void unset($_SERVER['__test.builder']); $builder = new Builder(new BaseBuilder( new PdoConnection(new PDO('sqlite::memory:')), - m::mock(Grammar::class), + Double::for(Grammar::class), new Processor )); $builder->macro('fooBar', function ($builder) { @@ -1028,20 +920,6 @@ public function testGetModelsProperlyHydratesModels(): void $this->assertSame(28, $models[1]->age); } - public function testEagerLoadRelationsLoadTopLevelRelationships(): void - { - $builder = m::mock(Builder::class . '[eagerLoadRelation]', [$this->getMockQueryBuilder()]); - $nop1 = function (): void { - }; - $nop2 = function (): void { - }; - $builder->setEagerLoads(['foo' => $nop1, 'foo.bar' => $nop2]); - $builder->shouldAllowMockingProtectedMethods()->expects('eagerLoadRelation')->with(['models'], 'foo', $nop1)->andReturn(['foo']); - - $results = $builder->eagerLoadRelations(['models']); - $this->assertEquals(['foo'], $results); - } - public function testEagerLoadRelationsCanBeFlushed(): void { $builder = new Builder($this->getMockQueryBuilder()); @@ -1057,17 +935,20 @@ public function testEagerLoadRelationsCanBeFlushed(): void public function testRelationshipEagerLoadProcess(): void { - $builder = m::mock(Builder::class . '[getRelation]', [$this->getMockQueryBuilder()]); - $builder->setEagerLoads(['orders' => function ($query) { - $_SERVER['__eloquent.constrain'] = $query; - }]); - $relation = m::mock(Relation::class); + $builder = Double::for(new Builder($this->getMockQueryBuilder()))->passthru(); + $builder->setEagerLoads([ + 'orders' => function ($query) { + $_SERVER['__eloquent.constrain'] = $query; + }, + 'orders.lines' => fn () => $this->fail('Nested relationships must load on their own query.'), + ]); + $relation = Double::for(Relation::class); $relation->expects('addEagerConstraints')->with(['models']); - $relation->expects('initRelation')->with(['models'], 'orders')->andReturn(['models']); + $relation->expects('initRelation')->with(['models'], 'orders')->returns(['models']); $eagerResults = new Collection(['results']); - $relation->expects('getEager')->andReturn($eagerResults); - $relation->expects('match')->with(['models'], $eagerResults, 'orders')->andReturn(['models.matched']); - $builder->expects('getRelation')->with('orders')->andReturn($relation); + $relation->expects('getEager')->returns($eagerResults); + $relation->expects('match')->with(['models'], $eagerResults, 'orders')->returns(['models.matched']); + $builder->expects('getRelation')->with('orders')->returns($relation); $results = $builder->eagerLoadRelations(['models']); $this->assertEquals(['models.matched'], $results); @@ -1077,71 +958,59 @@ public function testRelationshipEagerLoadProcess(): void public function testRelationshipEagerLoadProcessForImplicitlyEmpty(): void { - $queryBuilder = $this->getMockQueryBuilder(); - $builder = m::mock(Builder::class . '[getRelation]', [$queryBuilder]); - $builder->setEagerLoads(['parentFoo' => function ($query) { - $_SERVER['__eloquent.constrain'] = $query; - }]); $model = new ModelSelfRelatedStub; $this->mockConnectionForModel($model, 'SQLite'); + $constrained = null; $models = [ new ModelSelfRelatedStub, new ModelSelfRelatedStub, ]; - $relation = m::mock($model->parentFoo()); - $builder->expects('getRelation')->with('parentFoo')->andReturn($relation); + $model->newQuery()->with(['parentFoo' => function ($query) use (&$constrained) { + $constrained = $query; + }])->eagerLoadRelations($models); - $results = $builder->eagerLoadRelations($models); - - unset($_SERVER['__eloquent.constrain']); + $this->assertNotNull($constrained); + $this->assertTrue($models[0]->relationLoaded('parentFoo')); + $this->assertNull($models[0]->parentFoo); + $this->assertNull($models[1]->parentFoo); } public function testGetRelationProperlySetsNestedRelationships(): void { - $builder = $this->getBuilder(); - $builder->setModel($this->getMockModel()); - $relation = m::mock(Relation::class); - $builder->getModel()->expects('newInstance->orders')->andReturn($relation); - $relationQuery = m::mock(Builder::class); - $relation->expects('getQuery')->andReturn($relationQuery); - $relationQuery->expects('with')->with(['lines' => null, 'lines.details' => null]); - $builder->setEagerLoads(['orders' => null, 'orders.lines' => null, 'orders.lines.details' => null]); + $model = new ModelSelfRelatedStub; + $this->mockConnectionForModel($model, 'SQLite'); + $builder = $model->newQuery(); + $builder->setEagerLoads(['childFoos' => null, 'childFoos.parentFoo' => null, 'childFoos.parentFoo.childFoo' => null]); + + $relation = $builder->getRelation('childFoos'); - $builder->getRelation('orders'); + $this->assertSame(['parentFoo', 'parentFoo.childFoo'], array_keys($relation->getQuery()->getEagerLoads())); } public function testGetRelationProperlySetsNestedRelationshipsWithSimilarNames(): void { - $builder = $this->getBuilder(); - $builder->setModel($this->getMockModel()); - $relation = m::mock(Relation::class); - $groupsRelation = m::mock(Relation::class); - $builder->getModel()->expects('newInstance->orders')->andReturn($relation); - $builder->getModel()->expects('newInstance->ordersGroups')->andReturn($groupsRelation); - - $relationQuery = m::mock(Builder::class); - $relation->shouldReceive('getQuery')->andReturn($relationQuery); - - $groupRelationQuery = m::mock(Builder::class); - $groupsRelation->expects('getQuery')->andReturn($groupRelationQuery); - $groupRelationQuery->expects('with')->with(['lines' => null, 'lines.details' => null]); + $model = new ModelSelfRelatedStub; + $this->mockConnectionForModel($model, 'SQLite'); + $builder = $model->newQuery(); + $builder->setEagerLoads(['childFoo' => null, 'childFoos' => null, 'childFoos.parentFoo' => null, 'childFoos.parentFoo.childFoo' => null]); - $builder->setEagerLoads(['orders' => null, 'ordersGroups' => null, 'ordersGroups.lines' => null, 'ordersGroups.lines.details' => null]); + $relation = $builder->getRelation('childFoo'); + $groupsRelation = $builder->getRelation('childFoos'); - $builder->getRelation('orders'); - $builder->getRelation('ordersGroups'); + $this->assertSame([], array_keys($relation->getQuery()->getEagerLoads())); + $this->assertSame(['parentFoo', 'parentFoo.childFoo'], array_keys($groupsRelation->getQuery()->getEagerLoads())); } public function testGetRelationThrowsException(): void { $this->expectException(RelationNotFoundException::class); - $builder = $this->getBuilder(); - $builder->setModel($this->getMockModel()); + $model = new Stub; + $this->mockConnectionForModel($model, 'SQLite'); - $builder->getRelation('invalid'); + $model->newQuery()->getRelation('invalid'); } #[TestWith(['with'])] @@ -1238,45 +1107,45 @@ public function testEagerLoadParsingSetsProperRelationships(): void public function testQueryPassThru(): void { + BaseBuilder::macro('foobar', fn () => 'foo'); $builder = $this->getBuilder(); - $builder->getQuery()->expects('foobar')->andReturn('foo'); $this->assertInstanceOf(Builder::class, $builder->foobar()); $builder = $this->getBuilder(); - $builder->getQuery()->expects('insert')->with(['bar'])->andReturn(true); + $builder->getQuery()->expects('insert')->with(['bar'])->returns(true); $this->assertTrue($builder->insert(['bar'])); $builder = $this->getBuilder(); - $builder->getQuery()->expects('insertOrIgnore')->with(['bar'])->andReturn(1); + $builder->getQuery()->expects('insertOrIgnore')->with(['bar'])->returns(1); $this->assertSame(1, $builder->insertOrIgnore(['bar'])); $builder = $this->getBuilder(); $inserted = new BaseCollection([(object) ['baz' => 'foo']]); - $builder->getQuery()->expects('insertOrIgnoreReturning')->with(['bar'], ['baz'])->andReturn($inserted); + $builder->getQuery()->expects('insertOrIgnoreReturning')->with(['bar'], ['baz'])->returns($inserted); $this->assertSame($inserted, $builder->insertOrIgnoreReturning(['bar'], ['baz'])); $builder = $this->getBuilder(); - $builder->getQuery()->expects('insertOrIgnoreUsing')->with(['bar'], 'baz')->andReturn(1); + $builder->getQuery()->expects('insertOrIgnoreUsing')->with(['bar'], 'baz')->returns(1); $this->assertSame(1, $builder->insertOrIgnoreUsing(['bar'], 'baz')); $builder = $this->getBuilder(); - $builder->getQuery()->expects('insertGetId')->with(['bar'])->andReturn(123); + $builder->getQuery()->expects('insertGetId')->with(['bar'])->returns(123); $this->assertSame(123, $builder->insertGetId(['bar'])); $builder = $this->getBuilder(); - $builder->getQuery()->expects('insertUsing')->with(['bar'], 'baz')->andReturn(1); + $builder->getQuery()->expects('insertUsing')->with(['bar'], 'baz')->returns(1); $this->assertSame(1, $builder->insertUsing(['bar'], 'baz')); $builder = $this->getBuilder(); $expression = new Expression('foo'); - $builder->getQuery()->expects('raw')->with('bar')->andReturn($expression); + $builder->getQuery()->expects('raw')->with('bar')->returns($expression); $this->assertSame($expression, $builder->raw('bar')); } @@ -1434,27 +1303,6 @@ public function testApplyScopeCallbackWithoutWheresLeavesQueryUnchanged(): void $this->assertSame($bindings, $query->getBindings()); } - public function testNestedWhere(): void - { - $nestedQuery = m::mock(Builder::class); - $nestedRawQuery = $this->getMockQueryBuilder(); - $nestedQuery->expects('getQuery')->andReturn($nestedRawQuery); - $nestedQuery->expects('getEagerLoads')->andReturn([]); - $nestedQuery->expects('removedScopes')->andReturn([]); - $model = $this->getMockModel()->makePartial(); - $model->expects('newQueryWithoutRelationships')->andReturn($nestedQuery); - $builder = $this->getBuilder(); - $builder->getQuery()->shouldReceive('from'); - $builder->setModel($model); - $builder->getQuery()->expects('addNestedWhereQuery')->with($nestedRawQuery, 'and'); - $nestedQuery->expects('foo'); - - $result = $builder->where(function ($query) { - $query->foo(); - }); - $this->assertEquals($builder, $result); - } - public function testRealNestedWhereWithScopes(): void { $model = new NestedStub; @@ -1497,25 +1345,16 @@ public function testSimpleWhereNot(): void $this->assertEquals(['foo', 'bar'], $query->getBindings()); } - public function testWhereNot(): void + public function testWhereNotWithClosure(): void { - $nestedQuery = m::mock(Builder::class); - $nestedRawQuery = $this->getMockQueryBuilder(); - $nestedQuery->expects('getQuery')->andReturn($nestedRawQuery); - $nestedQuery->expects('getEagerLoads')->andReturn([]); - $nestedQuery->expects('removedScopes')->andReturn([]); - $model = $this->getMockModel()->makePartial(); - $model->expects('newQueryWithoutRelationships')->andReturn($nestedQuery); - $builder = $this->getBuilder(); - $builder->getQuery()->shouldReceive('from'); - $builder->setModel($model); - $builder->getQuery()->expects('addNestedWhereQuery')->with($nestedRawQuery, 'and not'); - $nestedQuery->expects('foo'); - - $result = $builder->whereNot(function ($query) { - $query->foo(); + $model = new Stub; + $this->mockConnectionForModel($model, 'SQLite'); + $query = $model->newQuery()->whereNot(function ($query) { + $query->where('baz', '>', 9000); }); - $this->assertEquals($builder, $result); + + $this->assertSame('select * from "table" where not ("baz" > ?)', $query->toSql()); + $this->assertEquals([9000], $query->getBindings()); } public function testSimpleOrWhereNot(): void @@ -1545,25 +1384,16 @@ public function testWhereNotWithArrayConditions(): void $this->assertEquals([3, 1, 2], $query->getBindings()); } - public function testOrWhereNot(): void + public function testOrWhereNotWithClosure(): void { - $nestedQuery = m::mock(Builder::class); - $nestedRawQuery = $this->getMockQueryBuilder(); - $nestedQuery->expects('getQuery')->andReturn($nestedRawQuery); - $nestedQuery->expects('getEagerLoads')->andReturn([]); - $nestedQuery->expects('removedScopes')->andReturn([]); - $model = $this->getMockModel()->makePartial(); - $model->expects('newQueryWithoutRelationships')->andReturn($nestedQuery); - $builder = $this->getBuilder(); - $builder->getQuery()->shouldReceive('from'); - $builder->setModel($model); - $builder->getQuery()->expects('addNestedWhereQuery')->with($nestedRawQuery, 'or not'); - $nestedQuery->expects('foo'); - - $result = $builder->orWhereNot(function ($query) { - $query->foo(); + $model = new Stub; + $this->mockConnectionForModel($model, 'SQLite'); + $query = $model->newQuery()->where('foo', 'bar')->orWhereNot(function ($query) { + $query->where('baz', '>', 9000); }); - $this->assertEquals($builder, $result); + + $this->assertSame('select * from "table" where "foo" = ? or not ("baz" > ?)', $query->toSql()); + $this->assertEquals(['bar', 9000], $query->getBindings()); } public function testQueryableWhereForwardersAcceptBuilderAndRelationSubqueries(): void @@ -1594,13 +1424,13 @@ public function testFirstWhereAcceptsRelationSubquery(): void $model = new ModelParentStub; $model->foo_id = 7; $connection = $this->mockConnectionForModel($model, 'SQLite'); - $connection->shouldReceive('getWritableName')->andReturn('database'); + $connection->allows('getWritableName')->returns('database'); $connection->expects('select')->with( 'select * from "model_parent_stubs" where (select * from "model_close_related_stubs" where "model_close_related_stubs"."id" = ?) > ? limit 1', [7, 5], true, [], - )->andReturn([['id' => 11]]); + )->returns([['id' => 11]]); $result = $model->newQuery()->firstWhere($model->foo(), '>', 5); @@ -1678,7 +1508,7 @@ public function testWhereBelongsTo(): void ]); $builder = $this->getBuilder(); - $builder->shouldReceive('from')->with('where_belongs_to_stubs'); + $builder->allows('from')->with('where_belongs_to_stubs'); $builder->setModel($related); $builder->getQuery()->expects('whereIn')->with('where_belongs_to_stubs.parent_id', [2], 'and'); @@ -1686,7 +1516,7 @@ public function testWhereBelongsTo(): void $this->assertEquals($result, $builder); $builder = $this->getBuilder(); - $builder->shouldReceive('from')->with('where_belongs_to_stubs'); + $builder->allows('from')->with('where_belongs_to_stubs'); $builder->setModel($related); $builder->getQuery()->expects('whereIn')->with('where_belongs_to_stubs.parent_id', [2], 'and'); @@ -1702,7 +1532,7 @@ public function testWhereBelongsTo(): void ])]); $builder = $this->getBuilder(); - $builder->shouldReceive('from')->with('where_belongs_to_stubs'); + $builder->allows('from')->with('where_belongs_to_stubs'); $builder->setModel($related); $builder->getQuery()->expects('whereIn')->with('where_belongs_to_stubs.parent_id', [2, 3], 'and'); @@ -1710,7 +1540,7 @@ public function testWhereBelongsTo(): void $this->assertEquals($result, $builder); $builder = $this->getBuilder(); - $builder->shouldReceive('from')->with('where_belongs_to_stubs'); + $builder->allows('from')->with('where_belongs_to_stubs'); $builder->setModel($related); $builder->getQuery()->expects('whereIn')->with('where_belongs_to_stubs.parent_id', [2, 3], 'and'); @@ -2247,7 +2077,7 @@ public function testHasNestedWithMorphTo(ExpressionContract|int $count): void $morphToKey = $model->morph()->getMorphType(); - $connection->expects('select')->andReturn([ + $connection->expects('select')->returns([ [$morphToKey => ModelFarRelatedStub::class], [$morphToKey => ModelOtherFarRelatedStub::class], ]); @@ -2276,7 +2106,7 @@ public function testHasNestedWithMorphToAndMultipleSubRelations(ExpressionContra $morphToKey = $model->morph()->getMorphType(); - $connection->expects('select')->andReturn([ + $connection->expects('select')->returns([ [$morphToKey => ModelFarRelatedStub::class], [$morphToKey => ModelOtherFarRelatedStub::class], ]); @@ -2315,7 +2145,7 @@ public function testHasNestedWithMorphToAfterFirstRelation(): void $model = new ModelParentStub; $connection = $this->mockConnectionForModel($model, ''); - $connection->expects('select')->andReturn([ + $connection->expects('select')->returns([ ['morph_type' => ModelFarRelatedStub::class], ['morph_type' => ModelOtherFarRelatedStub::class], ]); @@ -2333,8 +2163,8 @@ public function testHasNestedWithMorphToAfterFirstRelation(): void public function testHasWithCustomCountExpression(): void { - $count = m::mock(ExpressionContract::class); - $count->shouldReceive('getValue')->andReturn('model_parent_stubs.required_count'); + $count = Double::for(ExpressionContract::class); + $count->allows('getValue')->returns('model_parent_stubs.required_count'); $query = (new ModelParentStub)->whereHas('foo', static function (Builder $query): void { $query->where('active', true); @@ -2945,7 +2775,7 @@ public function testWhereKeyMethodWithInt(): void $int = 1; - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->getQuery()->expects('where')->with($keyName, '=', $int, 'and'); $builder->whereKey($int); @@ -2970,39 +2800,20 @@ public function testWhereKeyMethodWithStringNull(): void $builder = $this->getBuilder()->setModel($model); $keyName = $model->getQualifiedKeyName(); - $builder->getQuery()->expects('where')->with($keyName, '=', m::on(function (mixed $argument): bool { + $builder->getQuery()->expects('where')->with($keyName, '=', Argument::satisfies(function (mixed $argument): bool { return $argument === null; }), 'and'); $builder->whereKey(null); } - public function testWhereKeyMethodWithArray(): void + public function testWhereKeyMethodWithArrayAndCollection(): void { - $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); - $builder = $this->getBuilder()->setModel($model); - $keyName = $model->getQualifiedKeyName(); - - $array = [1, 2, 3]; - - $builder->getQuery()->expects('whereIntegerInRaw')->with($keyName, $array, 'and', false); - - $builder->whereKey($array); - } - - public function testWhereKeyMethodWithCollection(): void - { - $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); - $builder = $this->getBuilder()->setModel($model); - $keyName = $model->getQualifiedKeyName(); - - $collection = new Collection([1, 2, 3]); - - $builder->getQuery()->expects('whereIntegerInRaw')->with($keyName, $collection, 'and', false); + $model = new Stub; + $this->mockConnectionForModel($model, 'SQLite'); - $builder->whereKey($collection); + $this->assertSame('select * from "table" where "table"."id" in (1, 2, 3)', $model->newQuery()->whereKey([1, 2, 3])->toSql()); + $this->assertSame('select * from "table" where "table"."id" in (1, 2, 3)', $model->newQuery()->whereKey(new Collection([1, 2, 3]))->toSql()); } public function testWhereKeyMethodWithClosure(): void @@ -3036,7 +2847,7 @@ public function testWhereKeyMethodWithModel(): void $builder = $this->getBuilder()->setModel($model); $keyName = $model->getQualifiedKeyName(); - $builder->getQuery()->expects('where')->with($keyName, '=', m::on(function (mixed $argument): bool { + $builder->getQuery()->expects('where')->with($keyName, '=', Argument::satisfies(function (mixed $argument): bool { return $argument === '1'; }), 'and'); @@ -3091,7 +2902,7 @@ public function testWhereKeyNotMethodWithStringNull(): void $builder = $this->getBuilder()->setModel($model); $keyName = $model->getQualifiedKeyName(); - $builder->getQuery()->expects('where')->with($keyName, '!=', m::on(function (mixed $argument): bool { + $builder->getQuery()->expects('where')->with($keyName, '!=', Argument::satisfies(function (mixed $argument): bool { return $argument === null; }), 'and'); @@ -3106,38 +2917,19 @@ public function testWhereKeyNotMethodWithInt(): void $int = 1; - $model->expects('getKeyType')->andReturn('int'); + $model->expects('getKeyType')->returns('int'); $builder->getQuery()->expects('where')->with($keyName, '!=', $int, 'and'); $builder->whereKeyNot($int); } - public function testWhereKeyNotMethodWithArray(): void + public function testWhereKeyNotMethodWithArrayAndCollection(): void { - $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); - $builder = $this->getBuilder()->setModel($model); - $keyName = $model->getQualifiedKeyName(); - - $array = [1, 2, 3]; - - $builder->getQuery()->expects('whereIntegerInRaw')->with($keyName, $array, 'and', true); - - $builder->whereKeyNot($array); - } - - public function testWhereKeyNotMethodWithCollection(): void - { - $model = $this->getMockModel(); - $model->expects('getKeyType')->andReturn('int'); - $builder = $this->getBuilder()->setModel($model); - $keyName = $model->getQualifiedKeyName(); - - $collection = new Collection([1, 2, 3]); - - $builder->getQuery()->expects('whereIntegerInRaw')->with($keyName, $collection, 'and', true); + $model = new Stub; + $this->mockConnectionForModel($model, 'SQLite'); - $builder->whereKeyNot($collection); + $this->assertSame('select * from "table" where "table"."id" not in (1, 2, 3)', $model->newQuery()->whereKeyNot([1, 2, 3])->toSql()); + $this->assertSame('select * from "table" where "table"."id" not in (1, 2, 3)', $model->newQuery()->whereKeyNot(new Collection([1, 2, 3]))->toSql()); } public function testWhereKeyNotMethodWithSubquery(): void @@ -3158,7 +2950,7 @@ public function testWhereKeyNotMethodWithModel(): void $builder = $this->getBuilder()->setModel($model); $keyName = $model->getQualifiedKeyName(); - $builder->getQuery()->expects('where')->with($keyName, '!=', m::on(function (mixed $argument): bool { + $builder->getQuery()->expects('where')->with($keyName, '!=', Argument::satisfies(function (mixed $argument): bool { return $argument === '1'; }), 'and'); @@ -3277,7 +3069,7 @@ public function testExceptMethodWithModel(): void $builder = $this->getBuilder()->setModel($model); $keyName = $model->getQualifiedKeyName(); - $builder->getQuery()->expects('where')->with($keyName, '!=', m::on(function (mixed $argument): bool { + $builder->getQuery()->expects('where')->with($keyName, '!=', Argument::satisfies(function (mixed $argument): bool { return $argument === '1'; }), 'and'); @@ -3292,7 +3084,7 @@ public function testExceptMethodWithCollectionOfModel(): void $builder = $this->getBuilder()->setModel($model); $keyName = $model->getQualifiedKeyName(); - $builder->getQuery()->expects('whereIn')->with($keyName, m::on(function (mixed $argument): bool { + $builder->getQuery()->expects('whereIn')->with($keyName, Argument::satisfies(function (mixed $argument): bool { return $argument === [1, 2]; }), 'and', true); @@ -3314,7 +3106,7 @@ public function testExceptMethodWithArrayOfModel(): void $builder = $this->getBuilder()->setModel($model); $keyName = $model->getQualifiedKeyName(); - $builder->getQuery()->expects('whereIn')->with($keyName, m::on(function (mixed $argument): bool { + $builder->getQuery()->expects('whereIn')->with($keyName, Argument::satisfies(function (mixed $argument): bool { return $argument === [1, 2]; }), 'and', true); @@ -3342,7 +3134,7 @@ public function testWhereIn(): void public function testLatestWithoutColumnWithCreatedAt(): void { $model = $this->getMockModel(); - $model->expects('getCreatedAtColumn')->andReturn('foo'); + $model->expects('getCreatedAtColumn')->returns('foo'); $builder = $this->getBuilder()->setModel($model); $builder->getQuery()->expects('latest')->with('foo'); @@ -3353,7 +3145,7 @@ public function testLatestWithoutColumnWithCreatedAt(): void public function testLatestWithoutColumnWithoutCreatedAt(): void { $model = $this->getMockModel(); - $model->expects('getCreatedAtColumn')->andReturn(null); + $model->expects('getCreatedAtColumn')->returns(null); $builder = $this->getBuilder()->setModel($model); $builder->getQuery()->expects('latest')->with('created_at'); @@ -3400,7 +3192,7 @@ public function testLatestAndOldestAcceptQueryableSubqueries(): void public function testOldestWithoutColumnWithCreatedAt(): void { $model = $this->getMockModel(); - $model->expects('getCreatedAtColumn')->andReturn('foo'); + $model->expects('getCreatedAtColumn')->returns('foo'); $builder = $this->getBuilder()->setModel($model); $builder->getQuery()->expects('oldest')->with('foo'); @@ -3411,7 +3203,7 @@ public function testOldestWithoutColumnWithCreatedAt(): void public function testOldestWithoutColumnWithoutCreatedAt(): void { $model = $this->getMockModel(); - $model->expects('getCreatedAtColumn')->andReturn(null); + $model->expects('getCreatedAtColumn')->returns(null); $builder = $this->getBuilder()->setModel($model); $builder->getQuery()->expects('oldest')->with('created_at'); @@ -3433,15 +3225,15 @@ public function testUpdate(): void { CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10'); - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); $query = new BaseBuilder($connection, new Grammar($connection), new Processor); $builder = new Builder($query); $model = new Stub; $this->mockConnectionForModel($model, ''); $builder->setModel($model); $builder->getConnection()->expects('update') - ->with('update "table" set "foo" = ?, "table"."updated_at" = ?', ['bar', $now])->andReturn(1); + ->with('update "table" set "foo" = ?, "table"."updated_at" = ?', ['bar', $now])->returns(1); $result = $builder->update(['foo' => 'bar']); $this->assertEquals(1, $result); @@ -3449,15 +3241,15 @@ public function testUpdate(): void public function testUpdateWithTimestampValue(): void { - $connection = m::mock(Connection::class); - $connection->expects('getTablePrefix')->times(2)->andReturn(''); + $connection = Double::for(Connection::class); + $connection->expects('getTablePrefix')->times(2)->returns(''); $query = new BaseBuilder($connection, new Grammar($connection), new Processor); $builder = new Builder($query); $model = new Stub; $this->mockConnectionForModel($model, ''); $builder->setModel($model); $builder->getConnection()->expects('update') - ->with('update "table" set "foo" = ?, "table"."updated_at" = ?', ['bar', null])->andReturn(1); + ->with('update "table" set "foo" = ?, "table"."updated_at" = ?', ['bar', null])->returns(1); $result = $builder->update(['foo' => 'bar', 'updated_at' => null]); $this->assertEquals(1, $result); @@ -3465,15 +3257,15 @@ public function testUpdateWithTimestampValue(): void public function testUpdateWithQualifiedTimestampValue(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); $query = new BaseBuilder($connection, new Grammar($connection), new Processor); $builder = new Builder($query); $model = new Stub; $this->mockConnectionForModel($model, ''); $builder->setModel($model); $builder->getConnection()->expects('update') - ->with('update "table" set "table"."foo" = ?, "table"."updated_at" = ?', ['bar', null])->andReturn(1); + ->with('update "table" set "table"."foo" = ?, "table"."updated_at" = ?', ['bar', null])->returns(1); $result = $builder->update(['table.foo' => 'bar', 'table.updated_at' => null]); $this->assertEquals(1, $result); @@ -3481,15 +3273,15 @@ public function testUpdateWithQualifiedTimestampValue(): void public function testUpdateWithoutTimestamp(): void { - $connection = m::mock(Connection::class); - $connection->expects('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->expects('getTablePrefix')->returns(''); $query = new BaseBuilder($connection, new Grammar($connection), new Processor); $builder = new Builder($query); $model = new StubWithoutTimestamp; $this->mockConnectionForModel($model, ''); $builder->setModel($model); $builder->getConnection()->expects('update') - ->with('update "table" set "foo" = ?', ['bar'])->andReturn(1); + ->with('update "table" set "foo" = ?', ['bar'])->returns(1); $result = $builder->update(['foo' => 'bar']); $this->assertEquals(1, $result); @@ -3499,15 +3291,15 @@ public function testUpdateWithAlias(): void { CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10'); - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); $query = new BaseBuilder($connection, new Grammar($connection), new Processor); $builder = new Builder($query); $model = new Stub; $this->mockConnectionForModel($model, ''); $builder->setModel($model); $builder->getConnection()->expects('update') - ->with('update "table" as "alias" set "foo" = ?, "alias"."updated_at" = ?', ['bar', $now])->andReturn(1); + ->with('update "table" as "alias" set "foo" = ?, "alias"."updated_at" = ?', ['bar', $now])->returns(1); $result = $builder->from('table as alias')->update(['foo' => 'bar']); $this->assertEquals(1, $result); @@ -3517,15 +3309,15 @@ public function testUpdateWithAliasWithQualifiedTimestampValue(): void { CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10'); - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); $query = new BaseBuilder($connection, new Grammar($connection), new Processor); $builder = new Builder($query); $model = new Stub; $this->mockConnectionForModel($model, ''); $builder->setModel($model); $builder->getConnection()->expects('update') - ->with('update "table" as "alias" set "foo" = ?, "alias"."updated_at" = ?', ['bar', null])->andReturn(1); + ->with('update "table" as "alias" set "foo" = ?, "alias"."updated_at" = ?', ['bar', null])->returns(1); $result = $builder->from('table as alias')->update(['foo' => 'bar', 'alias.updated_at' => null]); $this->assertEquals(1, $result); @@ -3535,13 +3327,14 @@ public function testUpdateWithAnExplicitRawSourceAliasAndPrefix(): void { CarbonImmutable::setTestNow('2017-10-10 10:10:10'); - $connection = m::mock(Connection::class, ['getTablePrefix' => 'prefix_']); - $query = new BaseBuilder($connection, new MySqlGrammar($connection), m::mock(Processor::class)); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns('prefix_'); + $query = new BaseBuilder($connection, new MySqlGrammar($connection), Double::for(Processor::class)); $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` = ?', ['new', '2017-10-10 10:10:10'], - )->andReturn(1); + )->returns(1); $builder->from(new Expression('`prefix_table`'), 'target') ->join('profiles', 'profiles.user_id', '=', 'target.id'); @@ -3554,7 +3347,7 @@ public function testUpdateOrInsertReturnsTheQueryResult(): void { $builder = $this->getBuilder(); $builder->getQuery()->expects('updateOrInsert') - ->with(['email' => 'user@example.com'], ['name' => 'Taylor'])->andReturn(false); + ->with(['email' => 'user@example.com'], ['name' => 'Taylor'])->returns(false); $this->assertFalse($builder->updateOrInsert(['email' => 'user@example.com'], ['name' => 'Taylor'])); } @@ -3578,7 +3371,7 @@ public function testUpdateFromAppliesScopesAndModelTimestamps(bool $timestamps, $model = new Stub; $model->timestamps = $timestamps; $connection = $this->mockConnectionForModel($model, 'Postgres'); - $connection->expects('update')->with($sql, $bindings)->andReturn(2); + $connection->expects('update')->with($sql, $bindings)->returns(2); $builder = $model->newQuery() ->withGlobalScope('active', fn (Builder $query): Builder => $query->where('table.active', 1)) @@ -3622,7 +3415,7 @@ public function testUpdateFromWithAnOpaqueRawSourcePreservesSuppliedValues(array $connection->expects('update')->with( 'update "table" as "target" set ' . $columns . ' from "profiles" where "profiles"."user_id" = "target"."id"', $bindings, - )->andReturn(1); + )->returns(1); $builder = $model->newQuery()->fromRaw('"table" as "target"') ->join('profiles', 'profiles.user_id', '=', 'target.id'); @@ -3644,7 +3437,7 @@ public static function rawSourceUpdateValues(): array public function testGetColumnsReturnsTheQueryColumns(): void { $builder = $this->getBuilder(); - $builder->getQuery()->expects('getColumns')->andReturn(['name']); + $builder->getQuery()->expects('getColumns')->returns(['name']); $this->assertSame(['name'], $builder->getColumns()); } @@ -3653,7 +3446,7 @@ public function testGetProcessorReturnsTheQueryProcessor(): void { $builder = $this->getBuilder(); $processor = new Processor; - $builder->getQuery()->expects('getProcessor')->andReturn($processor); + $builder->getQuery()->expects('getProcessor')->returns($processor); $this->assertSame($processor, $builder->getProcessor()); } @@ -3662,8 +3455,8 @@ public function testUpsert(): void { CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10'); - $query = m::mock(BaseBuilder::class); - $query->expects('from')->with('foo_table')->andReturnSelf(); + $query = Double::for(BaseBuilder::class); + $query->expects('from')->with('foo_table')->returns($query); $query->from = 'foo_table'; $builder = new Builder($query); @@ -3672,9 +3465,9 @@ public function testUpsert(): void $query->expects('upsert') ->with([ - ['email' => 'foo', 'name' => 'bar', 'updated_at' => $now, 'created_at' => $now], - ['name' => 'bar2', 'email' => 'foo2', 'updated_at' => $now, 'created_at' => $now], - ], ['email'], ['email', 'name', 'updated_at'])->andReturn(2); + ['updated_at' => $now, 'created_at' => $now, 'email' => 'foo', 'name' => 'bar'], + ['updated_at' => $now, 'created_at' => $now, 'name' => 'bar2', 'email' => 'foo2'], + ], ['email'], ['email', 'name', 'updated_at'])->returns(2); $result = $builder->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], ['email']); @@ -3686,16 +3479,16 @@ public function testUpsertAddsUpdatedAtUnlessTheUpdateAlreadySetsIt(array $updat { CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10'); - $query = m::mock(BaseBuilder::class); - $query->expects('from')->with('foo_table')->andReturnSelf(); + $query = Double::for(BaseBuilder::class); + $query->expects('from')->with('foo_table')->returns($query); $query->from = 'foo_table'; $builder = new Builder($query); $builder->setModel(new StubStringPrimaryKey); $query->expects('upsert') - ->with([['email' => 'foo', 'updated_at' => $now, 'created_at' => $now]], ['email'], $expected) - ->andReturn(1); + ->with([['updated_at' => $now, 'created_at' => $now, 'email' => 'foo']], ['email'], $expected) + ->returns(1); $this->assertSame(1, $builder->upsert([['email' => 'foo']], ['email'], $update)); } @@ -3715,17 +3508,17 @@ public static function upsertUpdateColumnsProvider(): array public function testTouch(): void { - CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10'); + CarbonImmutable::setTestNow('2017-10-10 10:10:10'); - $query = m::mock(BaseBuilder::class); - $query->expects('from')->with('foo_table')->andReturnSelf(); + $query = Double::for(BaseBuilder::class); + $query->expects('from')->with('foo_table')->returns($query); $query->from = 'foo_table'; $builder = new Builder($query); $model = new StubStringPrimaryKey; $builder->setModel($model); - $query->expects('update')->with(['updated_at' => $now])->andReturn(2); + $query->expects('update')->with(['updated_at' => CarbonImmutable::now()])->returns(2); $result = $builder->touch(); @@ -3734,17 +3527,17 @@ public function testTouch(): void public function testTouchWithCustomColumn(): void { - CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10'); + CarbonImmutable::setTestNow('2017-10-10 10:10:10'); - $query = m::mock(BaseBuilder::class); - $query->expects('from')->with('foo_table')->andReturnSelf(); + $query = Double::for(BaseBuilder::class); + $query->expects('from')->with('foo_table')->returns($query); $query->from = 'foo_table'; $builder = new Builder($query); $model = new StubStringPrimaryKey; $builder->setModel($model); - $query->expects('update')->with(['published_at' => $now])->andReturn(2); + $query->expects('update')->with(['published_at' => CarbonImmutable::now()])->returns(2); $result = $builder->touch('published_at'); @@ -3753,10 +3546,10 @@ public function testTouchWithCustomColumn(): void public function testTouchWithMultipleColumns(): void { - CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10'); + CarbonImmutable::setTestNow('2017-10-10 10:10:10'); - $query = m::mock(BaseBuilder::class); - $query->expects('from')->with('foo_table')->andReturnSelf(); + $query = Double::for(BaseBuilder::class); + $query->expects('from')->with('foo_table')->returns($query); $query->from = 'foo_table'; $builder = new Builder($query); @@ -3764,8 +3557,8 @@ public function testTouchWithMultipleColumns(): void $builder->setModel($model); $query->expects('update') - ->with(['published_at' => $now, 'verified_at' => $now]) - ->andReturn(2); + ->with(['published_at' => CarbonImmutable::now(), 'verified_at' => CarbonImmutable::now()]) + ->returns(2); $result = $builder->touch(['published_at', 'verified_at']); @@ -3774,15 +3567,15 @@ public function testTouchWithMultipleColumns(): void public function testTouchWithoutUpdatedAtColumn(): void { - $query = m::mock(BaseBuilder::class); - $query->expects('from')->with('table')->andReturnSelf(); + $query = Double::for(BaseBuilder::class); + $query->expects('from')->with('table')->returns($query); $query->from = 'table'; $builder = new Builder($query); $model = new StubWithoutTimestamp; $builder->setModel($model); - $query->shouldNotReceive('update'); + $query->expects('update')->never(); $result = $builder->touch(); @@ -3791,8 +3584,8 @@ public function testTouchWithoutUpdatedAtColumn(): void public function testClone(): void { - $connection = m::mock(Connection::class); - $connection->expects('getTablePrefix')->times(2)->andReturn(''); + $connection = Double::for(Connection::class); + $connection->expects('getTablePrefix')->times(2)->returns(''); $query = new BaseBuilder($connection, new Grammar($connection), new Processor); $builder = new Builder($query); $builder->select('*')->from('users'); @@ -3862,8 +3655,8 @@ public function testNewQueryRestoresTheModelDefaults(): void public function testCloneModelMakesAFreshCopyOfTheModel(): void { - $connection = m::mock(Connection::class); - $connection->expects('getTablePrefix')->times(2)->andReturn(''); + $connection = Double::for(Connection::class); + $connection->expects('getTablePrefix')->times(2)->returns(''); $query = new BaseBuilder($connection, new Grammar($connection), new Processor); $builder = (new Builder($query))->setModel(new Stub); $builder->select('*')->from('users'); @@ -3890,9 +3683,9 @@ public function testCloneModelMakesAFreshCopyOfTheModel(): void public function testToRawSql(): void { - $query = m::mock(BaseBuilder::class); + $query = Double::for(BaseBuilder::class); $query->expects('toRawSql') - ->andReturn('select * from "users" where "email" = \'foo\''); + ->returns('select * from "users" where "email" = \'foo\''); $builder = new Builder($query); @@ -3901,12 +3694,12 @@ public function testToRawSql(): void public function testPassthruMethodsCallsAreNotCaseSensitive(): void { - $query = m::mock(BaseBuilder::class); + $query = Double::for(BaseBuilder::class); $mockResponse = 'select 1'; $query ->expects('toRawSql') - ->andReturn($mockResponse) + ->returns($mockResponse) ->times(3); $builder = new Builder($query); @@ -3918,7 +3711,7 @@ public function testPassthruMethodsCallsAreNotCaseSensitive(): void public function testPassthruArrayElementsMustAllBeLowercase(): void { - $builder = new class(m::mock(BaseBuilder::class)) extends Builder { + $builder = new class(Double::for(BaseBuilder::class)) extends Builder { // expose protected member for test public function getPassthru(): array { @@ -3966,22 +3759,22 @@ public function testPipeCallback(): void public function testIncrementEachCallsToBaseWithUpdatedAt(): void { - $query = m::mock(BaseBuilder::class); + $query = Double::for(BaseBuilder::class); $query->expects('from')->with('foo_table'); - $query->expects('getFromAlias')->andReturn('foo_table'); - $query->expects('incrementEach')->withArgs(function (array $columns, array $extra): bool { + $query->expects('getFromAlias')->returns('foo_table'); + $query->expects('incrementEach')->with(Argument::all(function (array $columns, array $extra): bool { return $columns === ['votes' => 5] && array_key_exists('foo_table.updated_at', $extra); - })->andReturn(1); + }))->returns(1); $builder = new Builder($query); $model = $this->getMockModel(); - $model->expects('usesTimestamps')->andReturn(true); - $model->expects('getUpdatedAtColumn')->times(2)->andReturn('updated_at'); - $model->expects('freshTimestampString')->andReturn('2026-03-26 00:00:00'); - $model->expects('hasSetMutator')->andReturn(false); - $model->expects('hasAttributeSetMutator')->andReturn(false); - $model->expects('hasCast')->andReturn(false); + $model->expects('usesTimestamps')->returns(true); + $model->expects('getUpdatedAtColumn')->times(2)->returns('updated_at'); + $model->expects('freshTimestampString')->returns('2026-03-26 00:00:00'); + $model->expects('hasSetMutator')->returns(false); + $model->expects('hasAttributeSetMutator')->returns(false); + $model->expects('hasCast')->returns(false); $builder->setModel($model); $result = $builder->incrementEach(['votes' => 5]); @@ -3991,22 +3784,22 @@ public function testIncrementEachCallsToBaseWithUpdatedAt(): void public function testDecrementEachCallsToBaseWithUpdatedAt(): void { - $query = m::mock(BaseBuilder::class); + $query = Double::for(BaseBuilder::class); $query->expects('from')->with('foo_table'); - $query->expects('getFromAlias')->andReturn('foo_table'); - $query->expects('decrementEach')->withArgs(function (array $columns, array $extra): bool { + $query->expects('getFromAlias')->returns('foo_table'); + $query->expects('decrementEach')->with(Argument::all(function (array $columns, array $extra): bool { return $columns === ['votes' => 3] && array_key_exists('foo_table.updated_at', $extra); - })->andReturn(1); + }))->returns(1); $builder = new Builder($query); $model = $this->getMockModel(); - $model->expects('usesTimestamps')->andReturn(true); - $model->expects('getUpdatedAtColumn')->times(2)->andReturn('updated_at'); - $model->expects('freshTimestampString')->andReturn('2026-03-26 00:00:00'); - $model->expects('hasSetMutator')->andReturn(false); - $model->expects('hasAttributeSetMutator')->andReturn(false); - $model->expects('hasCast')->andReturn(false); + $model->expects('usesTimestamps')->returns(true); + $model->expects('getUpdatedAtColumn')->times(2)->returns('updated_at'); + $model->expects('freshTimestampString')->returns('2026-03-26 00:00:00'); + $model->expects('hasSetMutator')->returns(false); + $model->expects('hasAttributeSetMutator')->returns(false); + $model->expects('hasCast')->returns(false); $builder->setModel($model); $result = $builder->decrementEach(['votes' => 3]); @@ -4016,13 +3809,13 @@ public function testDecrementEachCallsToBaseWithUpdatedAt(): void public function testIncrementEachWithoutTimestamps(): void { - $query = m::mock(BaseBuilder::class); + $query = Double::for(BaseBuilder::class); $query->expects('from')->with('foo_table'); - $query->expects('incrementEach')->with(['votes' => 1], [])->andReturn(1); + $query->expects('incrementEach')->with(['votes' => 1], [])->returns(1); $builder = new Builder($query); $model = $this->getMockModel(); - $model->expects('usesTimestamps')->andReturn(false); + $model->expects('usesTimestamps')->returns(false); $builder->setModel($model); $result = $builder->incrementEach(['votes' => 1]); @@ -4053,37 +3846,48 @@ protected function assertRelationshipConstraintTimeoutRejected(Closure $accept): $this->assertSame($bindings, $builder->getBindings()); } - protected function mockConnectionForModel($model, $database) + /** + * Bind a controlled connection for the model. + */ + protected function mockConnectionForModel(Model $model, string $database): Connection { $grammarClass = 'Hypervel\Database\Query\Grammars\\' . $database . 'Grammar'; $processorClass = 'Hypervel\Database\Query\Processors\\' . $database . 'Processor'; $processor = new $processorClass; - $connection = m::mock(Connection::class, ['getPostProcessor' => $processor]); + $connection = Double::for(Connection::class); + $connection->allows('getPostProcessor')->returns($processor); $grammar = new $grammarClass($connection); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor) { + $connection->allows('getQueryGrammar')->returns($grammar); + $connection->allows('getTablePrefix')->returns(''); + $connection->allows('query')->resolves(function () use ($connection, $grammar, $processor) { return new BaseBuilder($connection, $grammar, $processor); }); - $connection->shouldReceive('getDatabaseName')->andReturn('database'); - $resolver = m::mock(ConnectionResolverInterface::class, ['connection' => $connection]); + $connection->allows('getDatabaseName')->returns('database'); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->returns($connection); $class = get_class($model); $class::setConnectionResolver($resolver); return $connection; } - protected function getBuilder() + /** + * Create a builder with a controlled base query. + */ + protected function getBuilder(): Builder { return new Builder($this->getMockQueryBuilder()); } - protected function getMockModel() + /** + * Create a model double with the query metadata. + */ + protected function getMockModel(): Model { - $model = m::mock(Model::class); - $model->shouldReceive('getKeyName')->andReturn('foo'); - $model->shouldReceive('getTable')->andReturn('foo_table'); - $model->shouldReceive('getQualifiedKeyName')->andReturn('foo_table.foo'); + $model = Double::for(Model::class); + $model->allows('getKeyName')->returns('foo'); + $model->allows('getTable')->returns('foo_table'); + $model->allows('getQualifiedKeyName')->returns('foo_table.foo'); return $model; } @@ -4167,10 +3971,13 @@ protected function newBuilder(SQLiteConnection $connection): Builder return (new Builder($connection->query()))->setModel(new Stub); } - protected function getMockQueryBuilder() + /** + * Create a base query double. + */ + protected function getMockQueryBuilder(): BaseBuilder { - $query = m::mock(BaseBuilder::class); - $query->shouldReceive('from')->with('foo_table'); + $query = Double::for(BaseBuilder::class); + $query->allows('from')->with('foo_table'); return $query; } diff --git a/tests/Database/DatabaseEloquentCollectionQueueableTest.php b/tests/Database/DatabaseEloquentCollectionQueueableTest.php index f76bb39ac..5d951a0d3 100644 --- a/tests/Database/DatabaseEloquentCollectionQueueableTest.php +++ b/tests/Database/DatabaseEloquentCollectionQueueableTest.php @@ -4,20 +4,23 @@ namespace Hypervel\Tests\Database; -use Exception; use Hypervel\Database\Eloquent\Collection; use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\Relations\Pivot; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; class DatabaseEloquentCollectionQueueableTest extends TestCase { + use VerifiesDoubles; + public function testSerializesPivotsEntitiesId(): void { - $spy = m::spy(Pivot::class); - $spy->expects('getQueueableId')->andReturn('project_id:1:user_id:2'); + $spy = Double::for(Pivot::class); + $spy->expects('getQueueableId')->with(Argument::none())->returns('project_id:1:user_id:2'); $c = new Collection([$spy]); @@ -26,8 +29,8 @@ public function testSerializesPivotsEntitiesId(): void public function testSerializesModelEntitiesById(): void { - $spy = m::spy(Model::class); - $spy->expects('getQueueableId')->andReturn(1); + $spy = Double::for(Model::class); + $spy->expects('getQueueableId')->with(Argument::none())->returns(1); $c = new Collection([$spy]); @@ -60,18 +63,14 @@ public function testReturnsCompleteAndCompoundQueueableIdsInCollectionOrder(): v ); } - /** - * @throws Exception - */ 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 = m::mock(Model::class, [ - 'getKey' => random_bytes(10), - 'getQueueableId' => 'mocked', - ]); + $mock = Double::for(Model::class); + $mock->expects('getKey')->never(); + $mock->expects('getQueueableId')->returns('mocked'); $c = new Collection([$mock]); diff --git a/tests/Database/DatabaseEloquentCollectionTest.php b/tests/Database/DatabaseEloquentCollectionTest.php index f24fc8c9f..537ad3d94 100755 --- a/tests/Database/DatabaseEloquentCollectionTest.php +++ b/tests/Database/DatabaseEloquentCollectionTest.php @@ -15,12 +15,15 @@ use Hypervel\Database\Schema\Builder as SchemaBuilder; use Hypervel\Support\Collection as BaseCollection; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseEloquentCollectionTest extends TestCase { + use VerifiesDoubles; + /** * Setup the database schema. */ @@ -356,11 +359,11 @@ public function testFindOrFailThrowsExceptionWithoutMessageWhenOtherModelsAreNot public function testLoadMethodEagerLoadsGivenRelationships(): void { - $model = m::mock(Model::class); - $builder = m::mock(Builder::class); - $model->expects('newQueryWithoutRelationships')->andReturn($builder); - $builder->expects('with')->with(['bar', 'baz'])->andReturnSelf(); - $builder->expects('eagerLoadRelations')->with([$model])->andReturn(['results']); + $model = Double::for(Model::class); + $builder = Double::for(Builder::class); + $model->expects('newQueryWithoutRelationships')->returns($builder); + $builder->expects('with')->with(['bar', 'baz'])->returns($builder); + $builder->expects('eagerLoadRelations')->with([$model])->returns(['results']); $c = new Collection([$model]); $c->load('bar', 'baz'); @@ -369,8 +372,8 @@ public function testLoadMethodEagerLoadsGivenRelationships(): void public function testLoadMissingWithoutRelationsDoesNotBuildAQuery(): void { - $model = m::mock(Model::class); - $model->shouldNotReceive('newQueryWithoutRelationships'); + $model = Double::for(Model::class); + $model->expects('newQueryWithoutRelationships')->never(); $collection = new Collection([$model]); $this->assertSame($collection, $collection->loadMissing([])); @@ -1002,17 +1005,17 @@ public function testEmptyCollectionStayEmptyOnFresh(): void public function testCanConvertCollectionOfModelsToEloquentQueryBuilder(): void { - $one = m::mock(Model::class); - $one->shouldReceive('getKey')->andReturn(1); + $one = Double::for(Model::class); + $one->allows('getKey')->returns(1); - $two = m::mock(Model::class); - $two->shouldReceive('getKey')->andReturn(2); + $two = Double::for(Model::class); + $two->allows('getKey')->returns(2); $c = new Collection([$one, $two]); - $mocBuilder = m::mock(Builder::class); - $one->expects('newModelQuery')->andReturn($mocBuilder); - $mocBuilder->expects('whereKey')->with($c->modelKeys())->andReturn($mocBuilder); + $mocBuilder = Double::for(Builder::class); + $one->expects('newModelQuery')->returns($mocBuilder); + $mocBuilder->expects('whereKey')->with($c->modelKeys())->returns($mocBuilder); $this->assertInstanceOf(Builder::class, $c->toQuery()); } @@ -1026,10 +1029,10 @@ public function testConvertingEmptyCollectionToQueryThrowsException(): void public function testConvertingCollectionWithoutModelKeysToQueryThrowsException(): void { - $model = m::mock(CollectionModel::class)->makePartial(); - $model->expects('getKey')->andReturn(null); - $model->expects('getKeyName')->andReturn('id'); - $model->shouldNotReceive('newModelQuery'); + $model = Double::for(new CollectionModel)->passthru(); + $model->expects('getKey')->returns(null); + $model->expects('getKeyName')->returns('id'); + $model->expects('newModelQuery')->never(); $this->expectException(MissingAttributeException::class); diff --git a/tests/Database/DatabaseEloquentFactoryTest.php b/tests/Database/DatabaseEloquentFactoryTest.php index 52e70ac37..6c8d2e33a 100644 --- a/tests/Database/DatabaseEloquentFactoryTest.php +++ b/tests/Database/DatabaseEloquentFactoryTest.php @@ -34,12 +34,15 @@ use Hypervel\Support\Str; use Hypervel\Tests\Database\Fixtures\Models\Money\Price; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use ReflectionClass; class DatabaseEloquentFactoryTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ @@ -51,9 +54,9 @@ protected function setUp(): void $container->singleton(Generator::class, function (Container $app, array $parameters): Generator { return FakerFactory::create('en_US'); }); - $app = m::mock(Application::class); - $app->shouldReceive('getNamespace')->andReturn('App\\'); - $container->instance(Application::class, $app); + $app = Double::for(Application::class, override: true); + $app->allows('getNamespace')->returns('App\\'); + $container->instance(Application::class, $app->instance()); $db = new DB; @@ -843,9 +846,9 @@ public function testResolveNestedModelFactories(): void public function testResolveNestedModelNameFromFactory(): void { - $app = m::mock(Application::class); - $app->shouldReceive('getNamespace')->andReturn('Hypervel\Tests\Database\Fixtures\\'); - Container::getInstance()->instance(Application::class, $app); + $app = Double::for(Application::class, override: true); + $app->expects('getNamespace')->returns('Hypervel\Tests\Database\Fixtures\\'); + Container::getInstance()->instance(Application::class, $app->instance()); Factory::useNamespace('Hypervel\Tests\Database\Fixtures\Factories\\'); @@ -856,9 +859,9 @@ public function testResolveNestedModelNameFromFactory(): void public function testResolveNonAppNestedModelFactories(): void { - $app = m::mock(Application::class); - $app->shouldReceive('getNamespace')->andReturn('Foo\\'); - Container::getInstance()->instance(Application::class, $app); + $app = Double::for(Application::class, override: true); + $app->allows('getNamespace')->returns('Foo\\'); + Container::getInstance()->instance(Application::class, $app->instance()); Factory::useNamespace('Factories\\'); diff --git a/tests/Database/DatabaseEloquentHasManyCreateOrFirstTest.php b/tests/Database/DatabaseEloquentHasManyCreateOrFirstTest.php index c3426817e..1983bd090 100755 --- a/tests/Database/DatabaseEloquentHasManyCreateOrFirstTest.php +++ b/tests/Database/DatabaseEloquentHasManyCreateOrFirstTest.php @@ -4,86 +4,88 @@ namespace Hypervel\Tests\Database\DatabaseEloquentHasManyCreateOrFirstTest; +use ArrayObject; use Closure; -use Exception; -use Hypervel\Database\Connection; -use Hypervel\Database\ConnectionResolverInterface; +use Hypervel\Database\Capsule\Manager as DB; use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\Relations\HasMany; -use Hypervel\Database\Query\Builder; -use Hypervel\Database\UniqueConstraintViolationException; +use Hypervel\Database\Events\QueryExecuted; +use Hypervel\Events\Dispatcher; use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseEloquentHasManyCreateOrFirstTest extends TestCase { + /** + * Set up independent writer and replica databases. + */ protected function setUp(): void { parent::setUp(); CarbonImmutable::setTestNow('2023-01-01 00:00:00'); + + $db = new DB; + + $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:']); + + // Reads come from a replica that has not caught up with the writer yet... + $db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'read' => ['database' => ':memory:'], + 'write' => ['database' => ':memory:'], + ], 'replicated'); + + $db->setEventDispatcher(new Dispatcher); + $db->bootEloquent(); + $db->setAsGlobal(); + + $schema = 'create table "child_table" ( + "id" integer primary key autoincrement not null, + "parent_id" integer not null, + "attr" varchar not null, + "val" varchar null, + "created_at" datetime null, + "updated_at" datetime null, + unique ("parent_id", "attr") + )'; + + $db->getConnection()->getPdo()->exec($schema); + $db->getConnection('replicated')->getPdo()->exec($schema); + $db->getConnection('replicated')->getReadPdo()->exec($schema); } #[DataProvider('createOrFirstValues')] public function testCreateOrFirstMethodCreatesNewRecord(Closure|array $values): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite', [456]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection()->expects('insert')->with( - 'insert into "child_table" ("attr", "val", "parent_id", "updated_at", "created_at") values (?, ?, ?, ?, ?)', - ['foo', 'bar', 123, '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->children()->createOrFirst(['attr' => 'foo'], $values); + $result = $this->children()->createOrFirst(['attr' => 'foo'], $values); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->rows()); } public function testCreateOrFirstMethodRetrievesExistingRecord(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $sql = 'insert into "child_table" ("attr", "val", "parent_id", "updated_at", "created_at") values (?, ?, ?, ?, ?)'; - $bindings = ['foo', 'bar', 123, '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $model->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], false, []) - ->andReturn([[ - 'id' => 456, - 'parent_id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $result = $model->children()->createOrFirst(['attr' => 'foo'], ['val' => 'bar']); + $this->seedRecord(['parent_id' => 123, 'attr' => 'foo', 'val' => 'bar']); + + $result = $this->children()->createOrFirst(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame('bar', $result->val); + $this->assertSame(1, $this->rows()); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'val' => 'bar', @@ -94,51 +96,27 @@ public function testCreateOrFirstMethodRetrievesExistingRecord(): void public function testFirstOrCreateMethodCreatesNewRecord(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite', [456]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "child_table" ("attr", "val", "parent_id", "updated_at", "created_at") values (?, ?, ?, ?, ?)', - ['foo', 'bar', 123, '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $result = $this->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->rows()); } public function testCreateOrFirstMethodCreatesNewRecordWithoutValues(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite', [456]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection()->expects('insert')->with( - 'insert into "child_table" ("attr", "parent_id", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 123, '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->children()->createOrFirst(['attr' => 'foo']); + $result = $this->children()->createOrFirst(['attr' => 'foo']); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'created_at' => '2023-01-01T00:00:00.000000Z', @@ -148,26 +126,11 @@ public function testCreateOrFirstMethodCreatesNewRecordWithoutValues(): void public function testFirstOrCreateMethodCreatesNewRecordWithoutValues(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite', [456]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "child_table" ("attr", "parent_id", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 123, '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->children()->firstOrCreate(['attr' => 'foo']); + $result = $this->children()->firstOrCreate(['attr' => 'foo']); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'created_at' => '2023-01-01T00:00:00.000000Z', @@ -177,28 +140,16 @@ public function testFirstOrCreateMethodCreatesNewRecordWithoutValues(): void public function testFirstOrCreateMethodRetrievesExistingRecord(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([[ - 'id' => 456, - 'parent_id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]]); - - $result = $model->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $this->seedRecord(['parent_id' => 123, 'attr' => 'foo', 'val' => 'bar']); + + $result = $this->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame('bar', $result->val); + $this->assertSame(1, $this->rows()); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'val' => 'bar', @@ -209,41 +160,17 @@ public function testFirstOrCreateMethodRetrievesExistingRecord(): void public function testFirstOrCreateMethodRetrievesRecordCreatedJustNow(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([]); - - $sql = 'insert into "child_table" ("attr", "val", "parent_id", "updated_at", "created_at") values (?, ?, ?, ?, ?)'; - $bindings = ['foo', 'bar', 123, '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $model->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], false, []) - ->andReturn([[ - 'id' => 456, - 'parent_id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $result = $model->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + // The replica has not seen the record yet, so the insert collides and the writer is asked again... + $this->seedRecord(['parent_id' => 123, 'attr' => 'foo', 'val' => 'bar'], 'replicated'); + + $result = $this->children('replicated')->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame('bar', $result->val); + $this->assertSame(1, $this->rows('replicated')); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'val' => 'bar', @@ -252,65 +179,83 @@ public function testFirstOrCreateMethodRetrievesRecordCreatedJustNow(): void ], $result->toArray()); } + public function testFirstOrCreateRetriesWithinTheParentWhenAnotherParentHasTheSameRecord(): void + { + $this->seedRecord(['parent_id' => 999, 'attr' => 'foo', 'val' => 'other'], 'replicated'); + $this->seedRecord(['parent_id' => 123, 'attr' => 'foo', 'val' => 'bar'], 'replicated'); + + $result = $this->children('replicated')->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); + + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(123, $result->parent_id); + $this->assertSame('bar', $result->val); + } + + public function testFirstOrCreateDoesNotTouchTheWriterWhenTheReplicaHasTheRecord(): void + { + $this->seedReplica(['parent_id' => 123, 'attr' => 'foo', 'val' => 'bar']); + $sides = new ArrayObject; + DB::connection('replicated')->listen(fn (QueryExecuted $query) => $sides[] = $query->readWriteType); + + $result = $this->children('replicated')->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); + + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame('bar', $result->val); + $this->assertNotContains('write', $sides->getArrayCopy()); + } + + public function testFirstOrCreateIgnoresRecordsOwnedByOtherParents(): void + { + $this->seedRecord(['parent_id' => 999, 'attr' => 'foo', 'val' => 'other']); + + $result = $this->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + + $this->assertTrue($result->wasRecentlyCreated); + $this->assertSame(123, $result->parent_id); + $this->assertSame('bar', $result->val); + $this->assertSame(2, $this->rows()); + } + + public function testCreateOrFirstIgnoresRecordsOwnedByOtherParents(): void + { + $this->seedRecord(['parent_id' => 999, 'attr' => 'foo', 'val' => 'other']); + + $result = $this->children()->createOrFirst(['attr' => 'foo'], ['val' => 'bar']); + + $this->assertTrue($result->wasRecentlyCreated); + $this->assertSame(123, $result->parent_id); + $this->assertSame(2, $this->rows()); + } + public function testUpdateOrCreateMethodCreatesNewRecord(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite', [456]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "child_table" ("attr", "val", "parent_id", "updated_at", "created_at") values (?, ?, ?, ?, ?)', - ['foo', 'bar', 123, '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->children()->updateOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $result = $this->children()->updateOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->rows()); } public function testUpdateOrCreateMethodUpdatesExistingRecord(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([[ - 'id' => 456, - 'parent_id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]]); - - $model->getConnection()->expects('update')->with( - 'update "child_table" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 456], - )->andReturn(1); - - $result = $model->children()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->seedRecord(['parent_id' => 123, 'attr' => 'foo', 'val' => 'bar']); + + $result = $this->children()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame('baz', $result->val); + $this->assertSame('baz', $this->fresh()->val); + $this->assertSame(1, $this->rows()); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'val' => 'baz', @@ -321,46 +266,17 @@ public function testUpdateOrCreateMethodUpdatesExistingRecord(): void public function testUpdateOrCreateMethodUpdatesRecordCreatedJustNow(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([]); - - $sql = 'insert into "child_table" ("attr", "val", "parent_id", "updated_at", "created_at") values (?, ?, ?, ?, ?)'; - $bindings = ['foo', 'baz', 123, '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $model->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], false, []) - ->andReturn([[ - 'id' => 456, - 'parent_id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $model->getConnection()->expects('update')->with( - 'update "child_table" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 456], - )->andReturn(1); - - $result = $model->children()->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->seedRecord(['parent_id' => 123, 'attr' => 'foo', 'val' => 'bar'], 'replicated'); + + $result = $this->children('replicated')->updateOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame('baz', $result->val); + $this->assertSame('baz', $this->fresh('replicated', onWriter: true)->val); + $this->assertSame(1, $this->rows('replicated')); $this->assertEquals([ - 'id' => 456, + 'id' => 1, 'parent_id' => 123, 'attr' => 'foo', 'val' => 'baz', @@ -369,28 +285,25 @@ public function testUpdateOrCreateMethodUpdatesRecordCreatedJustNow(): void ], $result->toArray()); } + public function testUpdateOrCreateDoesNotUpdateRecordsOwnedByOtherParents(): void + { + $this->seedRecord(['parent_id' => 999, 'attr' => 'foo', 'val' => 'other']); + + $result = $this->children()->updateOrCreate(['attr' => 'foo'], ['val' => 'bar']); + + $this->assertTrue($result->wasRecentlyCreated); + $this->assertSame('other', DB::table('child_table')->where('parent_id', 999)->value('val')); + $this->assertSame('bar', $this->fresh()->val); + } + #[DataProvider('createOrFirstValues')] public function testUpdateOrCreateMethodAcceptsClosureValuesAndCreates(Closure|array $values): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite', [456]); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([]); - - $model->getConnection()->expects('insert')->with( - 'insert into "child_table" ("attr", "val", "parent_id", "updated_at", "created_at") values (?, ?, ?, ?, ?)', - ['foo', 'bar', 123, '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $model->children()->updateOrCreate(['attr' => 'foo'], $values); + $result = $this->children()->updateOrCreate(['attr' => 'foo'], $values); + $this->assertTrue($result->wasRecentlyCreated); $this->assertSame('bar', $result->val); + $this->assertSame('bar', $this->fresh()->val); } public static function createOrFirstValues(): array @@ -403,56 +316,21 @@ public static function createOrFirstValues(): array public function testUpdateOrCreateMethodAcceptsClosureValuesAndUpdates(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([[ - 'id' => 456, - 'parent_id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]]); - - $model->getConnection()->expects('update')->with( - 'update "child_table" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 456], - )->andReturn(1); - - $result = $model->children()->updateOrCreate(['attr' => 'foo'], fn () => ['val' => 'baz']); + $this->seedRecord(['parent_id' => 123, 'attr' => 'foo', 'val' => 'bar']); + + $result = $this->children()->updateOrCreate(['attr' => 'foo'], fn () => ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); $this->assertSame('baz', $result->val); + $this->assertSame('baz', $this->fresh()->val); } public function testFirstOrNewDoesNotInvokeClosureWhenRecordExists(): void { - $model = new ParentModel; - $model->id = 123; - $this->mockConnectionForModel($model, 'SQLite'); - $model->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $model->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $model->getConnection() - ->expects('select') - ->with('select * from "child_table" where "child_table"."parent_id" = ? and "child_table"."parent_id" is not null and ("attr" = ?) limit 1', [123, 'foo'], true, []) - ->andReturn([[ - 'id' => 456, - 'parent_id' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); + $this->seedRecord(['parent_id' => 123, 'attr' => 'foo', 'val' => 'bar']); $callCount = 0; - $result = $model->children()->firstOrNew(['attr' => 'foo'], function () use (&$callCount) { + $result = $this->children()->firstOrNew(['attr' => 'foo'], function () use (&$callCount) { ++$callCount; return ['val' => 'should-not-be-called']; @@ -463,27 +341,58 @@ public function testFirstOrNewDoesNotInvokeClosureWhenRecordExists(): void $this->assertSame('bar', $result->val); } - protected function mockConnectionForModel(Model $model, string $database, array $lastInsertIds = []): void + /** + * Get the parent's children on the given connection. + */ + protected function children(string $connection = 'default'): HasMany { - $grammarClass = 'Hypervel\Database\Query\Grammars\\' . $database . 'Grammar'; - $processorClass = 'Hypervel\Database\Query\Processors\\' . $database . 'Processor'; - $processor = new $processorClass; - $connection = m::mock(Connection::class, ['getPostProcessor' => $processor]); - $grammar = new $grammarClass($connection); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor) { - return new Builder($connection, $grammar, $processor); - }); - $connection->shouldReceive('getDatabaseName')->andReturn('database'); - $resolver = m::mock(ConnectionResolverInterface::class, ['connection' => $connection]); + $parent = (new ParentModel)->setConnection($connection); + $parent->id = 123; - $class = get_class($model); - $class::setConnectionResolver($resolver); + return $parent->children(); + } - foreach ($lastInsertIds as $id) { - $connection->expects('getLastInsertId')->andReturn($id); - } + /** + * Insert a child on the writer. + */ + protected function seedRecord(array $attributes, string $connection = 'default'): void + { + DB::connection($connection)->table('child_table')->insert($attributes + [ + 'created_at' => '2023-01-01 00:00:00', + 'updated_at' => '2023-01-01 00:00:00', + ]); + } + + /** + * Insert a child on the replica. + */ + protected function seedReplica(array $attributes): void + { + $attributes += ['created_at' => '2023-01-01 00:00:00', 'updated_at' => '2023-01-01 00:00:00']; + + DB::connection('replicated')->getReadPdo()->exec(sprintf( + 'insert into "child_table" (%s) values (%s)', + implode(', ', array_map(fn ($column) => "\"{$column}\"", array_keys($attributes))), + implode(', ', array_map(fn ($value) => "'{$value}'", $attributes)) + )); + } + + /** + * Retrieve the stored child. + */ + protected function fresh(string $connection = 'default', bool $onWriter = false): ChildModel + { + $query = $this->children($connection); + + return ($onWriter ? $query->useWritePdo() : $query)->where('attr', 'foo')->firstOrFail(); + } + + /** + * Count the children on the writer. + */ + protected function rows(string $connection = 'default'): int + { + return DB::connection($connection)->table('child_table')->useWritePdo()->count(); } } @@ -496,6 +405,9 @@ class ParentModel extends Model protected array $guarded = []; + /** + * Get the parent's children. + */ public function children(): HasMany { return $this->hasMany(ChildModel::class, 'parent_id'); diff --git a/tests/Database/DatabaseEloquentHasManyTest.php b/tests/Database/DatabaseEloquentHasManyTest.php index 4f2cc558f..d4fb05832 100755 --- a/tests/Database/DatabaseEloquentHasManyTest.php +++ b/tests/Database/DatabaseEloquentHasManyTest.php @@ -13,55 +13,14 @@ use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; -use Mockery as m; use PDO; class DatabaseEloquentHasManyTest extends TestCase { - public function testRelationUpsertFillsForeignKey(): void - { - $relation = $this->getRelation(); - - $relation->getQuery()->expects('upsert')->with( - [ - ['email' => 'foo3', 'name' => 'bar', $relation->getForeignKeyName() => $relation->getParentKey()], - ], - ['email'], - ['name'] - )->andReturn(1); - - $relation->upsert( - ['email' => 'foo3', 'name' => 'bar'], - ['email'], - ['name'] - ); - - $relation->getQuery()->expects('upsert')->with( - [ - ['email' => 'foo3', 'name' => 'bar', $relation->getForeignKeyName() => $relation->getParentKey()], - ['name' => 'bar2', 'email' => 'foo2', $relation->getForeignKeyName() => $relation->getParentKey()], - ], - ['email'], - ['name'] - )->andReturn(2); - - $relation->upsert( - [ - ['email' => 'foo3', 'name' => 'bar'], - ['name' => 'bar2', 'email' => 'foo2'], - ], - ['email'], - ['name'] - ); - } - public function testRelationIsProperlyInitialized(): void { - $relation = $this->getRelation(); + $relation = $this->getRelationWithRealQuery(); $model = new ModelStub; - $relation->getRelated()->expects('newCollection')->andReturnUsing(function (array $array = []): Collection { - return new Collection($array); - }); $models = $relation->initRelation([$model], 'foo'); $this->assertEquals([$model], $models); @@ -99,7 +58,7 @@ public function testEagerConstraintsAreProperlyAddedWithStringKey(): void public function testModelsAreProperlyMatchedToParents(): void { - $relation = $this->getRelation(); + $relation = $this->getRelationWithRealQuery(); $result1 = new ModelStub; $result1->foreign_key = 1; @@ -115,9 +74,6 @@ public function testModelsAreProperlyMatchedToParents(): void $model3 = new ModelStub; $model3->id = 3; - $relation->getRelated()->expects('newCollection')->times(2)->andReturnUsing(function (array $array): Collection { - return new Collection($array); - }); $models = $relation->match([$model1, $model2, $model3], new Collection([$result1, $result2, $result3]), 'foo'); $this->assertEquals(1, $models[0]->foo[0]->foreign_key); @@ -142,22 +98,6 @@ protected function getRelationWithRealQuery(?Model $parent = null): HasMany return new HasMany($builder, $parent, 'table.foreign_key', 'id'); } - - protected function getRelation() - { - $queryBuilder = m::mock(QueryBuilder::class); - $builder = m::mock(Builder::class, [$queryBuilder]); - $builder->shouldReceive('whereNotNull')->with('table.foreign_key'); - $builder->shouldReceive('where')->with('table.foreign_key', '=', 1); - $related = m::mock(Model::class); - $builder->shouldReceive('getModel')->andReturn($related); - $parent = m::mock(Model::class); - $parent->shouldReceive('getAttribute')->with('id')->andReturn(1); - $parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at'); - $parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at'); - - return new HasMany($builder, $parent, 'table.foreign_key', 'id'); - } } class ModelStub extends Model diff --git a/tests/Database/DatabaseEloquentHasManyThroughCreateOrFirstTest.php b/tests/Database/DatabaseEloquentHasManyThroughCreateOrFirstTest.php index 976f223c5..d56b71a06 100644 --- a/tests/Database/DatabaseEloquentHasManyThroughCreateOrFirstTest.php +++ b/tests/Database/DatabaseEloquentHasManyThroughCreateOrFirstTest.php @@ -5,165 +5,112 @@ namespace Hypervel\Tests\Database\DatabaseEloquentHasManyThroughCreateOrFirstTest; use Closure; -use Exception; -use Hypervel\Database\Connection; -use Hypervel\Database\ConnectionResolverInterface; +use Hypervel\Database\Capsule\Manager as DB; use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\Relations\HasManyThrough; -use Hypervel\Database\Query\Builder; use Hypervel\Database\UniqueConstraintViolationException; +use Hypervel\Events\Dispatcher; use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseEloquentHasManyThroughCreateOrFirstTest extends TestCase { + /** + * Set up the relationship database. + */ protected function setUp(): void { parent::setUp(); CarbonImmutable::setTestNow('2023-01-01 00:00:00'); + + $db = new DB; + + $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:']); + $db->setEventDispatcher(new Dispatcher); + $db->bootEloquent(); + $db->setAsGlobal(); + + $pdo = $db->getConnection()->getPdo(); + + $pdo->exec('create table "pivot" ("id" integer primary key autoincrement not null, "parent_id" integer not null)'); + $pdo->exec('create table "child" ( + "id" integer primary key autoincrement not null, + "pivot_id" integer null, + "attr" varchar not null unique, + "val" varchar null, + "created_at" datetime null, + "updated_at" datetime null + )'); + + // The parent owns the child through this pivot row... + DB::table('pivot')->insert(['id' => 456, 'parent_id' => 123]); + DB::table('pivot')->insert(['id' => 457, 'parent_id' => 999]); } #[DataProvider('createOrFirstValues')] public function testCreateOrFirstMethodCreatesNewRecord(Closure|array $values): void { - $parent = new ParentModel; - $parent->id = 123; - $this->mockConnectionForModel($parent, 'SQLite', [789]); - $parent->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $parent->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - $parent->getConnection()->expects('insert')->with( - 'insert into "child" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $parent->children()->createOrFirst(['attr' => 'foo'], $values); + $result = $this->children()->createOrFirst(['attr' => 'foo'], $values); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 789, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->rows()); } public function testCreateOrFirstMethodRetrievesExistingRecord(): void { - $parent = new ParentModel; - $parent->id = 123; - $parent->exists = true; - $this->mockConnectionForModel($parent, 'SQLite'); - $parent->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $parent->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $sql = 'insert into "child" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)'; - $bindings = ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $parent->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $parent->getConnection() - ->expects('select') - ->with( - 'select "child".*, "pivot"."parent_id" as "hypervel_through_key" from "child" inner join "pivot" on "pivot"."id" = "child"."pivot_id" where "pivot"."parent_id" = ? and ("child"."attr" = ?) limit 1', - [123, 'foo'], - false, - [], - ) - ->andReturn([[ - 'id' => 789, - 'pivot_id' => 456, - 'hypervel_through_key' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $result = $parent->children()->createOrFirst(['attr' => 'foo'], ['val' => 'bar']); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar', 'pivot_id' => 456]); + + $result = $this->children()->createOrFirst(['attr' => 'foo'], ['val' => 'bar']); + $this->assertFalse($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 789, + 'id' => 1, 'pivot_id' => 456, - 'hypervel_through_key' => 123, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', + 'hypervel_through_key' => 123, ], $result->toArray()); + $this->assertSame(1, $this->rows()); } public function testFirstOrCreateMethodCreatesNewRecord(): void { - $parent = new ParentModel; - $parent->id = 123; - $parent->exists = true; - $this->mockConnectionForModel($parent, 'SQLite', [789]); - $parent->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $parent->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $parent->getConnection() - ->expects('select') - ->with( - 'select "child".*, "pivot"."parent_id" as "hypervel_through_key" from "child" inner join "pivot" on "pivot"."id" = "child"."pivot_id" where "pivot"."parent_id" = ? and ("child"."attr" = ?) limit 1', - [123, 'foo'], - true, - [], - ) - ->andReturn([]); - - $parent->getConnection()->expects('insert')->with( - 'insert into "child" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - )->andReturnTrue(); - - $result = $parent->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $result = $this->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 789, + 'id' => 1, 'attr' => 'foo', 'val' => 'bar', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->rows()); } public function testFirstOrCreateMethodRetrievesExistingRecord(): void { - $parent = new ParentModel; - $parent->id = 123; - $parent->exists = true; - $this->mockConnectionForModel($parent, 'SQLite'); - $parent->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $parent->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $parent->getConnection() - ->expects('select') - ->with( - 'select "child".*, "pivot"."parent_id" as "hypervel_through_key" from "child" inner join "pivot" on "pivot"."id" = "child"."pivot_id" where "pivot"."parent_id" = ? and ("child"."attr" = ?) limit 1', - [123, 'foo'], - true, - [], - ) - ->andReturn([[ - 'id' => 789, - 'pivot_id' => 456, - 'hypervel_through_key' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01 00:00:00', - 'updated_at' => '2023-01-01 00:00:00', - ]]); - - $result = $parent->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar', 'pivot_id' => 456]); + + $result = $this->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'baz']); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame('bar', $result->val); + $this->assertSame(1, $this->rows()); $this->assertEquals([ - 'id' => 789, + 'id' => 1, 'pivot_id' => 456, 'hypervel_through_key' => 123, 'attr' => 'foo', @@ -176,53 +123,16 @@ public function testFirstOrCreateMethodRetrievesExistingRecord(): void #[DataProvider('createOrFirstValues')] public function testFirstOrCreateMethodRetrievesRecordCreatedJustNow(Closure|array $values): void { - $parent = new ParentModel; - $parent->id = 123; - $parent->exists = true; - $this->mockConnectionForModel($parent, 'SQLite'); - $parent->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $parent->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $parent->getConnection() - ->expects('select') - ->with( - 'select "child".*, "pivot"."parent_id" as "hypervel_through_key" from "child" inner join "pivot" on "pivot"."id" = "child"."pivot_id" where "pivot"."parent_id" = ? and ("child"."attr" = ?) limit 1', - [123, 'foo'], - true, - [], - ) - ->andReturn([]); - - $sql = 'insert into "child" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)'; - $bindings = ['foo', 'bar', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $parent->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $parent->getConnection() - ->expects('select') - ->with( - 'select "child".*, "pivot"."parent_id" as "hypervel_through_key" from "child" inner join "pivot" on "pivot"."id" = "child"."pivot_id" where "pivot"."parent_id" = ? and ("child"."attr" = ?) limit 1', - [123, 'foo'], - false, - [], - ) - ->andReturn([[ - 'id' => 789, - 'pivot_id' => 456, - 'hypervel_through_key' => 123, - 'attr' => 'foo', - 'val' => 'other', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]]); - - $result = $parent->children()->firstOrCreate(['attr' => 'foo'], $values); + $this->competingInsert(['attr' => 'foo', 'val' => 'other', 'pivot_id' => 456]); + + $result = $this->children()->firstOrCreate(['attr' => 'foo'], $values); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame(123, $result->hypervel_through_key); + $this->assertSame(1, $this->rows()); $this->assertEquals([ - 'id' => 789, + 'id' => 1, 'pivot_id' => 456, 'hypervel_through_key' => 123, 'attr' => 'foo', @@ -243,85 +153,45 @@ public static function createOrFirstValues(): array ]; } + public function testFirstOrCreateThrowsWhenAnotherParentsRecordHoldsTheUniqueValue(): void + { + $this->seedRecord(['attr' => 'foo', 'val' => 'bar', 'pivot_id' => 457]); + + $this->expectException(UniqueConstraintViolationException::class); + + $this->children()->firstOrCreate(['attr' => 'foo'], ['val' => 'bar']); + } + #[DataProvider('updateOrCreateValues')] public function testUpdateOrCreateMethodCreatesNewRecord(Closure|array $values): void { - $parent = new ParentModel; - $parent->id = 123; - $parent->exists = true; - $this->mockConnectionForModel($parent, 'SQLite', [789]); - $parent->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $parent->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $parent->getConnection() - ->expects('select') - ->with( - 'select "child".*, "pivot"."parent_id" as "hypervel_through_key" from "child" inner join "pivot" on "pivot"."id" = "child"."pivot_id" where "pivot"."parent_id" = ? and ("child"."attr" = ?) limit 1', - [123, 'foo'], - true, - [], - ) - ->andReturn([]); - - $parent->getConnection() - ->expects('insert') - ->with( - 'insert into "child" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)', - ['foo', 'baz', '2023-01-01 00:00:00', '2023-01-01 00:00:00'], - ) - ->andReturnTrue(); - - $result = $parent->children()->updateOrCreate(['attr' => 'foo'], $values); + $result = $this->children()->updateOrCreate(['attr' => 'foo'], $values); + $this->assertTrue($result->wasRecentlyCreated); $this->assertEquals([ - 'id' => 789, + 'id' => 1, 'attr' => 'foo', 'val' => 'baz', 'created_at' => '2023-01-01T00:00:00.000000Z', 'updated_at' => '2023-01-01T00:00:00.000000Z', ], $result->toArray()); + $this->assertSame(1, $this->rows()); } #[DataProvider('updateOrCreateValues')] public function testUpdateOrCreateMethodUpdatesExistingRecord(Closure|array $values): void { - $parent = new ParentModel; - $parent->id = 123; - $parent->exists = true; - $this->mockConnectionForModel($parent, 'SQLite'); - $parent->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $parent->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $parent->getConnection() - ->expects('select') - ->with( - 'select "child".*, "pivot"."parent_id" as "hypervel_through_key" from "child" inner join "pivot" on "pivot"."id" = "child"."pivot_id" where "pivot"."parent_id" = ? and ("child"."attr" = ?) limit 1', - [123, 'foo'], - true, - [], - ) - ->andReturn([[ - 'id' => 789, - 'pivot_id' => 456, - 'hypervel_through_key' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]]); - - $parent->getConnection() - ->expects('update') - ->with( - 'update "child" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 789], - ) - ->andReturn(1); - - $result = $parent->children()->updateOrCreate(['attr' => 'foo'], $values); + $this->seedRecord(['attr' => 'foo', 'val' => 'bar', 'pivot_id' => 456]); + + $result = $this->children()->updateOrCreate(['attr' => 'foo'], $values); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame('baz', $result->val); + $this->assertSame('baz', DB::table('child')->where('id', 1)->value('val')); + $this->assertSame(1, $this->rows()); $this->assertEquals([ - 'id' => 789, + 'id' => 1, 'pivot_id' => 456, 'hypervel_through_key' => 123, 'attr' => 'foo', @@ -334,61 +204,16 @@ public function testUpdateOrCreateMethodUpdatesExistingRecord(Closure|array $val #[DataProvider('updateOrCreateValues')] public function testUpdateOrCreateMethodUpdatesRecordCreatedJustNow(Closure|array $values): void { - $parent = new ParentModel; - $parent->id = 123; - $parent->exists = true; - $this->mockConnectionForModel($parent, 'SQLite'); - $parent->getConnection()->shouldReceive('transactionLevel')->andReturn(0); - $parent->getConnection()->shouldReceive('getWritableName')->andReturn('sqlite'); - - $parent->getConnection() - ->expects('select') - ->with( - 'select "child".*, "pivot"."parent_id" as "hypervel_through_key" from "child" inner join "pivot" on "pivot"."id" = "child"."pivot_id" where "pivot"."parent_id" = ? and ("child"."attr" = ?) limit 1', - [123, 'foo'], - true, - [], - ) - ->andReturn([]); - - $sql = 'insert into "child" ("attr", "val", "updated_at", "created_at") values (?, ?, ?, ?)'; - $bindings = ['foo', 'baz', '2023-01-01 00:00:00', '2023-01-01 00:00:00']; - - $parent->getConnection() - ->expects('insert') - ->with($sql, $bindings) - ->andThrow(new UniqueConstraintViolationException('sqlite', $sql, $bindings, new Exception)); - - $parent->getConnection() - ->expects('select') - ->with( - 'select "child".*, "pivot"."parent_id" as "hypervel_through_key" from "child" inner join "pivot" on "pivot"."id" = "child"."pivot_id" where "pivot"."parent_id" = ? and ("child"."attr" = ?) limit 1', - [123, 'foo'], - false, - [], - ) - ->andReturn([[ - 'id' => 789, - 'pivot_id' => 456, - 'hypervel_through_key' => 123, - 'attr' => 'foo', - 'val' => 'bar', - 'created_at' => '2023-01-01T00:00:00.000000Z', - 'updated_at' => '2023-01-01T00:00:00.000000Z', - ]]); - - $parent->getConnection() - ->expects('update') - ->with( - 'update "child" set "val" = ?, "updated_at" = ? where "id" = ?', - ['baz', '2023-01-01 00:00:00', 789], - ) - ->andReturn(1); - - $result = $parent->children()->updateOrCreate(['attr' => 'foo'], $values); + $this->competingInsert(['attr' => 'foo', 'val' => 'bar', 'pivot_id' => 456]); + + $result = $this->children()->updateOrCreate(['attr' => 'foo'], $values); + $this->assertFalse($result->wasRecentlyCreated); + $this->assertSame(1, $result->id); + $this->assertSame('baz', DB::table('child')->where('id', 1)->value('val')); + $this->assertSame(1, $this->rows()); $this->assertEquals([ - 'id' => 789, + 'id' => 1, 'pivot_id' => 456, 'hypervel_through_key' => 123, 'attr' => 'foo', @@ -410,29 +235,46 @@ public static function updateOrCreateValues(): array } /** - * Mock the model's database connection. + * Get the parent's children through the pivot model. */ - protected function mockConnectionForModel(Model $model, string $database, array $lastInsertIds = []): void + protected function children(): HasManyThrough { - $grammarClass = 'Hypervel\Database\Query\Grammars\\' . $database . 'Grammar'; - $processorClass = 'Hypervel\Database\Query\Processors\\' . $database . 'Processor'; - $processor = new $processorClass; - $connection = m::mock(Connection::class, ['getPostProcessor' => $processor]); - $grammar = new $grammarClass($connection); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor) { - return new Builder($connection, $grammar, $processor); - }); - $connection->shouldReceive('getDatabaseName')->andReturn('database'); - $resolver = m::mock(ConnectionResolverInterface::class, ['connection' => $connection]); + $parent = new ParentModel; + $parent->id = 123; + $parent->exists = true; - $class = get_class($model); - $class::setConnectionResolver($resolver); + return $parent->children(); + } - foreach ($lastInsertIds as $id) { - $connection->expects('getLastInsertId')->andReturn($id); - } + /** + * Insert a child record. + */ + protected function seedRecord(array $attributes): void + { + DB::table('child')->insert($attributes + [ + 'created_at' => '2023-01-01 00:00:00', + 'updated_at' => '2023-01-01 00:00:00', + ]); + } + + /** + * Have another process create the record right before this one is inserted. + */ + protected function competingInsert(array $attributes): void + { + ChildModel::creating(function () use ($attributes) { + ChildModel::flushEventListeners(); + + $this->seedRecord($attributes); + }); + } + + /** + * Count the child records. + */ + protected function rows(): int + { + return DB::table('child')->count(); } } diff --git a/tests/Database/DatabaseEloquentHasOneTest.php b/tests/Database/DatabaseEloquentHasOneTest.php index ac978e48b..ce85b7028 100755 --- a/tests/Database/DatabaseEloquentHasOneTest.php +++ b/tests/Database/DatabaseEloquentHasOneTest.php @@ -13,94 +13,19 @@ use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; -use Mockery as m; use PDO; class DatabaseEloquentHasOneTest extends TestCase { - protected $builder; - - protected $related; - - protected $parent; - - public function testHasOneWithDefault(): void - { - $relation = $this->getRelation()->withDefault(); - - $this->builder->expects('first')->andReturnNull(); - - // Use andReturnSelf() to satisfy static return type of newInstance() - $this->related->expects('newInstance')->andReturnSelf(); - $this->related->expects('setAttribute')->with('foreign_key', 1)->passthru(); - - $result = $relation->getResults(); - $this->assertSame($this->related, $result); - $this->assertSame(1, $result->getAttribute('foreign_key')); - } - - public function testHasOneWithDynamicDefault(): void - { - $relation = $this->getRelation()->withDefault(function (Model $newModel): void { - $newModel->username = 'taylor'; - }); - - $this->builder->expects('first')->andReturnNull(); - - // Use andReturnSelf() to satisfy static return type of newInstance() - $this->related->expects('newInstance')->andReturnSelf(); - $this->related->expects('setAttribute')->with('foreign_key', 1)->passthru(); - - $result = $relation->getResults(); - $this->assertSame($this->related, $result); - $this->assertSame('taylor', $result->username); - $this->assertSame(1, $result->getAttribute('foreign_key')); - } - - public function testHasOneWithDynamicDefaultUseParentModel(): void - { - $relation = $this->getRelation()->withDefault(function (Model $newModel, Model $parentModel): void { - $newModel->username = $parentModel->username; - }); - - $this->builder->expects('first')->andReturnNull(); - - // Use andReturnSelf() to satisfy static return type of newInstance() - $this->related->expects('newInstance')->andReturnSelf(); - $this->related->expects('setAttribute')->with('foreign_key', 1)->passthru(); - - $result = $relation->getResults(); - $this->assertSame($this->related, $result); - $this->assertSame('taylor', $result->username); - $this->assertSame(1, $result->getAttribute('foreign_key')); - } - - public function testHasOneWithArrayDefault(): void - { - $attributes = ['username' => 'taylor']; - - $relation = $this->getRelation()->withDefault($attributes); - - $this->builder->expects('first')->andReturnNull(); - - // Use andReturnSelf() to satisfy static return type of newInstance() - $this->related->expects('newInstance')->andReturnSelf(); - $this->related->expects('setAttribute')->with('foreign_key', 1)->passthru(); - - $result = $relation->getResults(); - $this->assertSame($this->related, $result); - $this->assertSame('taylor', $result->username); - $this->assertSame(1, $result->getAttribute('foreign_key')); - } - public function testRelationIsProperlyInitialized(): void { - $relation = $this->getRelation(); - $model = m::mock(Model::class); - $model->expects('setRelation')->with('foo', null); + $relation = $this->getRelationWithRealQuery(); + $model = new ModelStub; $models = $relation->initRelation([$model], 'foo'); - $this->assertEquals([$model], $models); + $this->assertSame([$model], $models); + $this->assertTrue($model->relationLoaded('foo')); + $this->assertNull($model->getRelation('foo')); } public function testEagerConstraintsAreProperlyAdded(): void @@ -118,7 +43,7 @@ public function testEagerConstraintsAreProperlyAdded(): void public function testModelsAreProperlyMatchedToParents(): void { - $relation = $this->getRelation(); + $relation = $this->getRelationWithRealQuery(); $result1 = new ModelStub; $result1->foreign_key = 1; @@ -179,27 +104,6 @@ protected function getRelationWithRealQuery(): HasOne return new HasOne($this->newBuilder(), $parent, 'table.foreign_key', 'id'); } - - /** - * Get the has one relationship. - */ - protected function getRelation(): HasOne - { - $this->builder = m::mock(Builder::class); - $this->builder->shouldReceive('whereNotNull')->with('table.foreign_key'); - $this->builder->shouldReceive('where')->with('table.foreign_key', '=', 1); - // Use partial mock so real Model methods work (setAttribute, forceFill, etc.) - $this->related = m::mock(Model::class)->makePartial(); - $this->builder->shouldReceive('getModel')->andReturn($this->related); - $this->parent = m::mock(Model::class); - $this->parent->shouldReceive('getAttribute')->with('id')->andReturn(1); - $this->parent->shouldReceive('getAttribute')->with('username')->andReturn('taylor'); - $this->parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at'); - $this->parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at'); - $this->parent->shouldReceive('newQueryWithoutScopes')->andReturn($this->builder); - - return new HasOne($this->builder, $this->parent, 'table.foreign_key', 'id'); - } } class ModelStub extends Model diff --git a/tests/Database/DatabaseEloquentIntegrationTest.php b/tests/Database/DatabaseEloquentIntegrationTest.php index b2487187b..b2d32f061 100644 --- a/tests/Database/DatabaseEloquentIntegrationTest.php +++ b/tests/Database/DatabaseEloquentIntegrationTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Database\DatabaseEloquentIntegrationTest; +use ArrayObject; use DateTimeInterface; use Exception; use Hypervel\Database\Capsule\Manager as DB; @@ -23,24 +24,31 @@ use Hypervel\Database\Eloquent\Relations\Relation; use Hypervel\Database\Eloquent\SoftDeletes; use Hypervel\Database\Eloquent\SoftDeletingScope; +use Hypervel\Database\Query\Expression; use Hypervel\Database\QueryException; use Hypervel\Database\Schema\Blueprint; use Hypervel\Database\Schema\Builder as SchemaBuilder; use Hypervel\Database\UniqueConstraintViolationException; +use Hypervel\Events\Dispatcher; use Hypervel\Pagination\AbstractPaginator as Paginator; use Hypervel\Pagination\Cursor; use Hypervel\Pagination\CursorPaginator; use Hypervel\Pagination\LengthAwarePaginator; use Hypervel\Support\CarbonImmutable; +use Hypervel\Support\Collection as BaseCollection; use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Database\Fixtures\Enums\Bar; use Hypervel\Tests\Database\Fixtures\Models\Integration\Post as IgnoringTouchPost; use Hypervel\Tests\Database\Fixtures\Models\Integration\User as IgnoringTouchUser; +use PHPUnit\Framework\Attributes\TestWith; +use Stringable; use UnitEnum; class DatabaseEloquentIntegrationTest extends TestCase { + protected DB $db; + /** * Setup the database schema. */ @@ -48,7 +56,7 @@ protected function setUp(): void { parent::setUp(); - $db = new DB; + $this->db = $db = new DB; $db->addConnection([ 'driver' => 'sqlite', @@ -80,6 +88,15 @@ protected function createSchema() $table->text('json')->default(json_encode([])); }); + $this->schema('default')->create('counters', function ($table) { + $table->increments('id'); + $table->integer('foo')->default(0); + $table->integer('bar')->default(0); + $table->integer('category')->nullable(); + $table->string('name')->nullable(); + $table->timestamps(); + }); + $this->schema('default')->create('generated_users', function (Blueprint $table): void { $table->increments('id'); $table->string('first_name'); @@ -368,6 +385,659 @@ public function testConfiguredAttributesAreRefreshedAfterIncrementAndDecrement() $user->save(); } + public function testHasManyUpsertFillsTheForeignKey(): void + { + $user = User::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']); + $this->schema()->table('posts', fn ($table) => $table->unique('name')); + + $user->posts()->upsert([['name' => 'first'], ['name' => 'second']], ['name'], ['name']); + $user->posts()->upsert(['name' => 'second'], ['name'], ['name']); + + $posts = Post::orderBy('id')->get(); + + $this->assertSame(['first', 'second'], $posts->pluck('name')->all()); + $this->assertSame([1, 1], $posts->pluck('user_id')->all()); + } + + public function testMorphManyUpsertFillsTheMorphColumns(): void + { + $user = User::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']); + $this->schema()->table('photos', fn ($table) => $table->unique('name')); + + $user->photos()->upsert([['name' => 'first'], ['name' => 'second']], ['name'], ['name']); + $user->photos()->upsert(['name' => 'second'], ['name'], ['name']); + + $photos = Photo::orderBy('id')->get(); + + $this->assertSame(['first', 'second'], $photos->pluck('name')->all()); + $this->assertSame([1, 1], $photos->pluck('imageable_id')->all()); + $this->assertSame([User::class, User::class], $photos->pluck('imageable_type')->all()); + } + + public function testMorphToManyAttachInsertsThePivotRecordWithTheMorphColumns(): void + { + $post = Post::create(['name' => 'Post', 'user_id' => 1]); + $tag = Tag::create(['name' => 'php']); + + $post->tags()->attach($tag->id, ['taxonomy' => 'bar']); + + $this->assertEquals([ + (object) [ + 'tag_id' => $tag->id, + 'taggable_id' => $post->id, + 'taggable_type' => Post::class, + 'taxonomy' => 'bar', + ], + ], $this->connection()->table('taggables')->get()->all()); + } + + public function testMorphToManyDetachOnlyRemovesTheOwnersPivotRecords(): void + { + $post = Post::create(['name' => 'Post', 'user_id' => 1]); + $tags = [ + Tag::create(['name' => 'php']), + Tag::create(['name' => 'hypervel']), + Tag::create(['name' => 'testing']), + ]; + + $post->tags()->attach(collect($tags)->pluck('id')->all()); + // Same ids, but owned by a different morph type, so they must survive. + foreach ($tags as $tag) { + $this->connection()->table('taggables')->insert([ + 'tag_id' => $tag->id, + 'taggable_id' => $post->id, + 'taggable_type' => Photo::class, + ]); + } + + $this->assertSame(2, $post->tags()->detach([$tags[0]->id, $tags[1]->id])); + $this->assertSame([$tags[2]->id], $post->tags()->pluck('tags.id')->all()); + $this->assertSame(3, $this->connection()->table('taggables')->where('taggable_type', Photo::class)->count()); + + $this->assertSame(1, $post->tags()->detach()); + $this->assertSame([], $post->tags()->pluck('tags.id')->all()); + $this->assertSame(3, $this->connection()->table('taggables')->where('taggable_type', Photo::class)->count()); + } + + public function testMorphToManyPivotClausesAcceptExpressions(): void + { + $post = Post::create(['name' => 'Post', 'user_id' => 1]); + // The tag ids and the taxonomies sort in opposite orders... + $b = Tag::create(['name' => 'b']); + $a = Tag::create(['name' => 'a']); + $none = Tag::create(['name' => 'none']); + + $post->tags()->attach($a->id, ['taxonomy' => 'a']); + $post->tags()->attach($b->id, ['taxonomy' => 'b']); + $post->tags()->attach($none->id); + + // An expression is used as given, instead of being qualified as a pivot column name... + $column = new Expression('upper("taggables"."taxonomy")'); + + $ids = fn ($relation) => $relation->pluck('tags.id')->all(); + + $this->assertSame([$a->id], $ids($post->tags()->wherePivot($column, '=', 'A'))); + $this->assertSame([$b->id, $a->id], $ids($post->tags()->wherePivotIn($column, ['A', 'B'])->orderBy('tags.id'))); + $this->assertSame([$a->id], $ids($post->tags()->wherePivotBetween($column, ['A', 'A']))); + $this->assertSame([$none->id], $ids($post->tags()->wherePivotNull($column))); + $this->assertSame([$a->id, $b->id], $ids($post->tags()->wherePivotNotNull($column)->orderByPivot($column))); + $this->assertSame([$b->id, $a->id], $ids($post->tags()->wherePivotNotNull($column)->orderByPivot($column, 'desc'))); + $this->assertSame([$b->id], $ids($post->tags()->withPivotValue($column, 'B'))); + } + + public function testBelongsToManyMatchesStringablePivotKeysToTheirParents(): void + { + $first = User::create(['id' => 1, 'email' => 'first@example.com']); + $second = User::create(['id' => 2, 'email' => 'second@example.com']); + + $result = (object) ['pivot' => (object) ['user_id' => new StringableKey('1')]]; + + $models = $first->friends()->match([$first, $second], new Collection([$result]), 'friends'); + + $this->assertSame(1, $models[0]->friends->count()); + $this->assertContains($result, $models[0]->friends); + $this->assertCount(0, $models[1]->friends); + } + + public function testBelongsToManyWithPivotValuesFiltersAndInsertsDefaults(): void + { + $user = User::create(['email' => 'first@example.com']); + $friend = User::create(['email' => 'second@example.com']); + $other = User::create(['email' => 'third@example.com']); + $relation = $user->friends()->withPivotValue(['friend_level_id' => 1]); + + $relation->attach($friend); + $user->friends()->attach($other, ['friend_level_id' => 2]); + + $this->assertSame(1, DB::table('friends')->where('friend_id', $friend->id)->value('friend_level_id')); + $this->assertSame([$friend->id], $relation->get()->modelKeys()); + } + + public function testModelsWithNullParentKeysAreNotMatchedToEmptyStringPivotKeys(): void + { + $model = (new User)->setKeyType('string')->forceFill(['id' => null]); + $relation = $model->friends(); + + $result = (object) [ + 'pivot' => (object) ['user_id' => ''], + ]; + + $relation->match([$model], Collection::wrap($result), 'friends'); + + $this->assertFalse($model->relationLoaded('friends')); + } + + public function testModelsWithNullPivotKeysAreNotMatchedToEmptyStringParentKeys(): void + { + $model = (new User)->setKeyType('string')->forceFill(['id' => '']); + $relation = $model->friends(); + + $result = (object) [ + 'pivot' => (object) ['user_id' => null], + ]; + + $relation->match([$model], Collection::wrap($result), 'friends'); + + $this->assertFalse($model->relationLoaded('friends')); + } + + public function testHasOneWithDefaultReturnsAnUnsavedModelWithTheForeignKeySet(): void + { + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + + $post = $user->post()->withDefault()->getResults(); + + $this->assertInstanceOf(Post::class, $post); + $this->assertFalse($post->exists); + $this->assertSame(7, $post->user_id); + $this->assertSame(0, Post::count()); + } + + public function testHasOneWithDefaultCanBeCustomizedWithAClosureOrArray(): void + { + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + + $post = $user->post()->withDefault(function ($newPost, $parent) { + $newPost->name = $parent->email; + })->getResults(); + + $this->assertSame('taylorotwell@gmail.com', $post->name); + $this->assertSame(7, $post->user_id); + + $post = $user->post()->withDefault(['name' => 'Default Post'])->getResults(); + + $this->assertSame('Default Post', $post->name); + $this->assertSame(7, $post->user_id); + } + + public function testHasOneWithDefaultIsIgnoredWhenTheRelatedModelExists(): void + { + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + $user->post()->create(['name' => 'Real Post']); + + $post = $user->post()->withDefault(['name' => 'Default Post'])->getResults(); + + $this->assertTrue($post->exists); + $this->assertSame('Real Post', $post->name); + } + + public function testHasManyCreatingMethodsFillTheForeignKey(): void + { + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + + $made = $user->posts()->make(['name' => 'made']); + $this->assertFalse($made->exists); + $this->assertSame(7, $made->user_id); + + $madeMany = $user->posts()->makeMany([['name' => 'a'], ['name' => 'b']]); + $this->assertSame([7, 7], $madeMany->pluck('user_id')->all()); + $this->assertSame(0, Post::count()); + + $user->posts()->create(['name' => 'created']); + $user->posts()->forceCreate(['name' => 'forced']); + $user->posts()->createMany([['name' => 'many-a'], ['name' => 'many-b']]); + $user->posts()->save(new Post(['name' => 'saved'])); + + $posts = Post::orderBy('id')->get(); + $this->assertSame(['created', 'forced', 'many-a', 'many-b', 'saved'], $posts->pluck('name')->all()); + $this->assertSame([7, 7, 7, 7, 7], $posts->pluck('user_id')->all()); + } + + public function testHasManyFindingOrCreatingMethodsFillTheForeignKey(): void + { + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + $existing = $user->posts()->create(['name' => 'existing']); + + $this->assertTrue($user->posts()->findOrNew($existing->id)->is($existing)); + $new = $user->posts()->findOrNew(999); + $this->assertFalse($new->exists); + $this->assertSame(7, $new->user_id); + + $this->assertTrue($user->posts()->firstOrNew(['name' => 'existing'])->is($existing)); + $new = $user->posts()->firstOrNew(['name' => 'new'], ['user_id' => 1]); + $this->assertFalse($new->exists); + $this->assertSame(7, $new->user_id); + + $this->assertTrue($user->posts()->firstOrCreate(['name' => 'existing'], ['name' => 'ignored'])->is($existing)); + $created = $user->posts()->firstOrCreate(['name' => 'first-or-create']); + $this->assertTrue($created->exists); + $this->assertSame(7, $created->user_id); + + $updated = $user->posts()->updateOrCreate(['name' => 'existing'], ['name' => 'updated']); + $this->assertTrue($updated->is($existing)); + $this->assertSame('updated', $existing->fresh()->name); + $created = $user->posts()->updateOrCreate(['name' => 'update-or-create']); + $this->assertTrue($created->exists); + $this->assertSame(7, $created->user_id); + } + + public function testHasOneCreatingMethodsFillTheForeignKey(): void + { + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + + $made = $user->post()->make(['name' => 'made']); + $this->assertFalse($made->exists); + $this->assertSame(7, $made->user_id); + $this->assertSame(0, Post::count()); + + $user->post()->create(['name' => 'created']); + $user->post()->forceCreate(['name' => 'forced']); + $user->post()->save(new Post(['name' => 'saved'])); + + $this->assertSame([7, 7, 7], Post::pluck('user_id')->all()); + } + + public function testHasOneWithDynamicDefaultReceivesTheParent(): void + { + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + + $post = $user->post()->withDefault(function ($newPost, $parent) { + $newPost->name = $parent->email; + })->getResults(); + + $this->assertSame('taylorotwell@gmail.com', $post->name); + } + + public function testMorphManyCreatingMethodsFillTheMorphColumns(): void + { + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + + $made = $user->photos()->make(['name' => 'made']); + $this->assertFalse($made->exists); + $this->assertSame(7, $made->imageable_id); + $this->assertSame(User::class, $made->imageable_type); + + $user->photos()->create(['name' => 'created']); + $user->photos()->forceCreate(['name' => 'forced']); + $user->photos()->createMany([['name' => 'many']]); + + $photos = Photo::orderBy('id')->get(); + $this->assertSame(['created', 'forced', 'many'], $photos->pluck('name')->all()); + $this->assertSame([7, 7, 7], $photos->pluck('imageable_id')->all()); + $this->assertSame(array_fill(0, 3, User::class), $photos->pluck('imageable_type')->all()); + } + + public function testMorphManyUsesTheMorphMapAlias(): void + { + Relation::morphMap(['user' => User::class]); + + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + $photo = $user->photos()->create(['name' => 'created']); + + $this->assertSame('user', $photo->imageable_type); + $this->assertTrue($photo->imageable->is($user)); + } + + public function testMorphManyFindingOrCreatingMethodsFillTheMorphColumns(): void + { + $user = User::create(['id' => 7, 'email' => 'taylorotwell@gmail.com']); + $existing = $user->photos()->create(['name' => 'existing']); + + $this->assertTrue($user->photos()->findOrNew($existing->id)->is($existing)); + $this->assertTrue($user->photos()->firstOrNew(['name' => 'existing'])->is($existing)); + $this->assertTrue($user->photos()->firstOrCreate(['name' => 'existing'])->is($existing)); + $this->assertTrue($user->photos()->updateOrCreate(['name' => 'existing'], ['name' => 'updated'])->is($existing)); + $this->assertSame('updated', $existing->fresh()->name); + + foreach ([ + $user->photos()->findOrNew(999), + $user->photos()->firstOrNew(['name' => 'a']), + ] as $new) { + $this->assertFalse($new->exists); + $this->assertSame(7, $new->imageable_id); + $this->assertSame(User::class, $new->imageable_type); + } + + foreach ([ + $user->photos()->firstOrCreate(['name' => 'b']), + $user->photos()->createOrFirst(['name' => 'c']), + $user->photos()->updateOrCreate(['name' => 'd']), + ] as $created) { + $this->assertTrue($created->exists); + $this->assertSame(7, $created->imageable_id); + $this->assertSame(User::class, $created->imageable_type); + } + } + + public function testFindOrReturnsTheModelOrTheCallbackResult(): void + { + $user = User::create(['id' => 1, 'email' => 'first@example.com']); + + $this->assertTrue($user->is(User::findOr(1, fn () => 'callback result'))); + $this->assertSame('first@example.com', User::findOr(1, ['email'], fn () => 'callback result')->email); + $this->assertNull(User::findOr(1, ['email'], fn () => 'callback result')->name); + $this->assertSame('callback result', User::findOr(2, fn () => 'callback result')); + $this->assertSame('callback result', User::findOr(2, ['email'], fn () => 'callback result')); + } + + #[TestWith([false])] + #[TestWith([true])] + public function testFindOrWithManyIdentifiersReturnsACollection(bool $useCollection): void + { + User::create(['id' => 1, 'email' => 'first@example.com']); + User::create(['id' => 2, 'email' => 'second@example.com']); + + $ids = $useCollection ? new Collection([1, 2]) : [1, 2]; + $found = User::findOr($ids, fn () => 'callback result'); + + $this->assertInstanceOf(Collection::class, $found); + $this->assertSame([1, 2], $found->modelKeys()); + + $found = User::findOr($ids, ['email'], fn () => 'callback result'); + + $this->assertInstanceOf(Collection::class, $found); + $this->assertSame(['first@example.com', 'second@example.com'], $found->pluck('email')->all()); + $this->assertNull($found->first()->name); + + $missing = $useCollection ? new Collection([1, 2, 3]) : [1, 2, 3]; + $this->assertSame('callback result', User::findOr($missing, fn () => 'callback result')); + + $empty = $useCollection ? new Collection : []; + $found = User::findOr($empty, fn () => 'callback result'); + + $this->assertInstanceOf(Collection::class, $found); + $this->assertCount(0, $found); + } + + public function testDestroyAcceptsVariousIdentifierShapes(): void + { + foreach ([1, 2, 3, 4, 5, 6, 7, 8] as $id) { + User::create(['id' => $id, 'email' => "user{$id}@example.com"]); + } + + $this->assertSame(3, User::destroy(1, 2, 3)); + $this->assertSame(1, User::destroy([4])); + $this->assertSame(1, User::destroy(new BaseCollection([5]))); + $this->assertSame(2, User::destroy(new Collection([ + User::find(6), + User::find(7), + ]))); + + $this->assertSame([8], User::pluck('id')->all()); + } + + public function testDestroyWithNoIdentifiersDeletesNothing(): void + { + User::create(['email' => 'taylorotwell@gmail.com']); + + $this->assertSame(0, User::destroy([])); + $this->assertSame(1, User::count()); + } + + public function testOnWriteConnectionFindsRecordsTheReplicaHasNotSeenYet(): void + { + $this->db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'read' => ['database' => ':memory:'], + 'write' => ['database' => ':memory:'], + ], 'replicated'); + + $connection = $this->connection('replicated'); + + foreach ([$connection->getPdo(), $connection->getReadPdo()] as $pdo) { + $pdo->exec('create table "users" ("id" integer primary key autoincrement not null, "email" varchar not null, "created_at" datetime null, "updated_at" datetime null)'); + } + + $connection->table('users')->insert(['email' => 'taylorotwell@gmail.com']); + + $this->assertNull(ReplicatedUser::find(1)); + $this->assertSame('taylorotwell@gmail.com', ReplicatedUser::onWriteConnection()->find(1)->email); + } + + public function testIncrementAndDecrementAreScopedToTheModelKey(): void + { + $counter = Counter::create(['foo' => 2]); + $other = Counter::create(['foo' => 2]); + + $counter->increment('foo', 3); + + $this->assertSame(5, $counter->foo); + $this->assertFalse($counter->isDirty()); + $this->assertSame(5, $counter->fresh()->foo); + $this->assertSame(2, $other->fresh()->foo); + + $counter->decrement('foo', 1); + + $this->assertSame(4, $counter->foo); + $this->assertSame(4, $counter->fresh()->foo); + $this->assertSame(2, $other->fresh()->foo); + } + + public function testIncrementAndDecrementEachAreScopedToTheModelKey(): void + { + $counter = Counter::create(['foo' => 2, 'bar' => 5]); + $other = Counter::create(['foo' => 2, 'bar' => 5]); + + $this->assertSame(1, $counter->incrementEach(['foo' => 1, 'bar' => 2])); + + $this->assertSame(3, $counter->foo); + $this->assertSame(7, $counter->bar); + $this->assertFalse($counter->isDirty()); + $this->assertSame(3, $counter->fresh()->foo); + $this->assertSame(7, $counter->fresh()->bar); + + $this->assertSame(1, $counter->decrementEach(['foo' => 3, 'bar' => 2])); + + $this->assertSame(0, $counter->foo); + $this->assertSame(5, $counter->bar); + $this->assertSame(0, $counter->fresh()->foo); + $this->assertSame(5, $counter->fresh()->bar); + + $this->assertSame(2, $other->fresh()->foo); + $this->assertSame(5, $other->fresh()->bar); + } + + public function testIncrementEachWithExtraColumns(): void + { + $counter = Counter::create(['foo' => 2]); + + $this->assertSame(1, $counter->incrementEach(['foo' => 5], ['name' => 'test'])); + + $this->assertSame(7, $counter->foo); + $this->assertSame('test', $counter->name); + $this->assertSame('test', $counter->fresh()->name); + $this->assertSame(7, $counter->fresh()->foo); + } + + public function testIncrementEachOnANonExistingModelUpdatesEveryRow(): void + { + Counter::create(['foo' => 1]); + Counter::create(['foo' => 2]); + + $this->assertSame(2, (new Counter)->incrementEach(['foo' => 1])); + + $this->assertSame([2, 3], Counter::orderBy('id')->pluck('foo')->all()); + } + + public function testIncrementAndDecrementFireModelEvents(): void + { + $counter = Counter::create(['foo' => 1]); + $events = $this->recordEvents(); + + $counter->increment('foo'); + $counter->decrement('foo'); + $counter->incrementEach(['foo' => 1]); + $counter->decrementEach(['foo' => 1]); + + $this->assertSame([ + 'eloquent.updating', 'eloquent.updated', + 'eloquent.updating', 'eloquent.updated', + 'eloquent.updating', 'eloquent.updated', + 'eloquent.updating', 'eloquent.updated', + ], $events->getArrayCopy()); + } + + public function testQuietIncrementAndDecrementDoNotFireModelEvents(): void + { + $counter = Counter::create(['foo' => 4, 'bar' => 4]); + $events = $this->recordEvents(); + + $counter->incrementQuietly('foo', 1); + $counter->decrementQuietly('foo', 2); + $counter->incrementEachQuietly(['bar' => 1]); + $counter->decrementEachQuietly(['bar' => 3]); + + $this->assertSame([], $events->getArrayCopy()); + $this->assertSame(3, $counter->foo); + $this->assertSame(2, $counter->bar); + $this->assertSame(3, $counter->fresh()->foo); + $this->assertSame(2, $counter->fresh()->bar); + $this->assertFalse($counter->isDirty()); + } + + public function testQuietIncrementAndDecrementWithExtraColumnsSyncTheStoredValues(): void + { + $counter = Counter::create(['foo' => 4, 'bar' => 4]); + $events = $this->recordEvents(); + + $counter->incrementQuietly('foo', 1, ['category' => 1]); + + $this->assertSame(5, $counter->foo); + $this->assertSame(1, $counter->category); + // Hypervel records extra values written by increments as original values. + $this->assertFalse($counter->isDirty('category')); + $this->assertFalse($counter->isDirty('foo')); + + $counter->decrementQuietly('foo', 1, ['category' => 2]); + + $this->assertSame(4, $counter->foo); + $this->assertSame(2, $counter->category); + $this->assertFalse($counter->isDirty()); + + $counter->decrementEachQuietly(['bar' => 1], ['category' => 3]); + + $this->assertSame(3, $counter->bar); + $this->assertSame(3, $counter->category); + $this->assertFalse($counter->isDirty('category')); + $this->assertSame([], $events->getArrayCopy()); + } + + public function testIncrementEachReturnsFalseWhenTheUpdatingEventIsCancelled(): void + { + $counter = Counter::create(['foo' => 1]); + + $events = new Dispatcher; + $events->listen('eloquent.updating: ' . Counter::class, fn () => false); + Eloquent::setEventDispatcher($events); + + $this->assertFalse($counter->incrementEach(['foo' => 1])); + + // Attributes are set before the event fires, matching increment() behavior. + // The in-memory value changes but the database is not updated. + $this->assertSame(2, $counter->foo); + Eloquent::unsetEventDispatcher(); + $this->assertSame(1, $counter->fresh()->foo); + } + + public function testUpdateOnlyWritesDirtyAttributesAndFiresEvents(): void + { + $counter = Counter::create(['foo' => 1, 'name' => 'taylor']); + $events = $this->recordEvents(); + + // Another process changes a column this model never touched... + $this->connection()->table('counters')->where('id', $counter->id)->update(['foo' => 99]); + + $counter->name = 'abigail'; + + $this->assertTrue($counter->save()); + $this->assertSame(['eloquent.saving', 'eloquent.updating', 'eloquent.updated', 'eloquent.saved'], $events->getArrayCopy()); + $this->assertSame('abigail', $counter->fresh()->name); + $this->assertSame(99, $counter->fresh()->foo); + } + + public function testUpdateUsesTheOriginalPrimaryKey(): void + { + $counter = Counter::create(['foo' => 1]); + $originalKey = $counter->id; + + $counter->id = 100; + $counter->foo = 2; + + $this->assertTrue($counter->save()); + $this->assertNull(Counter::find($originalKey)); + $this->assertSame(2, Counter::find(100)->foo); + } + + public function testUpdateDoesNotOverrideExplicitTimestamps(): void + { + $counter = Counter::create(['foo' => 1]); + + $counter->created_at = '2020-01-01 00:00:00'; + $counter->updated_at = '2020-01-02 00:00:00'; + $counter->save(); + + $counter = $counter->fresh(); + + $this->assertSame('2020-01-01 00:00:00', $counter->created_at->toDateTimeString()); + $this->assertSame('2020-01-02 00:00:00', $counter->updated_at->toDateTimeString()); + } + + public function testUpdateWithoutTimestampsLeavesTheUpdatedAtColumnAlone(): void + { + $counter = Counter::create(['foo' => 1]); + $counter->newQuery()->toBase()->update(['updated_at' => '2020-01-02 00:00:00']); + $counter = $counter->fresh(); + + $counter->timestamps = false; + $counter->name = 'taylor'; + $counter->save(); + + $this->assertSame('2020-01-02 00:00:00', $counter->fresh()->updated_at->toDateTimeString()); + $this->assertSame('taylor', $counter->fresh()->name); + } + + public function testDeleteRemovesTheModelOnly(): void + { + $counter = Counter::create(['foo' => 1]); + $other = Counter::create(['foo' => 2]); + + $counter->delete(); + + $this->assertFalse($counter->exists); + $this->assertNull(Counter::find($counter->id)); + $this->assertNotNull(Counter::find($other->id)); + } + + /** + * Record model events without their model-class suffix. + */ + protected function recordEvents(): ArrayObject + { + $log = new ArrayObject; + $events = new Dispatcher; + $events->listen('eloquent.*', function ($event) use ($log) { + $name = strstr($event, ':', true); + + if (! in_array($name, ['eloquent.booting', 'eloquent.booted'])) { + $log[] = $name; + } + }); + Eloquent::setEventDispatcher($events); + + return $log; + } + public function testConfiguredAttributesAreExcludedWhenReplicating(): void { $user = GeneratedUser::create([ @@ -2726,6 +3396,24 @@ public function testMultiLevelTouchingWorks(): void $this->assertTrue($future->isSameDay($user->fresh()->updated_at), 'It is not touching models related timestamps.'); } + public function testTouchingIsSkippedWhenTheOwnerDoesNotExist(): void + { + $before = CarbonImmutable::now(); + + $user = TouchingUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']); + $post = TouchingPost::create(['id' => 1, 'name' => 'Parent Post', 'user_id' => 1]); + + CarbonImmutable::setTestNow($future = $before->addDays(3)); + + // The comment points at a post that doesn't exist, so there is nothing to touch up the chain. + $comment = TouchingComment::create(['content' => 'Comment content', 'post_id' => 99]); + + $this->assertTrue($comment->exists); + $this->assertTrue($before->isSameDay($post->fresh()->updated_at)); + $this->assertTrue($before->isSameDay($user->fresh()->updated_at)); + $this->assertFalse($future->isSameDay($post->fresh()->updated_at)); + } + public function testDeletingChildModelTouchesParentTimestamps(): void { $before = CarbonImmutable::now(); @@ -3498,6 +4186,36 @@ class WithJSON extends Eloquent ]; } +class ReplicatedUser extends User +{ + protected UnitEnum|string|null $connection = 'replicated'; +} + +class StringableKey implements Stringable +{ + /** + * Create a stringable model key. + */ + public function __construct(protected string $value) + { + } + + /** + * Get the string key. + */ + public function __toString(): string + { + return $this->value; + } +} + +class Counter extends Eloquent +{ + protected ?string $table = 'counters'; + + protected array $guarded = []; +} + #[Refreshes('name')] class GeneratedUser extends Eloquent { diff --git a/tests/Database/DatabaseEloquentInverseRelationTest.php b/tests/Database/DatabaseEloquentInverseRelationTest.php index 07766b06c..c8f892cd8 100755 --- a/tests/Database/DatabaseEloquentInverseRelationTest.php +++ b/tests/Database/DatabaseEloquentInverseRelationTest.php @@ -15,27 +15,31 @@ use Hypervel\Database\SQLiteConnection; use Hypervel\Support\Stringable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionFunction; class DatabaseEloquentInverseRelationTest extends TestCase { + use VerifiesDoubles; + public function testBuilderCallbackIsNotAppliedWhenInverseRelationIsNotSet(): void { - $builder = m::mock(Builder::class); - $builder->expects('getModel')->andReturn(new HasInverseRelationRelatedStub); - $builder->shouldReceive('afterQuery')->never(); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->returns(new HasInverseRelationRelatedStub); + $builder->expects('afterQuery')->never(); new HasInverseRelationStub($builder, new HasInverseRelationParentStub); } public function testBuilderCallbackIsNotSetIfInverseRelationIsEmptyString(): void { - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(2)->andReturn(new HasInverseRelationRelatedStub); - $builder->shouldReceive('afterQuery')->never(); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(2)->returns(new HasInverseRelationRelatedStub); + $builder->expects('afterQuery')->never(); $this->expectException(RelationNotFoundException::class); @@ -44,9 +48,9 @@ public function testBuilderCallbackIsNotSetIfInverseRelationIsEmptyString(): voi public function testBuilderCallbackIsNotSetIfInverseRelationshipDoesNotExist(): void { - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(3)->andReturn(new HasInverseRelationRelatedStub); - $builder->shouldReceive('afterQuery')->never(); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(3)->returns(new HasInverseRelationRelatedStub); + $builder->expects('afterQuery')->never(); $this->expectException(RelationNotFoundException::class); @@ -55,9 +59,9 @@ public function testBuilderCallbackIsNotSetIfInverseRelationshipDoesNotExist(): public function testWithoutInverseMethodRemovesInverseRelation(): void { - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(2)->andReturn(new HasInverseRelationRelatedStub); - $builder->expects('afterQuery')->andReturnSelf(); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(2)->returns(new HasInverseRelationRelatedStub); + $builder->expects('afterQuery')->returns($builder); $relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub)); $this->assertNull($relation->getInverseRelationship()); @@ -73,27 +77,27 @@ public function testBuilderCallbackIsAppliedWhenInverseRelationIsSet(): void { $parent = new HasInverseRelationParentStub; - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(2)->andReturn(new HasInverseRelationRelatedStub); - $builder->expects('afterQuery')->withArgs(function (Closure $callback) use ($parent): bool { + $builder = Double::for(Builder::class); + $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(); return $relation instanceof HasInverseRelationStub && $relation->getParent() === $parent; - })->andReturnSelf(); + }))->returns($builder); (new HasInverseRelationStub($builder, $parent))->inverse('test'); } public function testBuilderCallbackAppliesInverseRelationToAllModelsInResult(): void { - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(2)->andReturn(new HasInverseRelationRelatedStub); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(2)->returns(new HasInverseRelationRelatedStub); // Capture the callback so that we can manually call it. $afterQuery = null; - $builder->expects('afterQuery')->withArgs(function (Closure $callback) use (&$afterQuery): bool { + $builder->expects('afterQuery')->with(Argument::satisfies(function (Closure $callback) use (&$afterQuery): bool { return (bool) $afterQuery = $callback; - })->andReturnSelf(); + }))->returns($builder); $parent = new HasInverseRelationParentStub; (new HasInverseRelationStub($builder, $parent))->inverse('test'); @@ -116,14 +120,14 @@ public function testBuilderCallbackAppliesInverseRelationToAllModelsInResult(): public function testInverseRelationIsNotSetIfInverseRelationIsUnset(): void { - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(2)->andReturn(new HasInverseRelationRelatedStub); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(2)->returns(new HasInverseRelationRelatedStub); // Capture the callback so that we can manually call it. $afterQuery = null; - $builder->expects('afterQuery')->withArgs(function (Closure $callback) use (&$afterQuery): bool { + $builder->expects('afterQuery')->with(Argument::satisfies(function (Closure $callback) use (&$afterQuery): bool { return (bool) $afterQuery = $callback; - })->andReturnSelf(); + }))->returns($builder); $parent = new HasInverseRelationParentStub; $relation = (new HasInverseRelationStub($builder, $parent)); @@ -154,8 +158,8 @@ public function testInverseRelationIsNotSetIfInverseRelationIsUnset(): void public function testProvidesPossibleInverseRelationBasedOnParent(): void { - $builder = m::mock(Builder::class); - $builder->shouldReceive('getModel')->andReturn(new HasInverseRelationRelatedStub); + $builder = Double::for(Builder::class); + $builder->allows('getModel')->returns(new HasInverseRelationRelatedStub); $relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub)); @@ -165,8 +169,8 @@ public function testProvidesPossibleInverseRelationBasedOnParent(): void public function testProvidesPossibleInverseRelationBasedOnForeignKey(): void { - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(2)->andReturn(new HasInverseRelationParentStub); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(2)->returns(new HasInverseRelationParentStub); $relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub, 'test_id')); @@ -175,8 +179,8 @@ public function testProvidesPossibleInverseRelationBasedOnForeignKey(): void public function testProvidesPossibleRecursiveRelationsIfRelatedIsTheSameClassAsParent(): void { - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(2)->andReturn(new HasInverseRelationParentStub); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(2)->returns(new HasInverseRelationParentStub); $relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub)); @@ -186,11 +190,11 @@ public function testProvidesPossibleRecursiveRelationsIfRelatedIsTheSameClassAsP #[DataProvider('guessedParentRelationsDataProvider')] public function testGuessesInverseRelationBasedOnParent($guessedRelation): void { - $related = m::mock(Model::class); - $related->shouldReceive('isRelation')->andReturnUsing(fn ($relation) => $relation === $guessedRelation); + $related = Double::for(Model::class); + $related->allows('isRelation')->resolves(fn ($relation) => $relation === $guessedRelation); - $builder = m::mock(Builder::class); - $builder->shouldReceive('getModel')->andReturn($related); + $builder = Double::for(Builder::class); + $builder->allows('getModel')->returns($related); $relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub)); @@ -199,11 +203,11 @@ public function testGuessesInverseRelationBasedOnParent($guessedRelation): void public function testGuessesPossibleInverseRelationBasedOnForeignKey(): void { - $related = m::mock(Model::class); - $related->expects('isRelation')->andReturnUsing(fn (string $relation): bool => $relation === 'test'); + $related = Double::for(Model::class); + $related->expects('isRelation')->resolves(fn (string $relation): bool => $relation === 'test'); - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(3)->andReturn($related); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(3)->returns($related); $relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub, 'test_id')); @@ -212,15 +216,15 @@ public function testGuessesPossibleInverseRelationBasedOnForeignKey(): void public function testGuessesRecursiveInverseRelationsIfRelatedIsSameClassAsParent(): void { - $related = m::mock(Model::class); - $related->expects('isRelation')->times(4)->andReturnUsing(fn (string $relation): bool => $relation === 'parent'); + $related = Double::for(Model::class); + $related->expects('isRelation')->times(4)->resolves(fn (string $relation): bool => $relation === 'parent'); - $parent = m::mock(Model::class); - $parent->expects('getForeignKey')->andReturn('recursive_parent_id'); - $parent->expects('getKeyName')->twice()->andReturn('id'); + $parent = Double::for(Model::class); + $parent->expects('getForeignKey')->returns('recursive_parent_id'); + $parent->expects('getKeyName')->times(2)->returns('id'); - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(6)->andReturn($related); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(6)->returns($related); $relation = (new HasInverseRelationStub($builder, $parent)); @@ -230,12 +234,12 @@ public function testGuessesRecursiveInverseRelationsIfRelatedIsSameClassAsParent #[DataProvider('guessedParentRelationsDataProvider')] public function testSetsGuessedInverseRelationBasedOnParent($guessedRelation): void { - $related = m::mock(Model::class); - $related->shouldReceive('isRelation')->andReturnUsing(fn ($relation) => $relation === $guessedRelation); + $related = Double::for(Model::class); + $related->allows('isRelation')->resolves(fn ($relation) => $relation === $guessedRelation); - $builder = m::mock(Builder::class); - $builder->shouldReceive('getModel')->andReturn($related); - $builder->expects('afterQuery')->andReturnSelf(); + $builder = Double::for(Builder::class); + $builder->allows('getModel')->returns($related); + $builder->expects('afterQuery')->returns($builder); $relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub))->inverse(); @@ -251,16 +255,16 @@ public static function guessedParentRelationsDataProvider() public function testSetsRecursiveInverseRelationsIfRelatedIsSameClassAsParent(): void { - $related = m::mock(Model::class); - $related->expects('isRelation')->times(5)->andReturnUsing(fn (string $relation): bool => $relation === 'parent'); + $related = Double::for(Model::class); + $related->expects('isRelation')->times(5)->resolves(fn (string $relation): bool => $relation === 'parent'); - $parent = m::mock(Model::class); - $parent->expects('getForeignKey')->andReturn('recursive_parent_id'); - $parent->expects('getKeyName')->twice()->andReturn('id'); + $parent = Double::for(Model::class); + $parent->expects('getForeignKey')->returns('recursive_parent_id'); + $parent->expects('getKeyName')->times(2)->returns('id'); - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(7)->andReturn($related); - $builder->expects('afterQuery')->andReturnSelf(); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(7)->returns($related); + $builder->expects('afterQuery')->returns($builder); $relation = (new HasInverseRelationStub($builder, $parent))->inverse(); @@ -269,12 +273,12 @@ public function testSetsRecursiveInverseRelationsIfRelatedIsSameClassAsParent(): public function testSetsGuessedInverseRelationBasedOnForeignKey(): void { - $related = m::mock(Model::class); - $related->expects('isRelation')->times(2)->andReturnUsing(fn (string $relation): bool => $relation === 'test'); + $related = Double::for(Model::class); + $related->expects('isRelation')->times(2)->resolves(fn (string $relation): bool => $relation === 'test'); - $builder = m::mock(Builder::class); - $builder->expects('getModel')->times(4)->andReturn($related); - $builder->expects('afterQuery')->andReturnSelf(); + $builder = Double::for(Builder::class); + $builder->expects('getModel')->times(4)->returns($related); + $builder->expects('afterQuery')->returns($builder); $relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub, 'test_id'))->inverse(); diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index 06c557e31..e1500293a 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -62,6 +62,7 @@ use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Database\Query\Grammars\PostgresGrammar; use Hypervel\Database\Query\Processors\Processor; +use Hypervel\Database\Schema\Builder as SchemaBuilder; use Hypervel\Database\SQLiteConnection; use Hypervel\Encryption\Encrypter as ConcreteEncrypter; use Hypervel\Events\Dispatcher as EventDispatcher; @@ -81,8 +82,9 @@ use Hypervel\Tests\Database\Fixtures\TestCast; use Hypervel\Tests\Database\Fixtures\TestValueObject; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; @@ -101,8 +103,7 @@ class DatabaseEloquentModelTest extends TestCase { use InteractsWithInMemoryConnection; use InteractsWithTime; - - protected $encrypter; + use VerifiesDoubles; public function testAttributeManipulation(): void { @@ -368,177 +369,6 @@ public function testDirtyOnCastedFluent(): void $this->assertTrue($model->isDirty('asFluentAttribute')); } - // public function testDirtyOnCastedEncryptedCollection() - // { - // $this->encrypter = m::mock(Encrypter::class); - // Crypt::swap($this->encrypter); - // Model::$encrypter = null; - - // $this->encrypter->expects('encryptString') - // ->with('{"foo":"bar"}') - // ->andReturn('encrypted-value'); - - // $this->encrypter->expects('decryptString') - // ->with('encrypted-value') - // ->andReturn('{"foo": "bar"}'); - - // $this->encrypter->expects('encryptString') - // ->with('{"foo":"baz"}') - // ->andReturn('new-encrypted-value'); - - // $this->encrypter->expects('decrypt') - // ->with('encrypted-value', false) - // ->andReturn('{"foo": "bar"}'); - - // $this->encrypter->expects('decrypt') - // ->with('new-encrypted-value', false) - // ->andReturn('{"foo":"baz"}'); - - // $model = new EloquentModelCastingStub; - // $model->setRawAttributes([ - // 'asEncryptedCollectionAttribute' => 'encrypted-value', - // ]); - // $model->syncOriginal(); - - // $this->assertInstanceOf(BaseCollection::class, $model->asEncryptedCollectionAttribute); - // $this->assertFalse($model->isDirty('asEncryptedCollectionAttribute')); - - // $model->asEncryptedCollectionAttribute = ['foo' => 'bar']; - // $this->assertFalse($model->isDirty('asEncryptedCollectionAttribute')); - - // $model->asEncryptedCollectionAttribute = ['foo' => 'baz']; - // $this->assertTrue($model->isDirty('asEncryptedCollectionAttribute')); - // } - - // public function testDirtyOnCastedEncryptedCustomCollection() - // { - // $this->encrypter = m::mock(Encrypter::class); - // Crypt::swap($this->encrypter); - // Model::$encrypter = null; - - // $this->encrypter->expects('encryptString') - // ->twice() - // ->with('{"foo":"bar"}') - // ->andReturn('encrypted-custom-value'); - - // $this->encrypter->expects('decryptString') - // ->with('encrypted-custom-value') - // ->andReturn('{"foo": "bar"}'); - - // $this->encrypter->expects('encryptString') - // ->with('{"foo":"baz"}') - // ->andReturn('new-encrypted-custom-value'); - - // $this->encrypter->expects('decrypt') - // ->with('encrypted-custom-value', false) - // ->andReturn('{"foo": "bar"}'); - - // $this->encrypter->expects('decrypt') - // ->with('new-encrypted-custom-value', false) - // ->andReturn('{"foo":"baz"}'); - - // $model = new EloquentModelCastingStub; - // $model->setRawAttributes([ - // 'asEncryptedCustomCollectionAttribute' => 'encrypted-custom-value', - // ]); - // $model->syncOriginal(); - - // $this->assertInstanceOf(CustomCollection::class, $model->asEncryptedCustomCollectionAttribute); - // $this->assertFalse($model->isDirty('asEncryptedCustomCollectionAttribute')); - - // $model->asEncryptedCustomCollectionAttribute = ['foo' => 'bar']; - // $this->assertFalse($model->isDirty('asEncryptedCustomCollectionAttribute')); - - // $model->asEncryptedCustomCollectionAttribute = ['foo' => 'baz']; - // $this->assertTrue($model->isDirty('asEncryptedCustomCollectionAttribute')); - // } - - // public function testDirtyOnCastedEncryptedCustomCollectionAsArray() - // { - // $this->encrypter = m::mock(Encrypter::class); - // Crypt::swap($this->encrypter); - // Model::$encrypter = null; - - // $this->encrypter->expects('encryptString') - // ->twice() - // ->with('{"foo":"bar"}') - // ->andReturn('encrypted-custom-value'); - - // $this->encrypter->expects('decryptString') - // ->with('encrypted-custom-value') - // ->andReturn('{"foo": "bar"}'); - - // $this->encrypter->expects('encryptString') - // ->with('{"foo":"baz"}') - // ->andReturn('new-encrypted-custom-value'); - - // $this->encrypter->expects('decrypt') - // ->with('encrypted-custom-value', false) - // ->andReturn('{"foo": "bar"}'); - - // $this->encrypter->expects('decrypt') - // ->with('new-encrypted-custom-value', false) - // ->andReturn('{"foo":"baz"}'); - - // $model = new EloquentModelCastingStub; - // $model->setRawAttributes([ - // 'asEncryptedCustomCollectionAsArrayAttribute' => 'encrypted-custom-value', - // ]); - // $model->syncOriginal(); - - // $this->assertInstanceOf(CustomCollection::class, $model->asEncryptedCustomCollectionAsArrayAttribute); - // $this->assertFalse($model->isDirty('asEncryptedCustomCollectionAsArrayAttribute')); - - // $model->asEncryptedCustomCollectionAsArrayAttribute = ['foo' => 'bar']; - // $this->assertFalse($model->isDirty('asEncryptedCustomCollectionAsArrayAttribute')); - - // $model->asEncryptedCustomCollectionAsArrayAttribute = ['foo' => 'baz']; - // $this->assertTrue($model->isDirty('asEncryptedCustomCollectionAsArrayAttribute')); - // } - - // public function testDirtyOnCastedEncryptedArrayObject() - // { - // $this->encrypter = m::mock(Encrypter::class); - // Crypt::swap($this->encrypter); - // Model::$encrypter = null; - - // $this->encrypter->expects('encryptString') - // ->twice() - // ->with('{"foo":"bar"}') - // ->andReturn('encrypted-value'); - - // $this->encrypter->expects('decryptString') - // ->with('encrypted-value') - // ->andReturn('{"foo": "bar"}'); - - // $this->encrypter->expects('encryptString') - // ->with('{"foo":"baz"}') - // ->andReturn('new-encrypted-value'); - - // $this->encrypter->expects('decrypt') - // ->with('encrypted-value', false) - // ->andReturn('{"foo": "bar"}'); - - // $this->encrypter->expects('decrypt') - // ->with('new-encrypted-value', false) - // ->andReturn('{"foo":"baz"}'); - - // $model = new EloquentModelCastingStub; - // $model->setRawAttributes([ - // 'asEncryptedArrayObjectAttribute' => 'encrypted-value', - // ]); - // $model->syncOriginal(); - - // $this->assertInstanceOf(ArrayObject::class, $model->asEncryptedArrayObjectAttribute); - // $this->assertFalse($model->isDirty('asEncryptedArrayObjectAttribute')); - - // $model->asEncryptedArrayObjectAttribute = ['foo' => 'bar']; - // $this->assertFalse($model->isDirty('asEncryptedArrayObjectAttribute')); - - // $model->asEncryptedArrayObjectAttribute = ['foo' => 'baz']; - // $this->assertTrue($model->isDirty('asEncryptedArrayObjectAttribute')); - // } - public function testDirtyOnEnumCollectionObject(): void { $model = new CastingStub; @@ -752,27 +582,19 @@ public function testForceCreateMethodSavesNewModelWithGuardedAttributes(): void $this->assertEquals(21, $model->id); } - public function testFindMethodUseWritePdo(): void - { - FindWithWritePdoStub::onWriteConnection()->find(1); - } - public function testRefreshForUpdateUsesLockForUpdate(): void { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes,load]'); + $model = $this->getMockBuilder(ModelStub::class)->onlyMethods(['newQueryWithoutScopes', 'load'])->getMock(); $model->exists = true; $model->setRawAttributes(['id' => 1, 'name' => 'Taylor'], true); $freshModel = new ModelStub; $freshModel->setRawAttributes(['id' => 1, 'name' => 'Abigail']); - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->andReturn($query); - $query->expects('lockForUpdate')->andReturnSelf(); - $query->expects('where')->with('id', '=', 1)->andReturnSelf(); - $query->expects('useWritePdo')->andReturnSelf(); - $query->expects('firstOrFail')->andReturn($freshModel); - $model->expects('load')->with([])->andReturnSelf(); + $query = Double::for($this->newBuilder()->setModel($model))->passthru(); + $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query); + $query->expects('firstOrFail')->returns($freshModel); + $model->expects($this->once())->method('load')->with([])->willReturnSelf(); $result = $model->refreshForUpdate(); @@ -780,42 +602,10 @@ public function testRefreshForUpdateUsesLockForUpdate(): void $this->assertSame('Abigail', $model->name); $this->assertEmpty($model->getDirty()); $this->assertSame('Abigail', $model->getOriginal('name')); - } - - public function testDestroyMethodCallsQueryBuilderCorrectly(): void - { - DestroyStub::destroy(1, 2, 3); - } - - public function testDestroyMethodCallsQueryBuilderCorrectlyWithCollection(): void - { - DestroyStub::destroy(new BaseCollection([1, 2, 3])); - } - - public function testDestroyMethodCallsQueryBuilderCorrectlyWithEloquentCollection(): void - { - DestroyStub::destroy(new Collection([ - new DestroyStub(['id' => 1]), - new DestroyStub(['id' => 2]), - new DestroyStub(['id' => 3]), - ])); - } - - public function testDestroyMethodCallsQueryBuilderCorrectlyWithMultipleArgs(): void - { - DestroyStub::destroy(1, 2, 3); - } - - public function testDestroyMethodCallsQueryBuilderCorrectlyWithEmptyIds(): void - { - $count = EmptyDestroyStub::destroy([]); - $this->assertSame(0, $count); - } - - public function testWithMethodCallsQueryBuilderCorrectly(): void - { - $result = WithStub::with('foo', 'bar'); - $this->assertInstanceOf(Builder::class, $result); + $this->assertTrue($query->getQuery()->lock); + $this->assertTrue($query->getQuery()->useWritePdo); + $this->assertSame('select * from "stub" where "id" = ?', $query->toSql()); + $this->assertSame([1], $query->getBindings()); } public function testWithoutMethodRemovesEagerLoadedRelationshipCorrectly(): void @@ -835,10 +625,13 @@ public function testWithOnlyMethodLoadsRelationshipCorrectly(): void $this->assertArrayNotHasKey('foo', $instance->getEagerLoads()); } - public function testEagerLoadingWithColumns(): void + #[TestWith([false])] + #[TestWith([true])] + public function testEagerLoadingWithColumns(bool $useArray): void { - $model = new WithoutRelationStub; - $instance = $model->newInstance()->newQuery()->with('foo:bar,baz', 'hadi'); + $instance = $useArray + ? WithoutRelationStub::with(['foo:bar,baz', 'hadi']) + : WithoutRelationStub::with('foo:bar,baz', 'hadi'); $this->assertNotNull($instance->getEagerLoads()['hadi']); $this->assertNotNull($instance->getEagerLoads()['foo']); $closure = $instance->getEagerLoads()['foo']; @@ -875,50 +668,6 @@ public function testWithWhereHasWorksInNestedQuery(): void $this->assertSame('select "diaa", "fares"', $builder->toSql()); } - public function testWithMethodCallsQueryBuilderCorrectlyWithArray(): void - { - $result = WithStub::with(['foo', 'bar']); - $this->assertInstanceOf(Builder::class, $result); - } - - public function testUpdateProcess(): void - { - $model = $this->getMockBuilder(ModelStub::class)->onlyMethods(['newModelQuery', 'updateTimestamps'])->getMock(); - $query = m::mock(Builder::class); - $query->expects('where')->with('id', '=', 1); - $query->expects('update')->with(['name' => 'taylor'])->andReturn(1); - $model->expects($this->once())->method('newModelQuery')->willReturn($query); - $model->expects($this->once())->method('updateTimestamps'); - $events = $this->recordEvents(); - - $model->id = 1; - $model->foo = 'bar'; - // make sure foo isn't synced so we can test that dirty attributes only are updated - $model->syncOriginal(); - $model->name = 'taylor'; - $model->exists = true; - $this->assertTrue($model->save()); - $this->assertSame(['eloquent.saving', 'eloquent.updating', 'eloquent.updated', 'eloquent.saved'], $events->getArrayCopy()); - } - - public function testUpdateProcessDoesntOverrideTimestamps(): void - { - $model = $this->getMockBuilder(ModelStub::class)->onlyMethods(['newModelQuery'])->getMock(); - $query = m::mock(Builder::class); - $query->expects('where')->with('id', '=', 1); - $query->expects('update')->with(['created_at' => 'foo', 'updated_at' => 'bar'])->andReturn(1); - $model->expects($this->once())->method('newModelQuery')->willReturn($query); - $events = $this->recordEvents(); - - $model->id = 1; - $model->syncOriginal(); - $model->created_at = 'foo'; - $model->updated_at = 'bar'; - $model->exists = true; - $this->assertTrue($model->save()); - $this->assertSame(['eloquent.saving', 'eloquent.updating', 'eloquent.updated', 'eloquent.saved'], $events->getArrayCopy()); - } - public function testSaveIsCanceledIfSavingEventReturnsFalse(): void { $model = $this->getMockBuilder(ModelStub::class)->onlyMethods(['newModelQuery'])->getMock(); @@ -959,44 +708,6 @@ public function testEventsCanBeFiredWithCustomEventObjects(): void $this->assertFalse($model->save()); } - public function testUpdateProcessWithoutTimestamps(): void - { - $model = $this->getMockBuilder(EventObjectStub::class)->onlyMethods(['newModelQuery', 'updateTimestamps', 'fireModelEvent'])->getMock(); - $model->timestamps = false; - $query = m::mock(Builder::class); - $query->expects('where')->with('id', '=', 1); - $query->expects('update')->with(['name' => 'taylor'])->andReturn(1); - $model->expects($this->once())->method('newModelQuery')->willReturn($query); - $model->expects($this->never())->method('updateTimestamps'); - $model->expects($this->exactly(4))->method('fireModelEvent')->willReturn(true); - - $model->id = 1; - $model->syncOriginal(); - $model->name = 'taylor'; - $model->exists = true; - $this->assertTrue($model->save()); - } - - public function testUpdateUsesOldPrimaryKey(): void - { - $model = $this->getMockBuilder(ModelStub::class)->onlyMethods(['newModelQuery', 'updateTimestamps'])->getMock(); - $query = m::mock(Builder::class); - $query->expects('where')->with('id', '=', 1); - $query->expects('update')->with(['id' => 2, 'foo' => 'bar'])->andReturn(1); - $model->expects($this->once())->method('newModelQuery')->willReturn($query); - $model->expects($this->once())->method('updateTimestamps'); - $events = $this->recordEvents(); - - $model->id = 1; - $model->syncOriginal(); - $model->id = 2; - $model->foo = 'bar'; - $model->exists = true; - - $this->assertTrue($model->save()); - $this->assertSame(['eloquent.saving', 'eloquent.updating', 'eloquent.updated', 'eloquent.saved'], $events->getArrayCopy()); - } - public function testTimestampsAreReturnedAsObjects(): void { $model = new class extends DateModelStub { @@ -1153,18 +864,18 @@ public function testInsertProcess(): void #[TestWith([['name' => 'taylor'], 'insert into "stub" ("name") values (?)', ['taylor']])] public function testNonIncrementingModelInsertsOneRow(array $attributes, string $sql, array $bindings): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('getWritableName')->andReturn('testing'); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); + $connection->allows('getWritableName')->returns('testing'); $grammar = new Grammar($connection); $processor = new Processor; - $connection->shouldReceive('query')->andReturnUsing( + $connection->allows('query')->resolves( fn () => new BaseBuilder($connection, $grammar, $processor) ); - $connection->expects('insert')->with($sql, $bindings)->andReturnTrue(); + $connection->expects('insert')->with($sql, $bindings)->returns(true); - Model::setConnectionResolver($resolver = m::mock(ConnectionResolverInterface::class)); - $resolver->shouldReceive('connection')->andReturn($connection); + Model::setConnectionResolver($resolver = Double::for(ConnectionResolverInterface::class)); + $resolver->allows('connection')->returns($connection); $model = new class extends ModelStub { public bool $incrementing = false; @@ -1186,8 +897,9 @@ public function testNonIncrementingModelWithoutAttributesDoesNotInsert(): void $model->setConnection('testing'); $model->setIncrementing(false); $model->timestamps = false; - $query = m::mock(Builder::class); - $query->shouldNotReceive('insert'); + $baseQuery = Double::for(BaseBuilder::class); + $baseQuery->expects('insert')->never(); + $query = new Builder($baseQuery); $model->expects($this->once())->method('newModelQuery')->willReturn($query); $this->assertTrue($model->save()); @@ -1281,20 +993,20 @@ 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 = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('getWritableName')->andReturn('testing'); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); + $connection->allows('getWritableName')->returns('testing'); $grammar = new PostgresGrammar($connection); $processor = new Processor; - $connection->shouldReceive('query')->andReturnUsing( + $connection->allows('query')->resolves( fn () => new BaseBuilder($connection, $grammar, $processor) ); $connection->expects('selectFromWriteConnection') - ->with($sql, $bindings)->andReturn([(object) ['id' => 1, ...$attributes]]); + ->with($sql, $bindings)->returns([(object) ['id' => 1, ...$attributes]]); $connection->expects('recordsHaveBeenModified')->with(true); - Model::setConnectionResolver($resolver = m::mock(ConnectionResolverInterface::class)); - $resolver->shouldReceive('connection')->andReturn($connection); + Model::setConnectionResolver($resolver = Double::for(ConnectionResolverInterface::class)); + $resolver->allows('connection')->returns($connection); $model = new class($attributes) extends ModelStub { public bool $timestamps = false; @@ -1321,32 +1033,19 @@ public function testInsertOrIgnoreThrowsWithoutAttributes(): void $model = $this->getMockBuilder(ModelStub::class) ->onlyMethods(['newModelQuery', 'updateTimestamps']) ->getMock(); - $query = m::mock(Builder::class); + $query = Double::for(Builder::class); $model->expects($this->once())->method('newModelQuery')->willReturn($query); $model->expects($this->once())->method('updateTimestamps'); - $model::setEventDispatcher($events = m::mock(Dispatcher::class)); - $events->expects('until')->with('eloquent.saving: ' . get_class($model), $model)->andReturn(true); - $events->expects('until')->with('eloquent.creating: ' . get_class($model), $model)->andReturn(true); + $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); $this->expectExceptionObject(new LogicException('Cannot use saveOrIgnore on a model without attributes.')); $model->saveOrIgnore(); } - public function testDeleteProperlyDeletesModel(): void - { - $model = $this->getMockBuilder(Model::class)->onlyMethods(['newModelQuery', 'updateTimestamps', 'touchOwners'])->getMock(); - $query = m::mock(Builder::class); - $query->expects('where')->with('id', '=', 1)->andReturn($query); - $query->expects('delete'); - $model->expects($this->once())->method('newModelQuery')->willReturn($query); - $model->expects($this->once())->method('touchOwners'); - $model->exists = true; - $model->id = 1; - $model->delete(); - } - public function testPushNoRelations(): void { $this->newStubConnection(); @@ -1489,7 +1188,7 @@ public function testConnectionManagement(): void #[TestWith([ConnectionNameBacked::Foo])] public function testConnectionEnums(string|UnitEnum $connectionName): void { - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); ModelStub::setConnectionResolver($resolver); $model = new ModelStub; @@ -1497,8 +1196,8 @@ public function testConnectionEnums(string|UnitEnum $connectionName): void $this->assertEquals($retval, $model); $this->assertSame('Foo', $model->getConnectionName()); - $mockConnection = m::mock(Connection::class); - $resolver->expects('connection')->with('Foo')->andReturn($mockConnection); + $mockConnection = Double::for(Connection::class); + $resolver->expects('connection')->with('Foo')->returns($mockConnection); $this->assertSame($mockConnection, $model->getConnection()); } @@ -2415,11 +2114,13 @@ public function testGuarded(): void { $model = new ModelStub; - $resolver = m::mock(Resolver::class); + $resolver = Double::for(Resolver::class); ModelStub::setConnectionResolver($resolver); - $connection = m::mock(Connection::class); - $resolver->shouldReceive('connection')->andReturn($connection); - $connection->shouldReceive('getSchemaBuilder->getColumnListing')->andReturn(['name', 'age', 'foo']); + $connection = Double::for(Connection::class); + $resolver->allows('connection')->returns($connection); + $schema = Double::for(SchemaBuilder::class); + $schema->expects('getColumnListing')->returns(['name', 'age', 'foo']); + $connection->expects('getSchemaBuilder')->returns($schema); $model->guard(['name', 'age']); $model->fill(['name' => 'foo', 'age' => 'bar', 'foo' => 'bar']); @@ -2445,12 +2146,6 @@ public function testGuardedWithFillableConfig(): void $model = new ModelStub; $model::unguard(); - $resolver = m::mock(Resolver::class); - ModelStub::setConnectionResolver($resolver); - $connection = m::mock(Connection::class); - $resolver->shouldReceive('connection')->andReturn($connection); - $connection->shouldReceive('getSchemaBuilder->getColumnListing')->andReturn(['name', 'age', 'foo']); - $model->guard([]); $model->fillable(['name']); $model->fill(['name' => 'Leto Atreides', 'age' => 51]); @@ -2465,11 +2160,13 @@ public function testGuardedWithFillableConfig(): void public function testUsesOverriddenHandlerWhenDiscardingAttributes(): void { - $resolver = m::mock(Resolver::class); + $resolver = Double::for(Resolver::class); ModelStub::setConnectionResolver($resolver); - $connection = m::mock(Connection::class); - $resolver->shouldReceive('connection')->andReturn($connection); - $connection->shouldReceive('getSchemaBuilder->getColumnListing')->andReturn(['name', 'age', 'foo']); + $connection = Double::for(Connection::class); + $resolver->allows('connection')->returns($connection); + $schema = Double::for(SchemaBuilder::class); + $schema->expects('getColumnListing')->returns(['name', 'age', 'foo']); + $connection->expects('getSchemaBuilder')->returns($schema); Model::preventSilentlyDiscardingAttributes(); @@ -2920,11 +2617,11 @@ public function testCloneModelMakesAFreshCopyOfTheModelWhenModelHasUlid(): void public function testModelObserversCanBeAttachedToModels(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $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'); - $events->shouldReceive('forget'); + $events->allows('forget'); ModelStub::setEventDispatcher($events); ModelStub::observe(new TestObserverStub); ModelStub::flushEventListeners(); @@ -2932,11 +2629,11 @@ public function testModelObserversCanBeAttachedToModels(): void public function testModelObserversCanBeAttachedToModelsWithString(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $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'); - $events->shouldReceive('forget'); + $events->allows('forget'); ModelStub::setEventDispatcher($events); ModelStub::observe(TestObserverStub::class); ModelStub::flushEventListeners(); @@ -2944,11 +2641,11 @@ public function testModelObserversCanBeAttachedToModelsWithString(): void public function testModelObserversCanBeAttachedToModelsThroughAnArray(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $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'); - $events->shouldReceive('forget'); + $events->allows('forget'); ModelStub::setEventDispatcher($events); ModelStub::observe([TestObserverStub::class]); ModelStub::flushEventListeners(); @@ -2956,29 +2653,29 @@ public function testModelObserversCanBeAttachedToModelsThroughAnArray(): void public function testModelObserversCanBeAttachedToModelsWithStringUsingAttribute(): void { - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class); $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'); - $events->shouldReceive('forget'); + $events->allows('forget'); ModelWithObserveAttributeStub::setEventDispatcher($events); ModelWithObserveAttributeStub::flushEventListeners(); } public function testModelObserversCanBeAttachedToModelsThroughAnArrayUsingAttribute(): void { - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class); $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'); - $events->shouldReceive('forget'); + $events->allows('forget'); ModelWithObserveAttributeUsingArrayStub::setEventDispatcher($events); ModelWithObserveAttributeUsingArrayStub::flushEventListeners(); } public function testModelObserversCanBeAttachedToModelsThroughAttributesOnParentClasses(): void { - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class); $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'); @@ -2986,7 +2683,7 @@ public function testModelObserversCanBeAttachedToModelsThroughAttributesOnParent $events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelWithObserveAttributeGrandchildStub', TestAnotherObserverStub::class . '@saved'); $events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelWithObserveAttributeGrandchildStub', TestThirdObserverStub::class . '@creating'); $events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelWithObserveAttributeGrandchildStub', TestThirdObserverStub::class . '@saved'); - $events->shouldReceive('forget'); + $events->allows('forget'); ModelWithObserveAttributeGrandchildStub::setEventDispatcher($events); ModelWithObserveAttributeGrandchildStub::flushEventListeners(); } @@ -3005,8 +2702,8 @@ public function testThrowExceptionOnAttachingNotExistsModelObserversThroughAnArr public function testModelObserversCanBeAttachedToModelsThroughCallingObserveMethodOnlyOnce(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $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'); ModelStub::setEventDispatcher($events); @@ -3014,7 +2711,7 @@ public function testModelObserversCanBeAttachedToModelsThroughCallingObserveMeth $events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestAnotherObserverStub::class . '@creating'); $events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestAnotherObserverStub::class . '@saved'); - $events->shouldReceive('forget'); + $events->allows('forget'); ModelStub::observe([ TestObserverStub::class, @@ -3029,13 +2726,18 @@ public function testWithoutEventDispatcher(): void // Boot the model before the dispatcher is set so booting events aren't dispatched. new SaveStub; - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class); $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); - $events->shouldNotReceive('until'); - $events->shouldNotReceive('dispatch'); - $events->shouldReceive('forget'); + $dispatched = []; + $events->allows('until')->resolves(function (...$arguments) use (&$dispatched): void { + $dispatched[] = ['until', ...$arguments]; + }); + $events->allows('dispatch')->resolves(function (...$arguments) use (&$dispatched): void { + $dispatched[] = ['dispatch', ...$arguments]; + }); + $events->allows('forget'); SaveStub::observe(TestObserverStub::class); $model = SaveStub::withoutEvents(function (): SaveStub { @@ -3050,12 +2752,16 @@ public function testWithoutEventDispatcher(): void $model->save(); }); - $events->expects('until')->with('eloquent.saving: Hypervel\Tests\Database\DatabaseEloquentModelTest\SaveStub', $model); - $events->expects('dispatch')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\SaveStub', $model); + $this->assertSame([], $dispatched); $model->last_name = 'Otwell'; $model->save(); + $this->assertSame([ + ['until', 'eloquent.saving: ' . SaveStub::class, $model], + ['dispatch', 'eloquent.saved: ' . SaveStub::class, $model], + ], $dispatched); + SaveStub::flushEventListeners(); } @@ -3314,154 +3020,35 @@ public function testReplicateQuietlyCreatesANewModelInstanceWithSameAttributeVal $this->assertSame([], $events->getArrayCopy()); } - public function testIncrementOnExistingModelCallsQueryAndSetsAttribute(): void - { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - $model->foo = 2; - - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->times(2)->andReturn($query); - $query->expects('where')->times(2)->andReturnSelf(); - $query->expects('increment')->times(2)->andReturn(1); - - // hmm - $model->publicIncrement('foo', 1); - $this->assertFalse($model->isDirty()); - - $model->publicIncrement('foo', 1, ['category' => 1]); - $this->assertEquals(4, $model->foo); - $this->assertEquals(1, $model->category); - $this->assertFalse($model->isDirty('category')); - } - - public function testIncrementQuietlyOnExistingModelCallsQueryAndSetsAttributeAndIsQuiet(): void - { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - $model->foo = 2; - - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->times(2)->andReturn($query); - $query->expects('where')->times(2)->andReturnSelf(); - $query->expects('increment')->times(2)->andReturn(1); - - $events = $this->recordEvents(); - - $model->publicIncrementQuietly('foo', 1); - $this->assertFalse($model->isDirty()); - - $model->publicIncrementQuietly('foo', 1, ['category' => 1]); - $this->assertEquals(4, $model->foo); - $this->assertEquals(1, $model->category); - $this->assertFalse($model->isDirty('category')); - $this->assertSame([], $events->getArrayCopy()); - } - - public function testDecrementQuietlyOnExistingModelCallsQueryAndSetsAttributeAndIsQuiet(): void - { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - $model->foo = 4; - - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->times(2)->andReturn($query); - $query->expects('where')->times(2)->andReturnSelf(); - $query->expects('decrement')->times(2)->andReturn(1); - - $events = $this->recordEvents(); - - $model->publicDecrementQuietly('foo', 1); - $this->assertFalse($model->isDirty()); - - $model->publicDecrementQuietly('foo', 1, ['category' => 1]); - $this->assertEquals(2, $model->foo); - $this->assertEquals(1, $model->category); - $this->assertFalse($model->isDirty('category')); - $this->assertSame([], $events->getArrayCopy()); - } - public function testIncrementReturnsFalseWhenUpdatingEventIsCancelled(): void { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); + $model = Double::for(new ModelStub)->passthru(); $model->exists = true; $model->foo = 1; - $model->shouldNotReceive('newQueryWithoutScopes'); + $model->expects('newQueryWithoutScopes')->never(); - $model->setEventDispatcher($events = m::mock(Dispatcher::class)); + $model->setEventDispatcher($events = Double::for(Dispatcher::class)); $events->expects('until') ->with('eloquent.updating: ' . get_class($model), $model) - ->andReturn(false); + ->returns(false); $this->assertFalse($model->publicIncrement('foo')); $this->assertSame(2, $model->foo); } - public function testIncrementEachOnExistingModelScopesQueryToModelKey(): void - { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - $model->foo = 2; - $model->bar = 5; - - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->andReturn($query); - $query->expects('where')->with('id', '=', 1)->andReturnSelf(); - $query->expects('incrementEach') - ->with(['foo' => 1, 'bar' => 2], []) - ->andReturn(1); - - $result = $model->publicIncrementEach(['foo' => 1, 'bar' => 2]); - - $this->assertSame(1, $result); - $this->assertSame(3, $model->foo); - $this->assertSame(7, $model->bar); - } - - public function testDecrementEachOnExistingModelScopesQueryToModelKey(): void - { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - $model->foo = 10; - $model->bar = 5; - - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->andReturn($query); - $query->expects('where')->with('id', '=', 1)->andReturnSelf(); - $query->expects('decrementEach') - ->with(['foo' => 3, 'bar' => 2], []) - ->andReturn(1); - - $result = $model->publicDecrementEach(['foo' => 3, 'bar' => 2]); - - $this->assertSame(1, $result); - $this->assertSame(7, $model->foo); - $this->assertSame(3, $model->bar); - } - public function testIncrementEachQuietlyOnExistingModelCallsQueryAndSetsAttributeAndIsQuiet(): void { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); + $model = Double::for(new ModelStub)->passthru(); $model->exists = true; $model->id = 1; $model->syncOriginalAttribute('id'); $model->foo = 2; $model->bar = 5; - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->times(2)->andReturn($query); - $query->expects('where')->times(2)->andReturnSelf(); - $query->expects('incrementEach')->times(2)->andReturn(1); + $query = Double::for(Builder::class); + $model->expects('newQueryWithoutScopes')->times(2)->returns($query); + $query->expects('where')->times(2)->returns($query); + $query->expects('incrementEach')->times(2)->returns(1); $events = $this->recordEvents(); @@ -3481,17 +3068,17 @@ public function testIncrementEachQuietlyOnExistingModelCallsQueryAndSetsAttribut public function testDecrementEachQuietlyOnExistingModelCallsQueryAndSetsAttributeAndIsQuiet(): void { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); + $model = Double::for(new ModelStub)->passthru(); $model->exists = true; $model->id = 1; $model->syncOriginalAttribute('id'); $model->foo = 10; $model->bar = 5; - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->times(2)->andReturn($query); - $query->expects('where')->times(2)->andReturnSelf(); - $query->expects('decrementEach')->times(2)->andReturn(1); + $query = Double::for(Builder::class); + $model->expects('newQueryWithoutScopes')->times(2)->returns($query); + $query->expects('where')->times(2)->returns($query); + $query->expects('decrementEach')->times(2)->returns(1); $events = $this->recordEvents(); @@ -3509,156 +3096,6 @@ public function testDecrementEachQuietlyOnExistingModelCallsQueryAndSetsAttribut $this->assertSame([], $events->getArrayCopy()); } - public function testIncrementEachQuietlyCanBeCalledDynamicallyOnModelInstance(): void - { - $query = m::mock(Builder::class); - $query->expects('where')->with('id', '=', 1)->andReturnSelf(); - $query->expects('incrementEach') - ->with(['foo' => 1, 'bar' => 2], []) - ->andReturn(1); - - $model = new DynamicIncrementEachStub($query, ['foo' => 2, 'bar' => 5]); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - - // Called dynamically (the method is protected) so it routes through Model::__call. - $model->incrementEachQuietly(['foo' => 1, 'bar' => 2]); - - $this->assertSame(3, $model->foo); - $this->assertSame(7, $model->bar); - } - - public function testDecrementEachQuietlyCanBeCalledDynamicallyOnModelInstance(): void - { - $query = m::mock(Builder::class); - $query->expects('where')->with('id', '=', 1)->andReturnSelf(); - $query->expects('decrementEach') - ->with(['foo' => 1, 'bar' => 2], []) - ->andReturn(1); - - $model = new DynamicIncrementEachStub($query, ['foo' => 5, 'bar' => 10]); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - - // Called dynamically (the method is protected) so it routes through Model::__call. - $model->decrementEachQuietly(['foo' => 1, 'bar' => 2]); - - $this->assertSame(4, $model->foo); - $this->assertSame(8, $model->bar); - } - - public function testIncrementEachWithExtraColumnsOnExistingModel(): void - { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - $model->foo = 2; - - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->andReturn($query); - $query->expects('where')->with('id', '=', 1)->andReturnSelf(); - $query->expects('incrementEach') - ->with(['foo' => 5], ['category' => 'test']) - ->andReturn(1); - - $result = $model->publicIncrementEach(['foo' => 5], ['category' => 'test']); - - $this->assertSame(1, $result); - $this->assertSame(7, $model->foo); - $this->assertSame('test', $model->category); - } - - public function testIncrementEachFiresModelEvents(): void - { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - $model->foo = 1; - - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutScopes')->andReturn($query); - $query->expects('where')->andReturnSelf(); - $query->expects('incrementEach')->andReturn(1); - - $events = $this->recordEvents(); - - $model->publicIncrementEach(['foo' => 1]); - $this->assertSame(['eloquent.updating', 'eloquent.updated'], $events->getArrayCopy()); - } - - public function testIncrementEachReturnsFalseWhenUpdatingEventCancelled(): void - { - $model = m::mock(ModelStub::class . '[newQueryWithoutScopes]'); - $model->exists = true; - $model->id = 1; - $model->syncOriginalAttribute('id'); - $model->foo = 1; - $model->shouldNotReceive('newQueryWithoutScopes'); - - $events = new EventDispatcher; - $events->listen('eloquent.updating: ' . get_class($model), fn (): bool => false); - $model::setEventDispatcher($events); - - $result = $model->publicIncrementEach(['foo' => 1]); - - $this->assertFalse($result); - // Note: attributes are set before the event fires, matching increment() behavior. - // The in-memory value changes but the database is not updated. - $this->assertSame(2, $model->foo); - } - - public function testIncrementEachOnNonExistingModelForwardsToQueryBuilder(): void - { - $model = m::mock(ModelStub::class . '[newQueryWithoutRelationships]'); - $model->exists = false; - - $query = m::mock(Builder::class); - $model->expects('newQueryWithoutRelationships')->andReturn($query); - $query->expects('incrementEach') - ->with(['foo' => 1], []) - ->andReturn(5); - - $result = $model->publicIncrementEach(['foo' => 1]); - - $this->assertSame(5, $result); - } - - public function testRelationshipTouchOwnersIsPropagated(): void - { - $relation = $this->getMockBuilder(BelongsTo::class)->onlyMethods(['touch'])->disableOriginalConstructor()->getMock(); - $relation->expects($this->once())->method('touch'); - - $model = m::mock(ModelStub::class . '[partner]'); - $this->addMockConnection($model); - $model->expects('partner')->andReturn($relation); - $model->setTouchedRelations(['partner']); - - $mockPartnerModel = m::mock(ModelStub::class . '[touchOwners]'); - $mockPartnerModel->expects('touchOwners'); - $model->setRelation('partner', $mockPartnerModel); - - $model->touchOwners(); - } - - public function testRelationshipTouchOwnersIsNotPropagatedIfNoRelationshipResult(): void - { - $relation = $this->getMockBuilder(BelongsTo::class)->onlyMethods(['touch'])->disableOriginalConstructor()->getMock(); - $relation->expects($this->once())->method('touch'); - - $model = m::mock(ModelStub::class . '[partner]'); - $this->addMockConnection($model); - $model->expects('partner')->andReturn($relation); - $model->setTouchedRelations(['partner']); - - $model->setRelation('partner', null); - - $model->touchOwners(); - } - public function testModelAttributesAreCastedWhenPresentInCastsPropertyOrCastsMethod(): void { $model = new CastingStub; @@ -4331,10 +3768,10 @@ public function testIssetBehavesCorrectlyWithAttributesAndRelationships(): void public function testNonExistingAttributeWithInternalMethodNameDoesntCallMethod(): void { - $model = m::mock(ModelStub::class . '[delete,getRelationValue]'); + $model = Double::for(new ModelStub)->passthru(); $model->name = 'Spark'; - $model->shouldNotReceive('delete'); - $model->expects('getRelationValue')->with('belongsToStub')->andReturn('relation'); + $model->expects('delete')->never(); + $model->expects('getRelationValue')->with('belongsToStub')->returns('relation'); // Can return a normal relation $this->assertSame('relation', $model->belongsToStub); @@ -4345,7 +3782,7 @@ public function testNonExistingAttributeWithInternalMethodNameDoesntCallMethod() // Returns null for a Model.php method name $this->assertNull($model->delete); - $model = m::mock(ModelStub::class . '[delete]'); + $model = Double::for(new ModelStub)->passthru(); $model->delete = 123; $this->assertEquals(123, $model->delete); } @@ -4467,8 +3904,8 @@ public function testSaveQueryRejectsAMissingPrimaryKey(): void { $model = new ModelStub; $model->exists = true; - $query = m::mock(Builder::class); - $query->shouldNotReceive('where'); + $query = Double::for(Builder::class); + $query->expects('where')->never(); $this->expectException(MissingAttributeException::class); @@ -4479,8 +3916,8 @@ public function testSelectQueryRejectsAMissingPrimaryKey(): void { $model = new ModelStub; $model->exists = true; - $query = m::mock(Builder::class); - $query->shouldNotReceive('where'); + $query = Double::for(Builder::class); + $query->expects('where')->never(); $this->expectException(MissingAttributeException::class); @@ -4516,7 +3953,7 @@ public function testWithoutTouchingOnCallback(): void public function testFlushGuardableColumnsRestoresOnlyGuardableColumnMetadata(): void { $reflection = new ReflectionClass(Model::class); - $resolver = m::mock(Resolver::class); + $resolver = Double::for(Resolver::class); Model::setConnectionResolver($resolver); $reflection->setStaticPropertyValue('guardableColumns', [ModelStub::class => ['id']]); @@ -4531,8 +3968,8 @@ public function testFlushStateRestoresStaticState(): void { $reflection = new ReflectionClass(Model::class); - Model::setConnectionResolver(m::mock(Resolver::class)); - Model::setEventDispatcher(m::mock(Dispatcher::class)); + Model::setConnectionResolver(Double::for(Resolver::class)); + Model::setEventDispatcher(Double::for(Dispatcher::class)); Model::preventLazyLoading(); Model::automaticallyEagerLoadRelationships(); Model::handleLazyLoadingViolationUsing(static function () { @@ -4544,7 +3981,7 @@ public function testFlushStateRestoresStaticState(): void Model::handleMissingAttributeViolationUsing(static function () { }); Model::$snakeAttributes = false; - Model::encryptUsing(m::mock(Encrypter::class)); + Model::encryptUsing(Double::for(Encrypter::class)); $reflection->setStaticPropertyValue('booting', [ModelStub::class => 1]); $reflection->setStaticPropertyValue('booted', [ModelStub::class => true]); @@ -4903,15 +4340,15 @@ public function testExistenceCheckSuppressesCustomMissingAttributeCallbackOnlyLo */ protected function addMockConnection(Model $model): void { - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $model->setConnectionResolver($resolver); - $connection = m::mock(Connection::class); - $resolver->shouldReceive('connection')->andReturn($connection); + $connection = Double::for(Connection::class); + $resolver->allows('connection')->returns($connection); $grammar = new Grammar($connection); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); + $connection->allows('getQueryGrammar')->returns($grammar); $processor = new Processor; - $connection->shouldReceive('getPostProcessor')->andReturn($processor); - $connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor): BaseBuilder { + $connection->allows('getPostProcessor')->returns($processor); + $connection->allows('query')->resolves(function () use ($connection, $grammar, $processor): BaseBuilder { return new BaseBuilder($connection, $grammar, $processor); }); } @@ -4920,8 +4357,8 @@ public function testTouchMethodWithMultipleAttributes(): void { CarbonImmutable::setTestNow($now = CarbonImmutable::now()); - $model = m::mock(ModelStub::class . '[save]'); - $model->expects('save')->andReturn(true); + $model = Double::for(new ModelStub)->passthru(); + $model->expects('save')->returns(true); $result = $model->touch(['published_at', 'verified_at']); @@ -5612,26 +5049,6 @@ public function publicIncrement($column, $amount = 1, $extra = []) return $this->increment($column, $amount, $extra); } - public function publicIncrementQuietly($column, $amount = 1, $extra = []) - { - return $this->incrementQuietly($column, $amount, $extra); - } - - public function publicDecrementQuietly($column, $amount = 1, $extra = []) - { - return $this->decrementQuietly($column, $amount, $extra); - } - - public function publicIncrementEach(array $columns, array $extra = []) - { - return $this->incrementEach($columns, $extra); - } - - public function publicDecrementEach(array $columns, array $extra = []) - { - return $this->decrementEach($columns, $extra); - } - /** * Expose quiet multi-column increments for testing. */ @@ -5799,13 +5216,13 @@ public function setIncrementing(bool $value): static */ public function getConnection(): Connection { - $mock = m::mock(Connection::class); + $mock = Double::for(Connection::class); $grammar = new Grammar($mock); - $mock->shouldReceive('getQueryGrammar')->andReturn($grammar); + $mock->allows('getQueryGrammar')->returns($grammar); $processor = new Processor; - $mock->shouldReceive('getPostProcessor')->andReturn($processor); - $mock->shouldReceive('getWritableName')->andReturn('name'); - $mock->shouldReceive('query')->andReturnUsing(function () use ($mock, $grammar, $processor): BaseBuilder { + $mock->allows('getPostProcessor')->returns($processor); + $mock->allows('getWritableName')->returns('name'); + $mock->allows('query')->resolves(function () use ($mock, $grammar, $processor): BaseBuilder { return new BaseBuilder($mock, $grammar, $processor); }); @@ -5818,67 +5235,6 @@ class KeyTypeModelStub extends ModelStub protected string $keyType = 'string'; } -class FindWithWritePdoStub extends Model -{ - /** - * Create a query that expects a lookup on the write connection. - */ - public function newQuery(): Builder - { - $mock = m::mock(Builder::class); - $mock->expects('useWritePdo')->andReturnSelf(); - $mock->expects('find')->with(1)->andReturn(m::mock(Model::class)); - - return $mock; - } -} - -class DestroyStub extends Model -{ - protected array $fillable = [ - 'id', - ]; - - /** - * Create a query that returns a model to delete. - */ - public function newQuery(): Builder - { - $mock = m::mock(Builder::class); - $mock->expects('whereIn')->with('id', [1, 2, 3])->andReturn($mock); - $model = m::mock(Model::class); - $mock->expects('get')->andReturn(new Collection([$model])); - $model->expects('delete'); - - return $mock; - } -} - -class EmptyDestroyStub extends Model -{ - public function newQuery(): Builder - { - $mock = m::mock(Builder::class); - $mock->shouldReceive('whereIn')->never(); - - return $mock; - } -} - -class WithStub extends Model -{ - /** - * Create a query that expects the requested eager loads. - */ - public function newQuery(): Builder - { - $mock = m::mock(Builder::class); - $mock->expects('with')->with(['foo', 'bar'])->andReturnSelf(); - - return $mock; - } -} - class WithWhereHasStub extends Model { public function foo() @@ -6695,37 +6051,6 @@ class CastCacheInvalidClassStub extends Model protected array $casts = ['foo' => '\This\Class\Does\Not\Exist']; } -class DynamicIncrementEachStub extends Model -{ - protected array $guarded = []; - - /** - * Create a model with the query used by dynamic update calls. - */ - public function __construct( - public Builder $queryStub, - array $attributes = [], - ) { - parent::__construct($attributes); - } - - /** - * Get the unscoped query for the model. - */ - public function newQueryWithoutScopes(): Builder - { - return $this->queryStub; - } - - /** - * Get the query for the model. - */ - public function newQuery(): Builder - { - return $this->queryStub; - } -} - enum ConnectionName { case Foo; diff --git a/tests/Database/DatabaseEloquentMorphTest.php b/tests/Database/DatabaseEloquentMorphTest.php index b38e5cb5c..749525923 100755 --- a/tests/Database/DatabaseEloquentMorphTest.php +++ b/tests/Database/DatabaseEloquentMorphTest.php @@ -13,7 +13,6 @@ use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; -use Mockery as m; use PDO; class DatabaseEloquentMorphTest extends TestCase @@ -68,43 +67,6 @@ public function testMorphManyEagerConstraintsAreProperlyAdded(): void $this->assertSame([ResetModelStub::class, 1, ResetModelStub::class], $relation->getBindings()); } - public function testMorphRelationUpsertFillsForeignKey(): void - { - $relation = $this->getManyRelation(); - - $relation->getQuery()->expects('upsert')->with( - [ - ['email' => 'foo3', 'name' => 'bar', $relation->getForeignKeyName() => $relation->getParentKey(), $relation->getMorphType() => $relation->getMorphClass()], - ], - ['email'], - ['name'] - )->andReturn(1); - - $relation->upsert( - ['email' => 'foo3', 'name' => 'bar'], - ['email'], - ['name'] - ); - - $relation->getQuery()->expects('upsert')->with( - [ - ['email' => 'foo3', 'name' => 'bar', $relation->getForeignKeyName() => $relation->getParentKey(), $relation->getMorphType() => $relation->getMorphClass()], - ['name' => 'bar2', 'email' => 'foo2', $relation->getForeignKeyName() => $relation->getParentKey(), $relation->getMorphType() => $relation->getMorphClass()], - ], - ['email'], - ['name'] - )->andReturn(2); - - $relation->upsert( - [ - ['email' => 'foo3', 'name' => 'bar'], - ['name' => 'bar2', 'email' => 'foo2'], - ], - ['email'], - ['name'] - ); - } - /** * Get a morph one or many relationship backed by a real query builder. * @@ -120,21 +82,6 @@ protected function getRelationWithRealQuery(string $relation, ?Model $parent = n return new $relation($builder, $parent, 'table.morph_type', 'table.morph_id', 'id'); } - - protected function getManyRelation() - { - $builder = m::mock(Builder::class); - $builder->expects('whereNotNull')->with('table.morph_id'); - $builder->expects('where')->with('table.morph_id', '=', 1); - $related = new ResetModelStub; - $builder->shouldReceive('getModel')->andReturn($related); - $parent = m::mock(Model::class); - $parent->shouldReceive('getAttribute')->with('id')->andReturn(1); - $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent)); - $builder->expects('where')->with('table.morph_type', get_class($parent)); - - return new MorphMany($builder, $parent, 'table.morph_type', 'table.morph_id', 'id'); - } } class ResetModelStub extends Model diff --git a/tests/Database/DatabaseEloquentMorphToManyTest.php b/tests/Database/DatabaseEloquentMorphToManyTest.php deleted file mode 100644 index 3b8d6367b..000000000 --- a/tests/Database/DatabaseEloquentMorphToManyTest.php +++ /dev/null @@ -1,164 +0,0 @@ -getRelation(); - $relation->getParent()->shouldReceive('getKeyName')->andReturn('id'); - $relation->getParent()->expects('getKeyType')->andReturn('int'); - $relation->getQuery()->expects('whereIntegerInRaw')->with('taggables.taggable_id', [1, 2]); - $relation->getQuery()->expects('where')->with('taggables.taggable_type', get_class($relation->getParent())); - $model1 = new ModelStub; - $model1->id = 1; - $model2 = new ModelStub; - $model2->id = 2; - $relation->addEagerConstraints([$model1, $model2]); - } - - public function testAttachInsertsPivotTableRecord(): void - { - $relation = $this->getMockBuilder(MorphToMany::class)->onlyMethods(['touchIfTouching'])->setConstructorArgs($this->getRelationArguments())->getMock(); - $query = m::mock(QueryBuilder::class); - $query->expects('from')->with('taggables')->andReturn($query); - $query->expects('insert')->with([['taggable_id' => 1, 'taggable_type' => get_class($relation->getParent()), 'tag_id' => 2, 'foo' => 'bar']])->andReturn(true); - $relation->getQuery()->getQuery()->expects('newQuery')->andReturn($query); - $relation->expects($this->once())->method('touchIfTouching'); - - $relation->attach(2, ['foo' => 'bar']); - } - - public function testDetachRemovesPivotTableRecord(): void - { - $relation = $this->getMockBuilder(MorphToMany::class)->onlyMethods(['touchIfTouching'])->setConstructorArgs($this->getRelationArguments())->getMock(); - $query = m::mock(QueryBuilder::class); - $query->expects('from')->with('taggables')->andReturn($query); - $query->expects('where')->with('taggables.taggable_id', 1)->andReturn($query); - $query->expects('where')->with('taggable_type', get_class($relation->getParent()))->andReturn($query); - $query->expects('whereIn')->with('taggables.tag_id', [1, 2, 3]); - $query->expects('delete')->andReturn(3); - $relation->getQuery()->getQuery()->expects('newQuery')->andReturn($query); - $relation->expects($this->once())->method('touchIfTouching'); - - $this->assertSame(3, $relation->detach([1, 2, 3])); - } - - public function testDetachMethodClearsAllPivotRecordsWhenNoIDsAreGiven(): void - { - $relation = $this->getMockBuilder(MorphToMany::class)->onlyMethods(['touchIfTouching'])->setConstructorArgs($this->getRelationArguments())->getMock(); - $query = m::mock(QueryBuilder::class); - $query->expects('from')->with('taggables')->andReturn($query); - $query->expects('where')->with('taggables.taggable_id', 1)->andReturn($query); - $query->expects('where')->with('taggable_type', get_class($relation->getParent()))->andReturn($query); - $query->shouldReceive('whereIn')->never(); - $query->expects('delete')->andReturn(1); - $relation->getQuery()->getQuery()->expects('newQuery')->andReturn($query); - $relation->expects($this->once())->method('touchIfTouching'); - - $this->assertSame(1, $relation->detach()); - } - - public function testQueryExpressionCanBePassedToDifferentPivotQueryBuilderClauses(): void - { - $value = 'pivot_value'; - $column = new Expression("CONCAT(foo, '_', bar)"); - $relation = $this->getRelation(); - /** @var Builder&MockInterface $builder */ - $builder = $relation->getQuery(); - - $builder->expects('where')->with($column, '=', $value, 'and')->times(2)->andReturnSelf(); - $relation->wherePivot($column, '=', $value); - $relation->withPivotValue($column, $value); - - $builder->expects('whereBetween')->with($column, [$value, $value], 'and', false)->andReturnSelf(); - $relation->wherePivotBetween($column, [$value, $value]); - - $builder->expects('whereIn')->with($column, [$value], 'and', false)->andReturnSelf(); - $relation->wherePivotIn($column, [$value]); - - $builder->expects('whereNull')->with($column, 'and', false)->andReturnSelf(); - $relation->wherePivotNull($column); - - $builder->expects('orderBy')->with($column, SortDirection::Ascending)->andReturnSelf(); - $relation->orderByPivot($column); - - $builder->expects('orderBy')->with($column, SortDirection::Descending)->andReturnSelf(); - $relation->orderByPivotDesc($column); - } - - public function getRelation(): MorphToMany - { - [$builder, $parent] = $this->getRelationArguments(); - - return new MorphToMany($builder, $parent, 'taggable', 'taggables', 'taggable_id', 'tag_id', 'id', 'id'); - } - - public function getRelationArguments(): array - { - $parent = m::mock(Model::class); - $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent)); - $parent->shouldReceive('getKey')->andReturn(1); - $parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at'); - $parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at'); - $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent)); - $parent->shouldReceive('getAttribute')->with('id')->andReturn(1); - - $builder = m::mock(Builder::class); - $related = m::mock(Model::class); - $builder->shouldReceive('getModel')->andReturn($related); - - $related->shouldReceive('getTable')->andReturn('tags'); - $related->shouldReceive('getKeyName')->andReturn('id'); - $related->shouldReceive('qualifyColumn')->with('id')->andReturn('tags.id'); - $related->shouldReceive('getMorphClass')->andReturn(get_class($related)); - - $builder->expects('join')->with('taggables', 'tags.id', '=', 'taggables.tag_id'); - $builder->expects('where')->with('taggables.taggable_id', '=', 1); - $builder->expects('where')->with('taggables.taggable_type', get_class($parent)); - - $grammar = new Grammar(m::mock(Connection::class)); - $queryBuilder = m::mock(QueryBuilder::class); - $queryBuilder->shouldReceive('getGrammar')->andReturn($grammar); - $connection = m::mock(ConnectionInterface::class); - $connection->shouldReceive('table')->andReturnUsing( - fn ($table) => $queryBuilder->newQuery()->from($table) - ); - $queryBuilder->shouldReceive('getConnection')->andReturn($connection); - $builder->shouldReceive('getQuery')->andReturn($queryBuilder); - - return [ - $builder, - $parent, - 'taggable', - 'taggables', - 'taggable_id', - 'tag_id', - 'id', - 'id', - 'relation_name', - false, - ]; - } -} - -class ModelStub extends Model -{ - protected array $guarded = []; -} diff --git a/tests/Database/DatabaseEloquentMorphToTest.php b/tests/Database/DatabaseEloquentMorphToTest.php index 6bf27bc2b..054790f32 100644 --- a/tests/Database/DatabaseEloquentMorphToTest.php +++ b/tests/Database/DatabaseEloquentMorphToTest.php @@ -5,8 +5,6 @@ namespace Hypervel\Tests\Database\DatabaseEloquentMorphToTest; use Hypervel\Database\ClassMorphViolationException; -use Hypervel\Database\Connection; -use Hypervel\Database\ConnectionResolverInterface; use Hypervel\Database\Eloquent\Builder; use Hypervel\Database\Eloquent\Collection as EloquentCollection; use Hypervel\Database\Eloquent\Model; @@ -16,28 +14,28 @@ use Hypervel\Database\Query\Builder as QueryBuilder; use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Database\Query\Processors\Processor; +use Hypervel\Tests\Database\Concerns\InteractsWithInMemoryConnection; use Hypervel\Tests\Database\Fixtures\TestEnum; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; class DatabaseEloquentMorphToTest extends TestCase { + use InteractsWithInMemoryConnection; + use VerifiesDoubles; + protected Builder $builder; protected Model $related; - protected function addMockConnection(Model $model): void + protected function setUp(): void { - $model->setConnectionResolver($resolver = m::mock(ConnectionResolverInterface::class)); - $resolver->shouldReceive('connection')->andReturn($connection = m::mock(Connection::class)); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar = m::mock(Grammar::class)); - $grammar->shouldReceive('getBitwiseOperators')->andReturn([]); - $connection->shouldReceive('getPostProcessor')->andReturn($processor = m::mock(Processor::class)); - $connection->shouldReceive('query')->andReturnUsing(function () use ($connection, $grammar, $processor) { - return new QueryBuilder($connection, $grammar, $processor); - }); + parent::setUp(); + + $this->useInMemoryConnection(); } public function testLookupDictionaryIsProperlyConstructedForEnums(): void @@ -122,11 +120,9 @@ public function testLookupDictionaryRetainsZeroMorphTypesAndSkipsEmptyTypes(): v public function testMorphToWithDefault(): void { - $this->addMockConnection(new ModelStub); - $relation = $this->getRelation()->withDefault(); - $this->builder->expects('first')->andReturnNull(); + $this->builder->expects('first')->returns(null); $newModel = new ModelStub; @@ -135,13 +131,11 @@ public function testMorphToWithDefault(): void public function testMorphToWithDynamicDefault(): void { - $this->addMockConnection(new ModelStub); - $relation = $this->getRelation()->withDefault(function ($newModel) { $newModel->username = 'taylor'; }); - $this->builder->expects('first')->andReturnNull(); + $this->builder->expects('first')->returns(null); $newModel = new ModelStub; $newModel->username = 'taylor'; @@ -155,11 +149,9 @@ public function testMorphToWithDynamicDefault(): void public function testMorphToWithArrayDefault(): void { - $this->addMockConnection(new ModelStub); - $relation = $this->getRelation()->withDefault(['username' => 'taylor']); - $this->builder->expects('first')->andReturnNull(); + $this->builder->expects('first')->returns(null); $newModel = new ModelStub; $newModel->username = 'taylor'; @@ -193,8 +185,6 @@ public function testMorphToWithEmptyStringMorphType(): void public function testMorphToWithSpecifiedClassDefault(): void { - $this->addMockConnection(new RelatedStub); - $parent = new ModelStub; $parent->relation_type = RelatedStub::class; @@ -236,8 +226,8 @@ public function testAssociateMethodIgnoresNullValue(): void public function testAssociateMethodUsesConfiguredOwnerKeyWithZeroValue(): void { - $builder = m::mock(Builder::class); - $builder->shouldReceive('getModel')->andReturn(new MorphToAssociateRelatedStub); + $builder = Double::for(Builder::class); + $builder->allows('getModel')->returns(new MorphToAssociateRelatedStub); $parent = new MorphToAssociateParentStub; $associate = (new MorphToAssociateRelatedStub)->forceFill([ @@ -262,8 +252,8 @@ public function testAssociateMethodUsesConfiguredOwnerKeyWithZeroValue(): void public function testAssociateMethodUsesConfiguredOwnerKeyWithNullValue(): void { - $builder = m::mock(Builder::class); - $builder->shouldReceive('getModel')->andReturn(new MorphToAssociateRelatedStub); + $builder = Double::for(Builder::class); + $builder->allows('getModel')->returns(new MorphToAssociateRelatedStub); $parent = new MorphToAssociateParentStub; $associate = (new MorphToAssociateRelatedStub)->forceFill([ @@ -288,8 +278,8 @@ public function testAssociateMethodUsesConfiguredOwnerKeyWithNullValue(): void public function testAssociateMethodRejectsScalarValuesBeforeChangingTheParent(): void { - $builder = m::mock(Builder::class); - $builder->shouldReceive('getModel')->andReturn(new MorphToAssociateRelatedStub); + $builder = Double::for(Builder::class); + $builder->allows('getModel')->returns(new MorphToAssociateRelatedStub); $parent = (new MorphToAssociateParentStub)->forceFill([ 'foreign_key' => 'original-id', @@ -319,8 +309,8 @@ public function testAssociateMethodRejectsScalarValuesBeforeChangingTheParent(): public function testAssociateMethodRejectsUnmappedModelsBeforeChangingTheParent(): void { - $builder = m::mock(Builder::class); - $builder->shouldReceive('getModel')->andReturn(new MorphToAssociateRelatedStub); + $builder = Double::for(Builder::class); + $builder->allows('getModel')->returns(new MorphToAssociateRelatedStub); $parent = (new MorphToAssociateParentStub)->forceFill([ 'foreign_key' => 'original-id', @@ -381,9 +371,9 @@ public function __toString(): string } }; - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class); $related = new RelatedStub; - $builder->expects('getModel')->andReturn($related); + $builder->expects('getModel')->returns($related); $parent = new ModelStub; $parent->morph_type = 'type_1'; @@ -395,8 +385,8 @@ public function __toString(): string $relation->addEagerConstraints([$parent]); - $result = m::mock(Model::class); - $result->expects('getKey')->andReturn($uuidObject); + $result = Double::for(Model::class); + $result->expects('getKey')->returns($uuidObject); $relation->callMatchToMorphParents('type_1', new EloquentCollection([$result])); @@ -425,16 +415,16 @@ protected function getRelationWithRealQuery(): MorphTo public function getRelation($parent = null, $builder = null) { - $this->builder = $builder ?: m::mock(Builder::class); - $this->builder->shouldReceive('where')->with('relation.id', '=', 'foreign.value'); - $this->related = m::mock(Model::class); - $this->related->shouldReceive('getKeyName')->andReturn('id'); - $this->related->shouldReceive('getTable')->andReturn('relation'); - $this->related->shouldReceive('qualifyColumn')->andReturnUsing(fn (string $column) => "relation.{$column}"); - $this->builder->shouldReceive('getModel')->andReturn($this->related); + $this->builder = $builder ?: Double::for(Builder::class); + $this->builder->allows('where')->with('relation.id', '=', 'foreign.value')->returns($this->builder); + $this->related = Double::for(Model::class); + $this->related->allows('getKeyName')->returns('id'); + $this->related->allows('getTable')->returns('relation'); + $this->related->allows('qualifyColumn')->resolves(fn (string $column) => "relation.{$column}"); + $this->builder->allows('getModel')->returns($this->related); $parent = $parent ?: new ModelStub; - return m::mock(MorphTo::class . '[createModelByType]', [$this->builder, $parent, 'foreign_key', 'id', 'morph_type', 'relation']); + return new MorphTo($this->builder, $parent, 'foreign_key', 'id', 'morph_type', 'relation'); } } diff --git a/tests/Database/DatabaseEloquentPivotTest.php b/tests/Database/DatabaseEloquentPivotTest.php index 8fdb3abc3..87ce9f208 100755 --- a/tests/Database/DatabaseEloquentPivotTest.php +++ b/tests/Database/DatabaseEloquentPivotTest.php @@ -13,21 +13,24 @@ use Hypervel\Database\Eloquent\Relations\Pivot; use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; class DatabaseEloquentPivotTest extends TestCase { + use VerifiesDoubles; + public function testPropertiesAreSetCorrectly(): void { - $parent = m::mock(Model::class . '[getConnectionName]'); - $parent->expects('getConnectionName')->times(1)->andReturn('connection'); - $resolver = m::mock(ConnectionResolverInterface::class); + $parent = Double::for(Model::class)->passthru(); + $parent->expects('getConnectionName')->times(1)->returns('connection'); + $resolver = Double::for(ConnectionResolverInterface::class); $parent->setConnectionResolver($resolver); - $connection = m::mock(Connection::class); - $resolver->expects('connection')->times(1)->andReturn($connection); + $connection = Double::for(Connection::class); + $resolver->expects('connection')->times(1)->returns($connection); $grammar = new Grammar($connection); - $connection->expects('getQueryGrammar')->times(1)->andReturn($grammar); + $connection->expects('getQueryGrammar')->times(1)->returns($grammar); $parent->setDateFormat('Y-m-d H:i:s'); $pivot = Pivot::fromAttributes($parent, ['foo' => 'bar', 'created_at' => '2015-09-12'], 'table', true); @@ -49,8 +52,8 @@ public function testMutatorsAreCalledFromConstructor(): void public function testFromRawAttributesDoesNotDoubleMutate(): void { - $parent = m::mock(Model::class . '[getConnectionName]'); - $parent->expects('getConnectionName')->andReturn('connection'); + $parent = Double::for(Model::class)->passthru(); + $parent->expects('getConnectionName')->returns('connection'); $pivot = JsonCastStub::fromRawAttributes($parent, ['foo' => json_encode(['name' => 'Taylor'])], 'table', true); @@ -59,8 +62,8 @@ public function testFromRawAttributesDoesNotDoubleMutate(): void public function testFromRawAttributesDoesNotMutate(): void { - $parent = m::mock(Model::class . '[getConnectionName]'); - $parent->expects('getConnectionName')->andReturn('connection'); + $parent = Double::for(Model::class)->passthru(); + $parent->expects('getConnectionName')->returns('connection'); $pivot = MutatorStub::fromRawAttributes($parent, ['foo' => 'bar'], 'table', true); @@ -69,8 +72,8 @@ public function testFromRawAttributesDoesNotMutate(): void public function testPropertiesUnchangedAreNotDirty(): void { - $parent = m::mock(Model::class . '[getConnectionName]'); - $parent->expects('getConnectionName')->andReturn('connection'); + $parent = Double::for(Model::class)->passthru(); + $parent->expects('getConnectionName')->returns('connection'); $pivot = Pivot::fromAttributes($parent, ['foo' => 'bar', 'shimy' => 'shake'], 'table', true); $this->assertSame([], $pivot->getDirty()); @@ -78,8 +81,8 @@ public function testPropertiesUnchangedAreNotDirty(): void public function testPropertiesChangedAreDirty(): void { - $parent = m::mock(Model::class . '[getConnectionName]'); - $parent->expects('getConnectionName')->andReturn('connection'); + $parent = Double::for(Model::class)->passthru(); + $parent->expects('getConnectionName')->returns('connection'); $pivot = Pivot::fromAttributes($parent, ['foo' => 'bar', 'shimy' => 'shake'], 'table', true); $pivot->shimy = 'changed'; @@ -88,8 +91,8 @@ public function testPropertiesChangedAreDirty(): void public function testTimestampPropertyIsSetIfCreatedAtInAttributes(): void { - $parent = m::mock(Model::class . '[getConnectionName]'); - $parent->expects('getConnectionName')->times(2)->andReturn('connection'); + $parent = Double::for(Model::class)->passthru(); + $parent->expects('getConnectionName')->times(2)->returns('connection'); $pivot = DateStub::fromAttributes($parent, ['foo' => 'bar', 'created_at' => 'foo'], 'table'); $this->assertTrue($pivot->timestamps); @@ -99,8 +102,8 @@ public function testTimestampPropertyIsSetIfCreatedAtInAttributes(): void public function testTimestampPropertyIsTrueWhenCreatingFromRawAttributes(): void { - $parent = m::mock(Model::class . '[getConnectionName]'); - $parent->expects('getConnectionName')->andReturn('connection'); + $parent = Double::for(Model::class)->passthru(); + $parent->expects('getConnectionName')->returns('connection'); $pivot = Pivot::fromRawAttributes($parent, ['foo' => 'bar', 'created_at' => 'foo'], 'table'); $this->assertTrue($pivot->timestamps); } @@ -121,9 +124,9 @@ public function testDeleteMethodDeletesModelByKeys(): void $pivot->setPivotKeys('foreign', 'other'); $pivot->foreign = 'foreign.value'; $pivot->other = 'other.value'; - $query = m::mock(Builder::class); - $query->expects('where')->with(['foreign' => 'foreign.value', 'other' => 'other.value'])->andReturn($query); - $query->expects('delete')->andReturn(1); + $query = Double::for(Builder::class); + $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); $rowsAffected = $pivot->delete(); @@ -135,9 +138,9 @@ public function testModelDeleteWrappersReturnAffectedRowCountForPivots(): void $pivot = new DeleteReturnPivotStub; $pivot->exists = true; - $pivot->setConnectionResolver($resolver = m::mock(ConnectionResolverInterface::class)); - $resolver->expects('connection')->andReturn($connection = m::mock(Connection::class)); - $connection->expects('transaction')->andReturnUsing(fn ($callback) => $callback()); + $pivot->setConnectionResolver($resolver = Double::for(ConnectionResolverInterface::class)); + $resolver->expects('connection')->returns($connection = Double::for(Connection::class)); + $connection->expects('transaction')->resolves(fn ($callback) => $callback()); $this->assertSame(1, $pivot->deleteQuietly()); $this->assertSame(1, $pivot->deleteOrFail()); @@ -170,8 +173,8 @@ public function testPivotModelTableNameIsSingular(): void public function testRestorationQueriesUsePrimaryKeys(string $pivotClass, array|int|string $ids): void { $pivot = $this->getMockBuilder($pivotClass)->onlyMethods(['newQueryWithoutScopes'])->getMock(); - $query = m::mock(Builder::class); - $query->expects('whereKey')->with($ids)->andReturnSelf(); + $query = Double::for(Builder::class); + $query->expects('whereKey')->with($ids)->returns($query); $pivot->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query); $this->assertSame($query, $pivot->newQueryForRestoration($ids)); @@ -202,7 +205,7 @@ public function testWithoutRelations(): void { $original = new Pivot; - $parentModel = m::mock(Model::class); + $parentModel = Double::for(Model::class); $original->pivotParent = $parentModel; $original->setRelation('bar', 'baz'); diff --git a/tests/Database/DatabaseEloquentPolymorphicRelationsIntegrationTest.php b/tests/Database/DatabaseEloquentPolymorphicRelationsIntegrationTest.php index e4d0829b5..56499c632 100644 --- a/tests/Database/DatabaseEloquentPolymorphicRelationsIntegrationTest.php +++ b/tests/Database/DatabaseEloquentPolymorphicRelationsIntegrationTest.php @@ -94,16 +94,23 @@ public function testCreation(): void public function testEagerLoading(): void { $post = Post::create(); + $secondPost = Post::create(); + $image = Image::create(); $tag = Tag::create(); + $secondTag = Tag::create(); $post->tags()->attach($tag->id); + $secondPost->tags()->attach($secondTag->id); + $image->tags()->attach($secondTag->id); - $post = Post::with('tags')->whereId(1)->first(); + [$post, $secondPost] = Post::with('tags')->orderBy('id')->get(); $tag = Tag::with('posts')->whereId(1)->first(); $this->assertTrue($post->relationLoaded('tags')); $this->assertTrue($tag->relationLoaded('posts')); $this->assertEquals($tag->id, $post->tags->first()->id); $this->assertEquals($post->id, $tag->posts->first()->id); + $this->assertSame([$tag->id], $post->tags->modelKeys()); + $this->assertSame([$secondTag->id], $secondPost->tags->modelKeys()); } public function testChunkById(): void diff --git a/tests/Database/DatabaseEloquentRelationshipsTest.php b/tests/Database/DatabaseEloquentRelationshipsTest.php index 5f0736877..9d9950818 100644 --- a/tests/Database/DatabaseEloquentRelationshipsTest.php +++ b/tests/Database/DatabaseEloquentRelationshipsTest.php @@ -20,11 +20,23 @@ use Hypervel\Database\Query\Builder as BaseBuilder; use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Database\Query\Processors\Processor; +use Hypervel\Tests\Database\Concerns\InteractsWithInMemoryConnection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DatabaseEloquentRelationshipsTest extends TestCase { + use InteractsWithInMemoryConnection; + use VerifiesDoubles; + + protected function setUp(): void + { + parent::setUp(); + + $this->useInMemoryConnection(); + } + public function testStandardRelationships(): void { $post = new Post; @@ -265,13 +277,13 @@ class MockedConnectionModel extends Model */ public function getConnection(): Connection { - $mock = m::mock(Connection::class); + $mock = Double::for(Connection::class); $grammar = new Grammar($mock); - $mock->shouldReceive('getQueryGrammar')->andReturn($grammar); + $mock->allows('getQueryGrammar')->returns($grammar); $processor = new Processor; - $mock->shouldReceive('getPostProcessor')->andReturn($processor); - $mock->shouldReceive('getName')->andReturn('name'); - $mock->shouldReceive('query')->andReturnUsing(function () use ($mock, $grammar, $processor): BaseBuilder { + $mock->allows('getPostProcessor')->returns($processor); + $mock->allows('getName')->returns('name'); + $mock->allows('query')->resolves(function () use ($mock, $grammar, $processor): BaseBuilder { return new BaseBuilder($mock, $grammar, $processor); }); @@ -279,11 +291,11 @@ public function getConnection(): Connection } } -class FakeRelationship extends MockedConnectionModel +class FakeRelationship extends Model { } -class Post extends MockedConnectionModel +class Post extends Model { public function attachment() { diff --git a/tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php b/tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php index 7fa02f5be..96672a8fc 100644 --- a/tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php +++ b/tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php @@ -8,18 +8,17 @@ use Exception; use Hypervel\Database\Capsule\Manager as DB; use Hypervel\Database\ConnectionInterface; -use Hypervel\Database\Eloquent\Builder as EloquentBuilder; use Hypervel\Database\Eloquent\Model as Eloquent; use Hypervel\Database\Eloquent\SoftDeletes; use Hypervel\Database\Eloquent\SoftDeletingScope; use Hypervel\Database\Query\Builder; +use Hypervel\Database\QueryException; use Hypervel\Database\Schema\Builder as SchemaBuilder; use Hypervel\Events\Dispatcher; use Hypervel\Pagination\CursorPaginator; use Hypervel\Pagination\Paginator; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; class DatabaseEloquentSoftDeletesIntegrationTest extends TestCase { @@ -235,33 +234,33 @@ public function testForceDeleteUpdateExistsProperty(): void public function testForceDeleteDoesntUpdateExistsPropertyIfFailed(): void { - $user = new class(['id' => 1]) extends User { - public bool $exists = true; - - /** - * Get a query builder that fails when deleting the model. - */ - public function newModelQuery(): EloquentBuilder - { - $mock = m::mock(EloquentBuilder::class); - $mock->expects('where')->with('id', '=', 1)->andReturnSelf(); - $mock->expects('forceDelete')->andThrow(new Exception); + $this->createUsers(); + $this->connection()->statement('create trigger prevent_user_delete before delete on users begin select raise(abort, \'blocked\'); end'); - return $mock; - } - }; + $user = User::find(2); $this->assertTrue($user->exists); try { $user->forceDelete(); - } catch (Exception) { + $this->fail('Expected the delete to fail.'); + } catch (QueryException) { } $this->assertTrue($user->exists); + $this->assertNotNull(User::find(2)); $this->assertFalse($user->isForceDeleting()); } + public function testForceDeleteWrappersPreserveIntegerDeleteResult(): void + { + $model = new IntegerDeleteResultModelStub; + $model->exists = true; + + $this->assertSame(1, $model->forceDelete()); + $this->assertSame(1, $model->forceDeleteQuietly()); + } + public function testForceDestroyFullyDeletesRecord(): void { $this->createUsers(); @@ -324,6 +323,25 @@ public function testForceDestroyDeletesRecordsFromEloquentCollection(): void $this->assertNull(User::find(2)); } + public function testDeleteSetsTheDeletedAtAndUpdatedAtColumnsAndLeavesTheModelClean(): void + { + CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2023-01-02 03:04:05')); + + $user = User::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']); + + CarbonImmutable::setTestNow($now->addDay()); + + $user->delete(); + + $this->assertTrue($user->trashed()); + $this->assertFalse($user->isDirty()); + $this->assertSame('2023-01-03 03:04:05', $user->deleted_at->toDateTimeString()); + + $row = (array) $this->connection()->table('users')->where('id', 1)->first(); + $this->assertSame('2023-01-03 03:04:05', $row['deleted_at']); + $this->assertSame('2023-01-03 03:04:05', $row['updated_at']); + } + public function testRestoreRestoresRecords(): void { $this->createUsers(); @@ -340,6 +358,24 @@ public function testRestoreRestoresRecords(): void $this->assertNull($users->find(2)->deleted_at); } + public function testRestoreIsCancelledWhenRestoringEventReturnsFalse(): void + { + Eloquent::setEventDispatcher(new Dispatcher); + + $this->createUsers(); + + User::restoring(function () { + return false; + }); + + $user = User::withTrashed()->find(1); + + $this->assertFalse($user->restore()); + $this->assertNotNull($user->deleted_at); + $this->assertNotNull(User::withTrashed()->find(1)->deleted_at); + $this->assertNull(User::find(1)); + } + public function testRestoreDoesNotFireRestoredEventWhenSavingEventCancelsSave(): void { $previousDispatcher = Eloquent::getEventDispatcher(); @@ -437,6 +473,40 @@ public function testFirstOrCreate(): void $this->assertCount(3, User::withTrashed()->get()); } + public function testRestoreOrCreateRestoresATrashedRecordOrCreatesANewOne(): void + { + $this->createUsers(); + + $restored = User::restoreOrCreate(['email' => 'taylorotwell@gmail.com']); + + $this->assertSame(1, $restored->id); + $this->assertFalse($restored->trashed()); + $this->assertCount(2, User::all()); + + $created = User::restoreOrCreate(['email' => 'foo@bar.com'], ['group_id' => 1]); + + $this->assertTrue($created->wasRecentlyCreated); + $this->assertSame(1, $created->fresh()->group_id); + $this->assertCount(3, User::all()); + } + + public function testCreateOrRestoreRestoresATrashedRecordOrCreatesANewOne(): void + { + $this->createUsers(); + + $restored = User::createOrRestore(['email' => 'taylorotwell@gmail.com']); + + $this->assertSame(1, $restored->id); + $this->assertFalse($restored->trashed()); + $this->assertCount(2, User::all()); + + $created = User::createOrRestore(['email' => 'foo@bar.com'], ['group_id' => 1]); + + $this->assertTrue($created->wasRecentlyCreated); + $this->assertSame(1, $created->fresh()->group_id); + $this->assertCount(3, User::all()); + } + public function testCreateOrFirst(): void { $this->createUsers(); @@ -1206,3 +1276,16 @@ public function users() $this->hasMany(User::class); } } + +class IntegerDeleteResultModelStub extends Eloquent +{ + use SoftDeletes; + + /** + * Return a simulated affected-row count. + */ + public function delete(): int + { + return 1; + } +} diff --git a/tests/Database/DatabaseManagerTest.php b/tests/Database/DatabaseManagerTest.php index cfedac16b..27bbb4150 100644 --- a/tests/Database/DatabaseManagerTest.php +++ b/tests/Database/DatabaseManagerTest.php @@ -22,11 +22,15 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PDO; class DatabaseManagerTest extends TestCase { + use VerifiesDoubles; + // REMOVED: Laravel's ::direct parsing, PDO selection and refresh tests. // Hypervel uses a separate named connection for that endpoint. @@ -50,7 +54,7 @@ public function testSetDefaultConnectionAcceptsEnums(): void $config = new Repository(['database' => ['default' => 'sqlite']]); $container->instance('config', $config); - $manager = new DatabaseManager($container, m::mock(ConnectionFactory::class)); + $manager = new DatabaseManager($container, Double::for(ConnectionFactory::class)); $manager->setDefaultConnection(DatabaseManagerTestBackedConnection::Reporting); @@ -72,7 +76,7 @@ public function testUsingConnectionAcceptsEnumsAndRestoresTheDefaultConnection() $container = new Container; $container->instance('config', new Repository(['database' => ['default' => 'sqlite']])); - $manager = new DatabaseManager($container, m::mock(ConnectionFactory::class)); + $manager = new DatabaseManager($container, Double::for(ConnectionFactory::class)); $default = $manager->usingConnection(DatabaseManagerTestBackedConnection::Reporting, fn (): ?string => $manager->getDefaultConnection()); @@ -520,8 +524,11 @@ public function testNonPooledReadExtensionRetainsCompleteConfigurationThroughRec $manager->extend('http', static function (array $config) use (&$receivedConfigurations): Connection { $receivedConfigurations[] = $config; - return m::mock(Connection::class . '[replaceDriverResources]', [$config['database'], $config['prefix'], $config]) - ->shouldAllowMockingProtectedMethods(); + $connection = Double::for(Connection::class)->passthru(); + // Initialize the abstract driver's real configuration; Double skips constructors. + $connection->__construct($config['database'], $config['prefix'], $config); + + return $connection; }); $expected = $config + [ 'prefix' => '', @@ -533,7 +540,7 @@ public function testNonPooledReadExtensionRetainsCompleteConfigurationThroughRec $this->assertSame([$expected], $receivedConfigurations); $this->assertSame($expected + ['mask_bindings_in_exception_messages' => false], $connection->getConfig()); - $connection->shouldReceive('replaceDriverResources')->once()->with(m::type(Connection::class)); + $connection->expects('replaceDriverResources')->with(Argument::type(Connection::class)); $this->assertSame($connection, $manager->reconnect('read-extension::read')); $this->assertSame([$expected, $expected], $receivedConfigurations); diff --git a/tests/Database/DatabaseMariaDbBuilderTest.php b/tests/Database/DatabaseMariaDbBuilderTest.php index 3caab6b9d..bc7373439 100644 --- a/tests/Database/DatabaseMariaDbBuilderTest.php +++ b/tests/Database/DatabaseMariaDbBuilderTest.php @@ -8,21 +8,24 @@ use Hypervel\Database\Schema\Grammars\MariaDbGrammar; use Hypervel\Database\Schema\MariaDbBuilder; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DatabaseMariaDbBuilderTest extends TestCase { + use VerifiesDoubles; + public function testCreateDatabase(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new MariaDbGrammar($connection); - $connection->expects('getConfig')->with('charset')->andReturn('utf8mb4'); - $connection->expects('getConfig')->with('collation')->andReturn('utf8mb4_unicode_ci'); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getConfig')->with('charset')->returns('utf8mb4'); + $connection->expects('getConfig')->with('collation')->returns('utf8mb4_unicode_ci'); + $connection->expects('getSchemaGrammar')->returns($grammar); $connection->expects('statement')->with( 'create database `my_temporary_database` default character set `utf8mb4` default collate `utf8mb4_unicode_ci`' - )->andReturn(true); + )->returns(true); $builder = new MariaDbBuilder($connection); $builder->createDatabase('my_temporary_database'); @@ -30,13 +33,13 @@ public function testCreateDatabase(): void public function testDropDatabaseIfExists(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new MariaDbGrammar($connection); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getSchemaGrammar')->returns($grammar); $connection->expects('statement')->with( 'drop database if exists `my_database_a`' - )->andReturn(true); + )->returns(true); $builder = new MariaDbBuilder($connection); diff --git a/tests/Database/DatabaseMariaDbQueryGrammarTest.php b/tests/Database/DatabaseMariaDbQueryGrammarTest.php index d83e256c2..c1ff1702c 100755 --- a/tests/Database/DatabaseMariaDbQueryGrammarTest.php +++ b/tests/Database/DatabaseMariaDbQueryGrammarTest.php @@ -9,23 +9,26 @@ use Hypervel\Database\Query\Grammars\MariaDbGrammar; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; class DatabaseMariaDbQueryGrammarTest extends TestCase { + use VerifiesDoubles; + public function testUpdateBindingsRejectUnencodableArrays(): void { $this->expectException(JsonException::class); - (new MariaDbGrammar(m::mock(Connection::class))) + (new MariaDbGrammar(Double::for(Connection::class))) ->prepareBindingsForUpdate([], ['payload' => [NAN]]); } public function testToRawSql(): void { - $connection = m::mock(Connection::class); - $connection->expects('escape')->with('foo', false)->andReturn("'foo'"); + $connection = Double::for(Connection::class); + $connection->expects('escape')->with('foo', false)->returns("'foo'"); $grammar = new MariaDbGrammar($connection); $query = $grammar->substituteBindingsIntoRawSql( @@ -103,14 +106,14 @@ public function testTimeoutCanBeCleared(): void protected function getBuilder(): Builder { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getDatabaseName')->andReturn('database'); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getDatabaseName')->returns('database'); + $connection->allows('getTablePrefix')->returns(''); return new Builder( $connection, new MariaDbGrammar($connection), - m::mock(Processor::class) + Double::for(Processor::class) ); } } diff --git a/tests/Database/DatabaseMariaDbSchemaBuilderTest.php b/tests/Database/DatabaseMariaDbSchemaBuilderTest.php index 8b6a68022..7ee171de9 100755 --- a/tests/Database/DatabaseMariaDbSchemaBuilderTest.php +++ b/tests/Database/DatabaseMariaDbSchemaBuilderTest.php @@ -9,35 +9,38 @@ use Hypervel\Database\Schema\Grammars\MariaDbGrammar; use Hypervel\Database\Schema\MariaDbBuilder; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DatabaseMariaDbSchemaBuilderTest extends TestCase { + use VerifiesDoubles; + public function testHasTable(): void { - $connection = m::mock(MariaDbConnection::class); - $connection->shouldReceive('usesBackslashEscapes')->andReturnTrue(); + $connection = Double::for(MariaDbConnection::class); + $connection->allows('usesBackslashEscapes')->returns(true); $grammar = new MariaDbGrammar($connection); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getSchemaGrammar')->returns($grammar); $builder = new MariaDbBuilder($connection); - $connection->expects('getTablePrefix')->andReturn('prefix_'); - $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists(null, 'prefix_table'))->andReturn([['exists' => 1]]); + $connection->expects('getTablePrefix')->returns('prefix_'); + $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists(null, 'prefix_table'))->returns([['exists' => 1]]); $this->assertTrue($builder->hasTable('table')); } public function testGetColumnListing(): void { - $connection = m::mock(MariaDbConnection::class); - $connection->shouldReceive('usesBackslashEscapes')->andReturnTrue(); + $connection = Double::for(MariaDbConnection::class); + $connection->allows('usesBackslashEscapes')->returns(true); $grammar = new MariaDbGrammar($connection); $processor = new MariaDbProcessor; - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('getPostProcessor')->andReturn($processor); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getPostProcessor')->returns($processor); $builder = new MariaDbBuilder($connection); - $connection->expects('getTablePrefix')->andReturn('prefix_'); + $connection->expects('getTablePrefix')->returns('prefix_'); $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'prefix_table')) - ->andReturn([(object) ['name' => 'column', 'type_name' => 'int', 'type' => 'int', 'collation' => null, 'nullable' => 'YES', 'default' => null, 'comment' => null, 'expression' => null, 'extra' => '']]); + ->returns([(object) ['name' => 'column', 'type_name' => 'int', 'type' => 'int', 'collation' => null, 'nullable' => 'YES', 'default' => null, 'comment' => null, 'expression' => null, 'extra' => '']]); $this->assertSame(['column'], $builder->getColumnListing('table')); } diff --git a/tests/Database/DatabaseMariaDbSchemaGrammarTest.php b/tests/Database/DatabaseMariaDbSchemaGrammarTest.php index 4915f6716..a5a7e8b1c 100755 --- a/tests/Database/DatabaseMariaDbSchemaGrammarTest.php +++ b/tests/Database/DatabaseMariaDbSchemaGrammarTest.php @@ -13,17 +13,20 @@ use Hypervel\Database\Schema\MariaDbBuilder; use Hypervel\Tests\Database\Fixtures\Enums\Foo; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DatabaseMariaDbSchemaGrammarTest extends TestCase { + use VerifiesDoubles; + public function testBasicCreateTable(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -36,7 +39,7 @@ public function testBasicCreateTable(): void $this->assertSame("create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8 collate 'utf8_unicode_ci'", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->increments('id'); @@ -51,7 +54,7 @@ public function testBasicCreateTable(): void ], $statements); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -66,9 +69,9 @@ public function testBasicCreateTable(): void public function testAutoIncrementStartingValue(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -99,8 +102,8 @@ public function testAddColumnsWithMultipleAutoIncrementStartingValue(): void public function testEngineCreateTable(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -114,9 +117,9 @@ public function testEngineCreateTable(): void $this->assertSame("create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8 collate 'utf8_unicode_ci' engine = InnoDB", $statements[0]); $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn('InnoDB'); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns('InnoDB'); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -132,7 +135,7 @@ public function testEngineCreateTable(): void public function testCharsetCollationCreateTable(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -147,9 +150,9 @@ public function testCharsetCollationCreateTable(): void $this->assertSame("create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci'", $statements[0]); $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -165,7 +168,7 @@ public function testCharsetCollationCreateTable(): void public function testBasicCreateTableWithPrefix(): void { $conn = $this->getConnection(prefix: 'prefix_'); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -181,7 +184,7 @@ public function testBasicCreateTableWithPrefix(): void public function testCreateTemporaryTable(): void { $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -554,7 +557,7 @@ public function testAddingForeignID(): void $blueprint = new Blueprint($this->getConnection(), 'users'); $foreignId = $blueprint->foreignId('foo'); $blueprint->foreignId('company_id')->constrained(); - $blueprint->foreignId('laravel_idea_id')->constrained(); + $blueprint->foreignId('hypervel_idea_id')->constrained(); $blueprint->foreignId('team_id')->references('id')->on('teams'); $blueprint->foreignId('team_column_id')->constrained('teams'); @@ -565,8 +568,8 @@ public function testAddingForeignID(): void 'alter table `users` add `foo` bigint unsigned not null', 'alter table `users` add `company_id` bigint unsigned not null', 'alter table `users` add constraint `users_company_id_foreign` foreign key (`company_id`) references `companies` (`id`)', - 'alter table `users` add `laravel_idea_id` bigint unsigned not null', - 'alter table `users` add constraint `users_laravel_idea_id_foreign` foreign key (`laravel_idea_id`) references `laravel_ideas` (`id`)', + 'alter table `users` add `hypervel_idea_id` bigint unsigned not null', + 'alter table `users` add constraint `users_hypervel_idea_id_foreign` foreign key (`hypervel_idea_id`) references `hypervel_ideas` (`id`)', 'alter table `users` add `team_id` bigint unsigned not null', 'alter table `users` add constraint `users_team_id_foreign` foreign key (`team_id`) references `teams` (`id`)', 'alter table `users` add `team_column_id` bigint unsigned not null', @@ -932,8 +935,8 @@ public function testAddingJsonb(): void public function testAddingDate(): void { $conn = $this->getConnection(); - $conn->expects('isMaria')->andReturn(true); - $conn->expects('getServerVersion')->andReturn('10.11.0'); + $conn->expects('isMaria')->returns(true); + $conn->expects('getServerVersion')->returns('10.11.0'); $blueprint = new Blueprint($conn, 'users'); $blueprint->date('foo'); @@ -946,8 +949,8 @@ public function testAddingDate(): void public function testAddingDateWithDefaultCurrent(): void { $conn = $this->getConnection(); - $conn->expects('isMaria')->andReturn(true); - $conn->expects('getServerVersion')->andReturn('10.11.0'); + $conn->expects('isMaria')->returns(true); + $conn->expects('getServerVersion')->returns('10.11.0'); $blueprint = new Blueprint($conn, 'users'); $blueprint->date('foo')->useCurrent(); @@ -960,8 +963,8 @@ public function testAddingDateWithDefaultCurrent(): void public function testAddingYear(): void { $conn = $this->getConnection(); - $conn->expects('isMaria')->andReturn(true); - $conn->expects('getServerVersion')->andReturn('10.11.0'); + $conn->expects('isMaria')->returns(true); + $conn->expects('getServerVersion')->returns('10.11.0'); $blueprint = new Blueprint($conn, 'users'); $blueprint->year('birth_year'); @@ -973,8 +976,8 @@ public function testAddingYear(): void public function testAddingYearWithDefaultCurrent(): void { $conn = $this->getConnection(); - $conn->expects('isMaria')->andReturn(true); - $conn->expects('getServerVersion')->andReturn('10.11.0'); + $conn->expects('isMaria')->returns(true); + $conn->expects('getServerVersion')->returns('10.11.0'); $blueprint = new Blueprint($conn, 'users'); $blueprint->year('birth_year')->useCurrent(); @@ -1244,7 +1247,7 @@ public function testAddingForeignUuid(): void $blueprint = new Blueprint($conn, 'users'); $foreignUuid = $blueprint->foreignUuid('foo'); $blueprint->foreignUuid('company_id')->constrained(); - $blueprint->foreignUuid('laravel_idea_id')->constrained(); + $blueprint->foreignUuid('hypervel_idea_id')->constrained(); $blueprint->foreignUuid('team_id')->references('id')->on('teams'); $blueprint->foreignUuid('team_column_id')->constrained('teams'); @@ -1255,8 +1258,8 @@ public function testAddingForeignUuid(): void 'alter table `users` add `foo` uuid not null', 'alter table `users` add `company_id` uuid not null', 'alter table `users` add constraint `users_company_id_foreign` foreign key (`company_id`) references `companies` (`id`)', - 'alter table `users` add `laravel_idea_id` uuid not null', - 'alter table `users` add constraint `users_laravel_idea_id_foreign` foreign key (`laravel_idea_id`) references `laravel_ideas` (`id`)', + 'alter table `users` add `hypervel_idea_id` uuid not null', + 'alter table `users` add constraint `users_hypervel_idea_id_foreign` foreign key (`hypervel_idea_id`) references `hypervel_ideas` (`id`)', 'alter table `users` add `team_id` uuid not null', 'alter table `users` add constraint `users_team_id_foreign` foreign key (`team_id`) references `teams` (`id`)', 'alter table `users` add `team_column_id` uuid not null', @@ -1427,8 +1430,8 @@ public function testAddingComment(): void public function testCreateDatabase(): void { $connection = $this->getConnection(); - $connection->expects('getConfig')->with('charset')->andReturn('utf8mb4_foo'); - $connection->expects('getConfig')->with('collation')->andReturn('utf8mb4_unicode_ci_foo'); + $connection->expects('getConfig')->with('charset')->returns('utf8mb4_foo'); + $connection->expects('getConfig')->with('collation')->returns('utf8mb4_unicode_ci_foo'); $statement = $this->getGrammar($connection)->compileCreateDatabase('my_database_a'); @@ -1438,8 +1441,8 @@ public function testCreateDatabase(): void ); $connection = $this->getConnection(); - $connection->expects('getConfig')->with('charset')->andReturn('utf8mb4_bar'); - $connection->expects('getConfig')->with('collation')->andReturn('utf8mb4_unicode_ci_bar'); + $connection->expects('getConfig')->with('charset')->returns('utf8mb4_bar'); + $connection->expects('getConfig')->with('collation')->returns('utf8mb4_unicode_ci_bar'); $statement = $this->getGrammar($connection)->compileCreateDatabase('my_database_b'); @@ -1452,9 +1455,9 @@ public function testCreateDatabase(): void public function testCreateTableWithVirtualAsColumn(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1467,7 +1470,7 @@ public function testCreateTableWithVirtualAsColumn(): void $this->assertSame("create table `users` (`my_column` varchar(255) not null, `my_other_column` varchar(255) as (my_column)) default character set utf8 collate 'utf8_unicode_ci'", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1480,7 +1483,7 @@ public function testCreateTableWithVirtualAsColumn(): void $this->assertSame("create table `users` (`my_json_column` varchar(255) not null, `my_other_column` varchar(255) as (json_value(`my_json_column`, '$.\"some_attribute\"')))", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1496,7 +1499,7 @@ public function testCreateTableWithVirtualAsColumn(): void public function testCreateTableWithVirtualAsColumnWhenJsonColumnHasArrayKey(): void { $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1511,9 +1514,9 @@ public function testCreateTableWithVirtualAsColumnWhenJsonColumnHasArrayKey(): v public function testCreateTableWithStoredAsColumn(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1526,7 +1529,7 @@ public function testCreateTableWithStoredAsColumn(): void $this->assertSame("create table `users` (`my_column` varchar(255) not null, `my_other_column` varchar(255) as (my_column) stored) default character set utf8 collate 'utf8_unicode_ci'", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1539,7 +1542,7 @@ public function testCreateTableWithStoredAsColumn(): void $this->assertSame("create table `users` (`my_json_column` varchar(255) not null, `my_other_column` varchar(255) as (json_value(`my_json_column`, '$.\"some_attribute\"')) stored)", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1603,18 +1606,17 @@ protected function getConnection( ?MariaDbGrammar $grammar = null, ?MariaDbBuilder $builder = null, string $prefix = '' - ): Connection&MockInterface { - $connection = m::mock(MariaDbConnection::class); - $connection->shouldReceive('usesBackslashEscapes')->passthru(); - $connection->shouldReceive('getConfig')->with('modes')->andReturn(null); - $connection->shouldReceive('getTablePrefix')->andReturn($prefix); - $connection->shouldReceive('getConfig')->with('prefix_indexes')->andReturn(null); + ): Connection&DoubleInterface { + $connection = Double::for(MariaDbConnection::class); + $connection->allows('usesBackslashEscapes')->returns(true); + $connection->allows('getTablePrefix')->returns($prefix); + $connection->allows('getConfig')->with('prefix_indexes')->returns(null); $grammar ??= $this->getGrammar($connection); $builder ??= $this->getBuilder(); - $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); - $connection->shouldReceive('getSchemaBuilder')->andReturn($builder); + $connection->allows('getSchemaGrammar')->returns($grammar); + $connection->allows('getSchemaBuilder')->returns($builder); return $connection; } @@ -1643,8 +1645,8 @@ public function getGrammar(?Connection $connection = null): MariaDbGrammar /** * Get a schema builder mock. */ - public function getBuilder(): MariaDbBuilder&MockInterface + public function getBuilder(): MariaDbBuilder&DoubleInterface { - return mock(MariaDbBuilder::class); + return Double::for(MariaDbBuilder::class); } } diff --git a/tests/Database/DatabaseMigrationCreatorTest.php b/tests/Database/DatabaseMigrationCreatorTest.php index 3e5d10dce..394010d85 100755 --- a/tests/Database/DatabaseMigrationCreatorTest.php +++ b/tests/Database/DatabaseMigrationCreatorTest.php @@ -11,23 +11,26 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use function Hypervel\Coroutine\parallel; class DatabaseMigrationCreatorTest extends TestCase { + use VerifiesDoubles; + public function testBasicCreateMethodStoresMigrationFile(): void { $creator = $this->getCreator(); $creator->expects($this->once())->method('getDatePrefix')->willReturn('foo'); - $creator->getFilesystem()->expects('exists')->with('stubs/migration.stub')->andReturn(false); - $creator->getFilesystem()->expects('get')->with($creator->stubPath() . '/migration.stub')->andReturn('return new class'); + $creator->getFilesystem()->expects('exists')->with('stubs/migration.stub')->returns(false); + $creator->getFilesystem()->expects('get')->with($creator->stubPath() . '/migration.stub')->returns('return new class'); $creator->getFilesystem()->expects('ensureDirectoryExists')->with('foo'); $creator->getFilesystem()->expects('replace')->with('foo/foo_create_bar.php', 'return new class'); - $creator->getFilesystem()->expects('glob')->with('foo/*.php')->andReturn(['foo/foo_create_bar.php']); + $creator->getFilesystem()->expects('glob')->with('foo/*.php')->returns(['foo/foo_create_bar.php']); $creator->getFilesystem()->expects('requireOnce')->with('foo/foo_create_bar.php'); $creator->create('create_bar', 'foo'); @@ -45,11 +48,11 @@ public function testBasicCreateMethodCallsPostCreateHooks(): void }); $creator->expects($this->once())->method('getDatePrefix')->willReturn('foo'); - $creator->getFilesystem()->expects('exists')->with('stubs/migration.update.stub')->andReturn(false); - $creator->getFilesystem()->expects('get')->with($creator->stubPath() . '/migration.update.stub')->andReturn('return new class DummyTable'); + $creator->getFilesystem()->expects('exists')->with('stubs/migration.update.stub')->returns(false); + $creator->getFilesystem()->expects('get')->with($creator->stubPath() . '/migration.update.stub')->returns('return new class DummyTable'); $creator->getFilesystem()->expects('ensureDirectoryExists')->with('foo'); $creator->getFilesystem()->expects('replace')->with('foo/foo_create_bar.php', 'return new class baz'); - $creator->getFilesystem()->expects('glob')->with('foo/*.php')->andReturn(['foo/foo_create_bar.php']); + $creator->getFilesystem()->expects('glob')->with('foo/*.php')->returns(['foo/foo_create_bar.php']); $creator->getFilesystem()->expects('requireOnce')->with('foo/foo_create_bar.php'); $creator->create('create_bar', 'foo', $table); @@ -64,11 +67,11 @@ public function testTableUpdateMigrationStoresMigrationFile(): void { $creator = $this->getCreator(); $creator->expects($this->once())->method('getDatePrefix')->willReturn('foo'); - $creator->getFilesystem()->expects('exists')->with('stubs/migration.update.stub')->andReturn(false); - $creator->getFilesystem()->expects('get')->with($creator->stubPath() . '/migration.update.stub')->andReturn('return new class DummyTable'); + $creator->getFilesystem()->expects('exists')->with('stubs/migration.update.stub')->returns(false); + $creator->getFilesystem()->expects('get')->with($creator->stubPath() . '/migration.update.stub')->returns('return new class DummyTable'); $creator->getFilesystem()->expects('ensureDirectoryExists')->with('foo'); $creator->getFilesystem()->expects('replace')->with('foo/foo_create_bar.php', 'return new class baz'); - $creator->getFilesystem()->expects('glob')->with('foo/*.php')->andReturn(['foo/foo_create_bar.php']); + $creator->getFilesystem()->expects('glob')->with('foo/*.php')->returns(['foo/foo_create_bar.php']); $creator->getFilesystem()->expects('requireOnce')->with('foo/foo_create_bar.php'); $creator->create('create_bar', 'foo', 'baz'); @@ -78,11 +81,11 @@ public function testTableCreationMigrationStoresMigrationFile(): void { $creator = $this->getCreator(); $creator->expects($this->once())->method('getDatePrefix')->willReturn('foo'); - $creator->getFilesystem()->expects('exists')->with('stubs/migration.create.stub')->andReturn(false); - $creator->getFilesystem()->expects('get')->with($creator->stubPath() . '/migration.create.stub')->andReturn('return new class DummyTable'); + $creator->getFilesystem()->expects('exists')->with('stubs/migration.create.stub')->returns(false); + $creator->getFilesystem()->expects('get')->with($creator->stubPath() . '/migration.create.stub')->returns('return new class DummyTable'); $creator->getFilesystem()->expects('ensureDirectoryExists')->with('foo'); $creator->getFilesystem()->expects('replace')->with('foo/foo_create_bar.php', 'return new class baz'); - $creator->getFilesystem()->expects('glob')->with('foo/*.php')->andReturn(['foo/foo_create_bar.php']); + $creator->getFilesystem()->expects('glob')->with('foo/*.php')->returns(['foo/foo_create_bar.php']); $creator->getFilesystem()->expects('requireOnce')->with('foo/foo_create_bar.php'); $creator->create('create_bar', 'foo', 'baz', true); @@ -94,7 +97,7 @@ public function testTableUpdateMigrationWontCreateDuplicateClass(): void $creator = $this->getCreator([]); - $creator->getFilesystem()->expects('glob')->with('foo/*.php')->andReturn(['foo/foo_create_bar.php']); + $creator->getFilesystem()->expects('glob')->with('foo/*.php')->returns(['foo/foo_create_bar.php']); $creator->getFilesystem()->expects('requireOnce')->with('foo/foo_create_bar.php'); $creator->create('migration_creator_fake_migration', 'foo'); @@ -149,8 +152,8 @@ protected function getDatePrefix(): string public function testOverriddenCreateMethodRetainsExistingDatePrefixBehavior(): void { - $files = m::mock(Filesystem::class); - $files->shouldNotReceive('glob'); + $files = Double::for(Filesystem::class); + $files->expects('glob')->never(); $creator = new class($files, 'stubs') extends MigrationCreator { /** @@ -205,10 +208,10 @@ public function testCustomStubReadFailureDoesNotPublishAMigration(): void { $exception = new RuntimeException('Unable to read stub.'); $creator = $this->getCreator([]); - $creator->getFilesystem()->shouldReceive('glob')->once()->with('foo/*.php')->andReturn([]); - $creator->getFilesystem()->shouldReceive('get')->once()->with('package.stub')->andThrow($exception); - $creator->getFilesystem()->shouldNotReceive('ensureDirectoryExists'); - $creator->getFilesystem()->shouldNotReceive('replace'); + $creator->getFilesystem()->expects('glob')->with('foo/*.php')->returns([]); + $creator->getFilesystem()->expects('get')->with('package.stub')->throws($exception); + $creator->getFilesystem()->expects('ensureDirectoryExists')->never(); + $creator->getFilesystem()->expects('replace')->never(); try { $creator->create('create_bar', 'foo', stubPath: 'package.stub'); @@ -223,10 +226,10 @@ public function testPublicationFailureDoesNotFirePostCreateHooks(): void $exception = new RuntimeException('Unable to publish migration.'); $creator = $this->getCreator(); $creator->expects($this->once())->method('getDatePrefix')->willReturn('foo'); - $creator->getFilesystem()->shouldReceive('glob')->once()->with('foo/*.php')->andReturn([]); - $creator->getFilesystem()->shouldReceive('get')->once()->with('package.stub')->andReturn('return new class'); - $creator->getFilesystem()->shouldReceive('ensureDirectoryExists')->once()->with('foo'); - $creator->getFilesystem()->shouldReceive('replace')->once()->andThrow($exception); + $creator->getFilesystem()->expects('glob')->with('foo/*.php')->returns([]); + $creator->getFilesystem()->expects('get')->with('package.stub')->returns('return new class'); + $creator->getFilesystem()->expects('ensureDirectoryExists')->with('foo'); + $creator->getFilesystem()->expects('replace')->throws($exception); $hookCalled = false; $creator->afterCreate(function () use (&$hookCalled): void { @@ -246,7 +249,7 @@ public function testPublicationFailureDoesNotFirePostCreateHooks(): void public function testGlobFailureIsReported(): void { $creator = $this->getCreator([]); - $creator->getFilesystem()->shouldReceive('glob')->once()->with('foo/*.php')->andReturnFalse(); + $creator->getFilesystem()->expects('glob')->with('foo/*.php')->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIsOrContains('Unable to read files matching [foo/*.php].'); @@ -256,7 +259,7 @@ public function testGlobFailureIsReported(): void public function testDatePrefixUsesTheFrameworkClockWithoutAnActivePath(): void { - $creator = new class(m::mock(Filesystem::class)) extends MigrationCreator { + $creator = new class(Double::for(Filesystem::class)) extends MigrationCreator { public function datePrefix(): string { return $this->getDatePrefix(); @@ -318,7 +321,7 @@ public function testCollisionFreePrefixesAreIsolatedAcrossConcurrentPaths(): voi */ protected function getCreator(array $methods = ['getDatePrefix']): MigrationCreator { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $customStubs = 'stubs'; if ($methods === []) { diff --git a/tests/Database/DatabaseMigrationInstallCommandTest.php b/tests/Database/DatabaseMigrationInstallCommandTest.php index 229b0218f..1dcee40ca 100755 --- a/tests/Database/DatabaseMigrationInstallCommandTest.php +++ b/tests/Database/DatabaseMigrationInstallCommandTest.php @@ -5,35 +5,30 @@ namespace Hypervel\Tests\Database; use Hypervel\Config\Repository; -use Hypervel\Console\CommandMutex; use Hypervel\Context\CoroutineContext; use Hypervel\Database\ConnectionResolver; use Hypervel\Database\Console\Migrations\InstallCommand; use Hypervel\Database\Migrations\MigrationRepositoryInterface; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; class DatabaseMigrationInstallCommandTest extends TestCase { - protected function tearDown(): void - { - CoroutineContext::forget(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY); - - parent::tearDown(); - } + use VerifiesDoubles; public function testFireCallsRepositoryToInstall(): void { $app = new ApplicationDatabaseInstallStub; - $repository = m::mock(MigrationRepositoryInterface::class); + $repository = Double::for(MigrationRepositoryInterface::class); $command = new InstallCommand($repository); $command->setHypervel($app); $repository->expects('setSource')->with('foo'); $repository->expects('createRepository'); - $repository->expects('repositoryExists')->andReturn(false); + $repository->expects('repositoryExists')->returns(false); $this->runCommand($command, ['--database' => 'foo']); } @@ -41,11 +36,12 @@ public function testFireCallsRepositoryToInstall(): void public function testFireCallsRepositoryToInstallExists(): void { $app = new ApplicationDatabaseInstallStub; - $repository = m::mock(MigrationRepositoryInterface::class); + $repository = Double::for(MigrationRepositoryInterface::class); $command = new InstallCommand($repository); $command->setHypervel($app); $repository->expects('setSource')->with('foo'); - $repository->expects('repositoryExists')->andReturn(true); + $repository->expects('repositoryExists')->returns(true); + $repository->expects('createRepository')->never(); $this->runCommand($command, ['--database' => 'foo']); } @@ -62,11 +58,11 @@ public function testSetSourceReceivesSwappedNameWhenMigrationsConnectionConfigur ], ])); - $repository = m::mock(MigrationRepositoryInterface::class); + $repository = Double::for(MigrationRepositoryInterface::class); $command = new InstallCommand($repository); $command->setHypervel($app); $repository->expects('setSource')->with('pgsql'); - $repository->expects('repositoryExists')->andReturn(false); + $repository->expects('repositoryExists')->returns(false); $repository->expects('createRepository'); $this->runCommand($command, ['--database' => 'pgsql-pooled']); @@ -89,11 +85,12 @@ public function testSetSourceRoutesThroughDefaultWhenNoDatabaseOptionGiven(): vo ], ])); - $repository = m::mock(MigrationRepositoryInterface::class); + $repository = Double::for(MigrationRepositoryInterface::class); $command = new InstallCommand($repository); $command->setHypervel($app); $repository->expects('setSource')->with('pgsql'); - $repository->expects('repositoryExists')->andReturn(true); + $repository->expects('repositoryExists')->returns(true); + $repository->expects('createRepository')->never(); $this->runCommand($command); } @@ -123,11 +120,12 @@ public function testSetSourceHonorsContextOverrideWhenNoDatabaseOptionGiven(): v CoroutineContext::set(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY, 'tenant-pooled'); - $repository = m::mock(MigrationRepositoryInterface::class); + $repository = Double::for(MigrationRepositoryInterface::class); $command = new InstallCommand($repository); $command->setHypervel($app); $repository->expects('setSource')->with('tenant-direct'); - $repository->expects('repositoryExists')->andReturn(true); + $repository->expects('repositoryExists')->returns(true); + $repository->expects('createRepository')->never(); $this->runCommand($command); } @@ -145,10 +143,6 @@ class ApplicationDatabaseInstallStub extends Application { public function __construct() { - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); - $mutex->shouldReceive('release')->andReturn(true); - $this->instance(CommandMutex::class, $mutex); $this->instance('env', 'development'); static::setInstance($this); diff --git a/tests/Database/DatabaseMigrationMakeCommandTest.php b/tests/Database/DatabaseMigrationMakeCommandTest.php index 1aaaacccf..05b02d65f 100755 --- a/tests/Database/DatabaseMigrationMakeCommandTest.php +++ b/tests/Database/DatabaseMigrationMakeCommandTest.php @@ -4,17 +4,19 @@ namespace Hypervel\Tests\Database; -use Hypervel\Console\CommandMutex; use Hypervel\Database\Console\Migrations\MigrateMakeCommand; use Hypervel\Database\Migrations\MigrationCreator; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; class DatabaseMigrationMakeCommandTest extends TestCase { + use VerifiesDoubles; + // REMOVED: make:migration no longer dumps Composer autoload files or // accepts Laravel's deprecated --fullpath option. @@ -22,12 +24,12 @@ public function testBasicCreateGivesCreatorProperArguments(): void { $app = new ApplicationDatabaseMigrationMakeStub; $app->useDatabasePath(__DIR__); - $creator = m::mock(MigrationCreator::class); + $creator = Double::for(MigrationCreator::class); $command = new MigrateMakeCommand($creator); $command->setHypervel($app); $creator->expects('create') ->with('create_foo', __DIR__ . DIRECTORY_SEPARATOR . 'migrations', 'foo', true) - ->andReturn(__DIR__ . '/Fixtures/migrations/2021_04_23_110457_create_foo.php'); + ->returns(__DIR__ . '/Fixtures/migrations/2021_04_23_110457_create_foo.php'); $this->runCommand($command, ['name' => 'create_foo']); } @@ -36,12 +38,12 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenNameIsStudlyCase() { $app = new ApplicationDatabaseMigrationMakeStub; $app->useDatabasePath(__DIR__); - $creator = m::mock(MigrationCreator::class); + $creator = Double::for(MigrationCreator::class); $command = new MigrateMakeCommand($creator); $command->setHypervel($app); $creator->expects('create') ->with('create_foo', __DIR__ . DIRECTORY_SEPARATOR . 'migrations', 'foo', true) - ->andReturn(__DIR__ . '/Fixtures/migrations/2021_04_23_110457_create_foo.php'); + ->returns(__DIR__ . '/Fixtures/migrations/2021_04_23_110457_create_foo.php'); $this->runCommand($command, ['name' => 'CreateFoo']); } @@ -50,12 +52,12 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenTableIsSet(): void { $app = new ApplicationDatabaseMigrationMakeStub; $app->useDatabasePath(__DIR__); - $creator = m::mock(MigrationCreator::class); + $creator = Double::for(MigrationCreator::class); $command = new MigrateMakeCommand($creator); $command->setHypervel($app); $creator->expects('create') ->with('create_foo', __DIR__ . DIRECTORY_SEPARATOR . 'migrations', 'users', true) - ->andReturn(__DIR__ . '/Fixtures/migrations/2021_04_23_110457_create_foo.php'); + ->returns(__DIR__ . '/Fixtures/migrations/2021_04_23_110457_create_foo.php'); $this->runCommand($command, ['name' => 'create_foo', '--create' => 'users']); } @@ -64,12 +66,12 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenCreateTablePattern { $app = new ApplicationDatabaseMigrationMakeStub; $app->useDatabasePath(__DIR__); - $creator = m::mock(MigrationCreator::class); + $creator = Double::for(MigrationCreator::class); $command = new MigrateMakeCommand($creator); $command->setHypervel($app); $creator->expects('create') ->with('create_users_table', __DIR__ . DIRECTORY_SEPARATOR . 'migrations', 'users', true) - ->andReturn(__DIR__ . '/Fixtures/migrations/2021_04_23_110457_create_users_table.php'); + ->returns(__DIR__ . '/Fixtures/migrations/2021_04_23_110457_create_users_table.php'); $this->runCommand($command, ['name' => 'create_users_table']); } @@ -77,13 +79,13 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenCreateTablePattern public function testCanSpecifyPathToCreateMigrationsIn(): void { $app = new ApplicationDatabaseMigrationMakeStub; - $creator = m::mock(MigrationCreator::class); + $creator = Double::for(MigrationCreator::class); $command = new MigrateMakeCommand($creator); $command->setHypervel($app); $app->setBasePath('/home/hypervel'); $creator->expects('create') ->with('create_foo', '/home/hypervel/vendor/hypervel-package/migrations', 'users', true) - ->andReturn('/home/hypervel/vendor/hypervel-package/migrations/2021_04_23_110457_create_foo.php'); + ->returns('/home/hypervel/vendor/hypervel-package/migrations/2021_04_23_110457_create_foo.php'); $this->runCommand($command, ['name' => 'create_foo', '--path' => 'vendor/hypervel-package/migrations', '--create' => 'users']); } @@ -100,10 +102,6 @@ class ApplicationDatabaseMigrationMakeStub extends Application { public function __construct() { - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); - $mutex->shouldReceive('release')->andReturn(true); - $this->instance(CommandMutex::class, $mutex); $this->instance('env', 'development'); static::setInstance($this); diff --git a/tests/Database/DatabaseMigrationMigrateCommandTest.php b/tests/Database/DatabaseMigrationMigrateCommandTest.php index 5e85fcf58..2321ed706 100755 --- a/tests/Database/DatabaseMigrationMigrateCommandTest.php +++ b/tests/Database/DatabaseMigrationMigrateCommandTest.php @@ -26,7 +26,8 @@ use Hypervel\Prompts\Prompt; use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PDOException; use PHPUnit\Framework\Attributes\TestWith; @@ -40,6 +41,8 @@ class DatabaseMigrationMigrateCommandTest extends TestCase { + use VerifiesDoubles; + protected function tearDown(): void { RecordingMigrationMySqlConnection::reset(); @@ -52,13 +55,13 @@ public function testBasicMigrationsCallMigratorWithProperArguments(): void { $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $dispatcher = new EventsDispatcher; $command = new MigrateCommand($migrator, $dispatcher); $command->setHypervel($app); $this->expectMigrationPreflight($migrator); - $migrator->expects('hasRunAnyMigrations')->andReturn(true); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('run')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => false]); $this->runCommand($command); @@ -68,21 +71,21 @@ public function testMigrationsCanBeRunWithStoredSchema(): void { $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $dispatcher = new EventFake(new EventsDispatcher); $command = new MigrateCommand($migrator, $dispatcher); $command->setHypervel($app); $this->expectMigrationPreflight($migrator); - $migrator->expects('hasRunAnyMigrations')->andReturn(false); - $connection = m::mock(MySqlConnection::class); - $migrator->expects('resolveConnection')->andReturn($connection); - $connection->expects('getName')->andReturn('mysql'); + $migrator->expects('hasRunAnyMigrations')->returns(false); + $connection = Double::for(MySqlConnection::class); + $migrator->expects('resolveConnection')->returns($connection); + $connection->expects('getName')->returns('mysql'); $migrator->expects('deleteRepository'); - $schemaState = m::mock(MySqlSchemaState::class); - $connection->expects('getSchemaState')->andReturn($schemaState); - $schemaState->expects('handleOutputUsing')->andReturnSelf(); + $schemaState = Double::for(MySqlSchemaState::class); + $connection->expects('getSchemaState')->returns($schemaState); + $schemaState->expects('handleOutputUsing')->returns($schemaState); $schemaState->expects('load')->with(__DIR__ . '/Fixtures/schema.sql'); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('run')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => false]); $this->runCommand($command, ['--schema-path' => __DIR__ . '/Fixtures/schema.sql']); @@ -94,22 +97,22 @@ public function testStoredSchemaDoesNotDispatchWithoutListeners(): void { $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $migrator = m::mock(Migrator::class); - $dispatcher = m::mock(Dispatcher::class); + $migrator = Double::for(Migrator::class); + $dispatcher = Double::for(Dispatcher::class); $command = new MigrateCommand($migrator, $dispatcher); $command->setHypervel($app); $this->expectMigrationPreflight($migrator); - $migrator->expects('hasRunAnyMigrations')->andReturn(false); - $connection = m::mock(Connection::class); - $migrator->expects('resolveConnection')->andReturn($connection); + $migrator->expects('hasRunAnyMigrations')->returns(false); + $connection = Double::for(Connection::class); + $migrator->expects('resolveConnection')->returns($connection); $migrator->expects('deleteRepository'); - $schemaState = m::mock(SchemaState::class); - $connection->expects('getSchemaState')->andReturn($schemaState); - $schemaState->expects('handleOutputUsing')->andReturnSelf(); + $schemaState = Double::for(SchemaState::class); + $connection->expects('getSchemaState')->returns($schemaState); + $schemaState->expects('handleOutputUsing')->returns($schemaState); $schemaState->expects('load')->with(__DIR__ . '/Fixtures/schema.sql'); - $dispatcher->expects('hasListeners')->with(SchemaLoaded::class)->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); - $migrator->expects('setOutput')->andReturn($migrator); + $dispatcher->expects('hasListeners')->with(SchemaLoaded::class)->returns(false); + $dispatcher->expects('dispatch')->never(); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('run')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => false]); $this->runCommand($command, ['--schema-path' => __DIR__ . '/Fixtures/schema.sql']); @@ -119,14 +122,14 @@ public function testMigrationRepositoryCreatedWhenNecessary(): void { $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $dispatcher = new EventsDispatcher; $params = [$migrator, $dispatcher]; $command = $this->getMockBuilder(MigrateCommand::class)->onlyMethods(['callSilent'])->setConstructorArgs($params)->getMock(); $command->setHypervel($app); $this->expectMigrationPreflight($migrator, repositoryExists: false); - $migrator->expects('hasRunAnyMigrations')->andReturn(true); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('run')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => false]); $command->expects($this->once())->method('callSilent')->with('migrate:install', []); @@ -137,13 +140,13 @@ public function testTheCommandMayBePretended(): void { $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $dispatcher = new EventsDispatcher; $command = new MigrateCommand($migrator, $dispatcher); $command->setHypervel($app); $this->expectMigrationPreflight($migrator); - $migrator->expects('hasRunAnyMigrations')->andReturn(true); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('run')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => true, 'step' => false]); $this->runCommand($command, ['--pretend' => true]); @@ -153,13 +156,13 @@ public function testTheDatabaseMayBeSet(): void { $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $dispatcher = new EventsDispatcher; $command = new MigrateCommand($migrator, $dispatcher); $command->setHypervel($app); $this->expectMigrationPreflight($migrator, 'foo'); - $migrator->expects('hasRunAnyMigrations')->andReturn(true); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('run')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => false]); $this->runCommand($command, ['--database' => 'foo']); @@ -169,13 +172,13 @@ public function testStepMayBeSet(): void { $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $dispatcher = new EventsDispatcher; $command = new MigrateCommand($migrator, $dispatcher); $command->setHypervel($app); $this->expectMigrationPreflight($migrator); - $migrator->expects('hasRunAnyMigrations')->andReturn(true); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('run')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => true]); $this->runCommand($command, ['--step' => true]); @@ -186,7 +189,7 @@ public function testGracefulReturnsSuccessWhenRunMigrationsThrows(): void $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $command = $this->getMockBuilder(MigrateCommand::class) ->onlyMethods(['runMigrations']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class), $dispatcher = m::mock(Dispatcher::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class)]) ->getMock(); $command->setHypervel($app); $command->expects($this->once())->method('runMigrations')->willThrowException(new RuntimeException('boom')); @@ -202,13 +205,13 @@ public function testSeedOptionRunsSeederAfterMigrations(): void $app->useDatabasePath(__DIR__); $command = $this->getMockBuilder(MigrateCommand::class) ->onlyMethods(['call']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class), $dispatcher = m::mock(Dispatcher::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class)]) ->getMock(); $command->setHypervel($app); $this->expectMigrationPreflight($migrator); - $migrator->shouldReceive('hasRunAnyMigrations')->andReturn(true); - $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); - $migrator->shouldReceive('run')->once()->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => false]); + $migrator->allows('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); + $migrator->expects('run')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => false]); $command->expects($this->once())->method('call')->with('db:seed', [ '--class' => 'Database\Seeders\CustomSeeder', '--force' => true, @@ -225,13 +228,13 @@ public function testSeedFailureHonorsGracefulOption(bool $graceful): void $app->useDatabasePath(__DIR__); $command = $this->getMockBuilder(MigrateCommand::class) ->onlyMethods(['call']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class), m::mock(Dispatcher::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class), Double::for(Dispatcher::class)]) ->getMock(); $command->setHypervel($app); $this->expectMigrationPreflight($migrator); - $migrator->shouldReceive('hasRunAnyMigrations')->andReturn(true); - $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); - $migrator->shouldReceive('run')->once(); + $migrator->allows('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); + $migrator->expects('run'); $command->expects($this->once())->method('call')->with('db:seed', [ '--class' => 'Database\Seeders\DatabaseSeeder', '--force' => true, @@ -260,13 +263,13 @@ public function testSeedOptionForwardsDatabaseToSeedCommand(): void $app->useDatabasePath(__DIR__); $command = $this->getMockBuilder(MigrateCommand::class) ->onlyMethods(['call']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class), $dispatcher = m::mock(Dispatcher::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class)]) ->getMock(); $command->setHypervel($app); $this->expectMigrationPreflight($migrator, 'pgsql-pooled'); - $migrator->shouldReceive('hasRunAnyMigrations')->andReturn(true); - $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); - $migrator->shouldReceive('run')->once(); + $migrator->allows('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); + $migrator->expects('run'); $command->expects($this->once())->method('call')->with('db:seed', [ '--database' => 'pgsql-pooled', '--class' => 'Database\Seeders\DatabaseSeeder', @@ -293,13 +296,13 @@ public function testMigrateWithSeedDoesNotLeakConnectionStateOrMutateConfig(): v $command = $this->getMockBuilder(MigrateCommand::class) ->onlyMethods(['call']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class), $dispatcher = m::mock(Dispatcher::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class)]) ->getMock(); $command->setHypervel($app); $this->expectMigrationPreflight($migrator, 'pgsql-pooled'); - $migrator->shouldReceive('hasRunAnyMigrations')->andReturn(true); - $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); - $migrator->shouldReceive('run')->once(); + $migrator->allows('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); + $migrator->expects('run'); $command->expects($this->once())->method('call'); $contextBefore = CoroutineContext::get( @@ -330,15 +333,15 @@ public function testAllTargetsAreInspectedAndMissingSqliteDatabaseIsCreatedBefor $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $command = new MigrateCommand($migrator = m::mock(Migrator::class), $dispatcher = m::mock(Dispatcher::class)); + $command = new MigrateCommand($migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class)); $command->setHypervel($app); $paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations']; $currentConnection = null; $secondaryInspections = 0; - $migrator->shouldReceive('paths')->once()->andReturn([]); - $migrator->shouldReceive('getMigrationConnections')->once()->with($paths, null)->andReturn(['default', 'analytics']); - $migrator->shouldReceive('usingConnection')->times(4)->andReturnUsing( + $migrator->expects('paths')->returns([]); + $migrator->expects('getMigrationConnections')->with($paths, null)->returns(['default', 'analytics']); + $migrator->expects('usingConnection')->times(4)->resolves( function ($name, $callback) use (&$currentConnection) { $previousConnection = $currentConnection; $currentConnection = $name; @@ -350,7 +353,7 @@ function ($name, $callback) use (&$currentConnection) { } } ); - $migrator->shouldReceive('repositoryExists')->times(4)->andReturnUsing( + $migrator->expects('repositoryExists')->times(4)->resolves( function () use (&$currentConnection, &$secondaryInspections, $path): bool { if ($currentConnection === 'analytics') { ++$secondaryInspections; @@ -365,9 +368,9 @@ function () use (&$currentConnection, &$secondaryInspections, $path): bool { return true; } ); - $migrator->shouldReceive('hasRunAnyMigrations')->once()->andReturn(true); - $migrator->shouldReceive('setOutput')->once()->andReturn($migrator); - $migrator->shouldReceive('run')->once()->with($paths, ['pretend' => false, 'step' => false])->andReturnUsing( + $migrator->expects('hasRunAnyMigrations')->returns(true); + $migrator->expects('setOutput')->returns($migrator); + $migrator->expects('run')->with($paths, ['pretend' => false, 'step' => false])->resolves( function () use ($path, &$secondaryInspections): array { $this->assertFileExists($path); $this->assertSame(2, $secondaryInspections); @@ -443,16 +446,16 @@ public function testDecliningMissingDatabaseCreationCreatesNothing(): void public function testMissingDatabaseClassifierRecognizesOnlySupportedSignals(): void { - $migrator = m::mock(Migrator::class); - $mysqlConnection = m::mock(Connection::class); - $mysqlConnection->shouldReceive('getDriverName')->andReturn('mysql'); - $postgresConnection = m::mock(Connection::class); - $postgresConnection->shouldReceive('getDriverName')->andReturn('pgsql'); - $postgresConnection->shouldReceive('getDatabaseName')->andReturn('analytics'); - $migrator->shouldReceive('resolveConnection')->andReturnUsing( + $migrator = Double::for(Migrator::class); + $mysqlConnection = Double::for(Connection::class); + $mysqlConnection->allows('getDriverName')->returns('mysql'); + $postgresConnection = Double::for(Connection::class); + $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, m::mock(Dispatcher::class)); + $command = new TestableMigrateCommand($migrator, Double::for(Dispatcher::class)); $sqliteCause = new SQLiteDatabaseDoesNotExistException('/missing.sqlite'); $mysqlCause = new PDOException('Unknown database', 1049); @@ -493,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(m::mock(Migrator::class), m::mock(Dispatcher::class)); + $command = new TestableMigrateCommand(Double::for(Migrator::class), Double::for(Dispatcher::class)); $command->setHypervel($app); $command->probeCreateMissingServerDatabase($connection); @@ -532,7 +535,7 @@ public function testPostgresAdminCreationRemovesConnectViaDatabaseAndDisconnects ], 'pgsql'); $failure = new RuntimeException('create failed'); RecordingMigrationPostgresConnection::$unpreparedException = $failure; - $command = new TestableMigrateCommand(m::mock(Migrator::class), m::mock(Dispatcher::class)); + $command = new TestableMigrateCommand(Double::for(Migrator::class), Double::for(Dispatcher::class)); $command->setHypervel($app); $caught = null; @@ -565,28 +568,28 @@ private function expectMigrationPreflight( ): void { $paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations']; - $migrator->expects('paths')->andReturn([]); - $migrator->expects('getMigrationConnections')->with($paths, $database)->andReturn([$database ?? 'default']); - $migrator->shouldReceive('usingConnection')->twice()->andReturnUsing(function (?string $name, callable $callback): mixed { + $migrator->expects('paths')->returns([]); + $migrator->expects('getMigrationConnections')->with($paths, $database)->returns([$database ?? 'default']); + $migrator->expects('usingConnection')->times(2)->resolves(function (?string $name, callable $callback): mixed { return $callback(); }); - $migrator->shouldReceive('repositoryExists')->twice()->andReturn($repositoryExists); + $migrator->expects('repositoryExists')->times(2)->returns($repositoryExists); } private function makeCommandWithMissingSqliteTarget(string $path): TestableMigrateCommand { $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $command = new TestableMigrateCommand($migrator = m::mock(Migrator::class), m::mock(Dispatcher::class)); + $command = new TestableMigrateCommand($migrator = Double::for(Migrator::class), Double::for(Dispatcher::class)); $command->setHypervel($app); $paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations']; - $migrator->shouldReceive('paths')->once()->andReturn([]); - $migrator->shouldReceive('getMigrationConnections')->once()->with($paths, null)->andReturn(['analytics']); - $migrator->shouldReceive('usingConnection')->once()->andReturnUsing(function ($name, $callback) { + $migrator->expects('paths')->returns([]); + $migrator->expects('getMigrationConnections')->with($paths, null)->returns(['analytics']); + $migrator->expects('usingConnection')->resolves(function ($name, $callback) { return $callback(); }); - $migrator->shouldReceive('repositoryExists')->once()->andThrow(new SQLiteDatabaseDoesNotExistException($path)); - $migrator->shouldReceive('run')->never(); + $migrator->expects('repositoryExists')->throws(new SQLiteDatabaseDoesNotExistException($path)); + $migrator->expects('run')->never(); return $command; } @@ -608,8 +611,8 @@ class ApplicationDatabaseMigrationStub extends Application { public function __construct(array $data = []) { - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); + $mutex = Double::for(CommandMutex::class); + $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 0b691a0fe..e51b195ef 100755 --- a/tests/Database/DatabaseMigrationRefreshCommandTest.php +++ b/tests/Database/DatabaseMigrationRefreshCommandTest.php @@ -4,7 +4,6 @@ namespace Hypervel\Tests\Database; -use Hypervel\Console\CommandMutex; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Database\Console\Migrations\MigrateCommand; use Hypervel\Database\Console\Migrations\RefreshCommand; @@ -13,8 +12,9 @@ use Hypervel\Database\Events\DatabaseRefreshed; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\Matcher\MatcherInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\Console\Application as ConsoleApplication; @@ -24,33 +24,35 @@ class DatabaseMigrationRefreshCommandTest extends TestCase { + use VerifiesDoubles; + public function testRefreshCommandCallsCommandsWithProperArguments(): void { $command = new RefreshCommand; $app = new ApplicationDatabaseRefreshStub(['path.database' => __DIR__]); - $events = m::mock(Dispatcher::class)->shouldIgnoreMissing(); + $events = Double::for(Dispatcher::class); $dispatcher = $app->instance(Dispatcher::class, $events); - $console = m::mock(ConsoleApplication::class)->makePartial(); - $console->__construct(); + $console = Double::for(new ConsoleApplication)->passthru(); $command->setHypervel($app); $command->setApplication($console); - $resetCommand = m::mock(ResetCommand::class); - $migrateCommand = m::mock(MigrateCommand::class); + $resetCommand = Double::for(ResetCommand::class); + $migrateCommand = Double::for(MigrateCommand::class); - $console->expects('find')->with('migrate:reset')->andReturn($resetCommand); - $console->expects('find')->with('migrate')->andReturn($migrateCommand); - $dispatcher->expects('hasListeners')->with(DatabaseRefreshed::class)->andReturnTrue(); - $dispatcher->expects('dispatch')->with(m::type(DatabaseRefreshed::class)); + $console->expects('find')->with('migrate:reset')->returns($resetCommand); + $console->expects('find')->with('migrate')->returns($migrateCommand); + $dispatcher->allows('hasListeners')->with(Argument::satisfies(fn (string $event): bool => $event !== DatabaseRefreshed::class))->returns(false); + $dispatcher->expects('hasListeners')->with(DatabaseRefreshed::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(DatabaseRefreshed::class)); $quote = DIRECTORY_SEPARATOR === '\\' ? '"' : "'"; - $resetCommand->expects('setApplication')->with($console); - $resetCommand->expects('setHypervel')->with($app); - $resetCommand->expects('run')->with(new InputMatcher("--force=1 {$quote}migrate:reset{$quote}"), m::any()); - $migrateCommand->expects('setApplication')->with($console); - $migrateCommand->expects('setHypervel')->with($app); - $migrateCommand->expects('run')->with(new InputMatcher('--force=1 migrate'), m::any()); + $resetCommand->expects('setApplication')->with(Argument::same($console)); + $resetCommand->expects('setHypervel')->with(Argument::same($app)); + $resetCommand->expects('run')->with(Argument::satisfies(fn (ArrayInput $input): bool => (string) $input === "--force=1 {$quote}migrate:reset{$quote}"), Argument::any()); + $migrateCommand->expects('setApplication')->with(Argument::same($console)); + $migrateCommand->expects('setHypervel')->with(Argument::same($app)); + $migrateCommand->expects('run')->with(Argument::satisfies(fn (ArrayInput $input): bool => (string) $input === '--force=1 migrate'), Argument::any()); $this->runCommand($command); } @@ -60,28 +62,28 @@ public function testRefreshCommandCallsCommandsWithStep(): void $command = new RefreshCommand; $app = new ApplicationDatabaseRefreshStub(['path.database' => __DIR__]); - $events = m::mock(Dispatcher::class)->shouldIgnoreMissing(); + $events = Double::for(Dispatcher::class); $dispatcher = $app->instance(Dispatcher::class, $events); - $console = m::mock(ConsoleApplication::class)->makePartial(); - $console->__construct(); + $console = Double::for(new ConsoleApplication)->passthru(); $command->setHypervel($app); $command->setApplication($console); - $rollbackCommand = m::mock(RollbackCommand::class); - $migrateCommand = m::mock(MigrateCommand::class); + $rollbackCommand = Double::for(RollbackCommand::class); + $migrateCommand = Double::for(MigrateCommand::class); - $console->expects('find')->with('migrate:rollback')->andReturn($rollbackCommand); - $console->expects('find')->with('migrate')->andReturn($migrateCommand); - $dispatcher->expects('hasListeners')->with(DatabaseRefreshed::class)->andReturnTrue(); - $dispatcher->expects('dispatch')->with(m::type(DatabaseRefreshed::class)); + $console->expects('find')->with('migrate:rollback')->returns($rollbackCommand); + $console->expects('find')->with('migrate')->returns($migrateCommand); + $dispatcher->allows('hasListeners')->with(Argument::satisfies(fn (string $event): bool => $event !== DatabaseRefreshed::class))->returns(false); + $dispatcher->expects('hasListeners')->with(DatabaseRefreshed::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(DatabaseRefreshed::class)); $quote = DIRECTORY_SEPARATOR === '\\' ? '"' : "'"; - $rollbackCommand->expects('setApplication')->with($console); - $rollbackCommand->expects('setHypervel')->with($app); - $rollbackCommand->expects('run')->with(new InputMatcher("--step=2 --force=1 {$quote}migrate:rollback{$quote}"), m::any()); - $migrateCommand->expects('setApplication')->with($console); - $migrateCommand->expects('setHypervel')->with($app); - $migrateCommand->expects('run')->with(new InputMatcher('--force=1 migrate'), m::any()); + $rollbackCommand->expects('setApplication')->with(Argument::same($console)); + $rollbackCommand->expects('setHypervel')->with(Argument::same($app)); + $rollbackCommand->expects('run')->with(Argument::satisfies(fn (ArrayInput $input): bool => (string) $input === "--step=2 --force=1 {$quote}migrate:rollback{$quote}"), Argument::any()); + $migrateCommand->expects('setApplication')->with(Argument::same($console)); + $migrateCommand->expects('setHypervel')->with(Argument::same($app)); + $migrateCommand->expects('run')->with(Argument::satisfies(fn (ArrayInput $input): bool => (string) $input === '--force=1 migrate'), Argument::any()); $this->runCommand($command, ['--step' => '2']); } @@ -90,8 +92,8 @@ 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, m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->byDefault()->andReturnFalse(); + $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class)); + $dispatcher->allows('hasListeners')->returns(false); $command = $this->getMockBuilder(RefreshCommand::class)->onlyMethods(['call'])->getMock(); $command->setHypervel($app); $operations = []; @@ -100,8 +102,8 @@ public function testChildFailureStopsRefresh(string $failedCommand, array $optio return $name === $failedCommand ? 1 : 0; }); - $dispatcher->shouldReceive('hasListeners')->with(DatabaseRefreshed::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->with(m::type(DatabaseRefreshed::class))->andReturnUsing(function () use (&$operations): void { + $dispatcher->allows('hasListeners')->with(DatabaseRefreshed::class)->returns(true); + $dispatcher->allows('dispatch')->with(Argument::type(DatabaseRefreshed::class))->resolves(function () use (&$operations): void { $operations[] = 'event'; }); $caught = null; @@ -146,10 +148,9 @@ public function testRefreshCommandExitsWhenProhibited(): void $command = new RefreshCommand; $app = new ApplicationDatabaseRefreshStub(['path.database' => __DIR__]); - $events = m::mock(Dispatcher::class)->shouldIgnoreMissing(); + $events = Double::for(Dispatcher::class); $dispatcher = $app->instance(Dispatcher::class, $events); - $console = m::mock(ConsoleApplication::class)->makePartial(); - $console->__construct(); + $console = Double::for(new ConsoleApplication)->passthru(); $command->setHypervel($app); $command->setApplication($console); @@ -159,8 +160,8 @@ public function testRefreshCommandExitsWhenProhibited(): void $this->assertSame(1, $code); - $console->shouldNotHaveReceived('find'); - $dispatcher->shouldNotHaveReceived('dispatch'); + $console->received('find')->never(); + $dispatcher->received('dispatch')->never(); } /** @@ -172,34 +173,6 @@ protected function runCommand(RefreshCommand $command, array $input = []): int } } -class InputMatcher implements MatcherInterface -{ - /** - * Create a new command input matcher. - */ - public function __construct(protected string $expected) - { - } - - /** - * Match the command input. - * - * @param ArrayInput $actual - */ - public function match(mixed &$actual): bool - { - return (string) $actual === $this->expected; - } - - /** - * Get the string representation of the matcher. - */ - public function __toString(): string - { - return ''; - } -} - class ApplicationDatabaseRefreshStub extends Application { /** @@ -207,10 +180,6 @@ class ApplicationDatabaseRefreshStub extends Application */ public function __construct(array $data = []) { - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); - $mutex->shouldReceive('release')->andReturn(true); - $this->instance(CommandMutex::class, $mutex); $this->instance('env', 'development'); foreach ($data as $abstract => $instance) { diff --git a/tests/Database/DatabaseMigrationRepositoryTest.php b/tests/Database/DatabaseMigrationRepositoryTest.php index 9a7db5f15..12d2077b3 100755 --- a/tests/Database/DatabaseMigrationRepositoryTest.php +++ b/tests/Database/DatabaseMigrationRepositoryTest.php @@ -11,41 +11,44 @@ use Hypervel\Database\Schema\Builder as SchemaBuilder; use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseMigrationRepositoryTest extends TestCase { + use VerifiesDoubles; + public function testGetRanMigrationsListMigrationsByPackage(): void { $repository = $this->getRepository(); - $query = m::mock(QueryBuilder::class); - $connectionMock = m::mock(Connection::class); - $repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->andReturn($connectionMock); - $repository->getConnection()->expects('table')->with('migrations')->andReturn($query); - $query->expects('orderBy')->with('batch', 'asc')->andReturn($query); - $query->expects('orderBy')->with('migration', 'asc')->andReturn($query); - $query->expects('pluck')->with('migration')->andReturn(new Collection(['bar'])); - $query->expects('useWritePdo')->andReturn($query); + $query = Double::for(QueryBuilder::class); + $connectionMock = Double::for(Connection::class); + $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); + $query->expects('orderBy')->with('migration', 'asc')->returns($query); + $query->expects('pluck')->with('migration')->returns(new Collection(['bar'])); + $query->expects('useWritePdo')->returns($query); $this->assertSame(['bar'], $repository->getRan()); } public function testGetLastMigrationsGetsAllMigrationsWithTheLatestBatchNumber(): void { - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $repository = $this->getMockBuilder(DatabaseMigrationRepository::class)->onlyMethods(['getLastBatchNumber'])->setConstructorArgs([ $resolver, 'migrations', ])->getMock(); $repository->expects($this->once())->method('getLastBatchNumber')->willReturn(1); - $query = m::mock(QueryBuilder::class); - $connectionMock = m::mock(Connection::class); - $repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->andReturn($connectionMock); - $repository->getConnection()->expects('table')->with('migrations')->andReturn($query); - $query->expects('where')->with('batch', 1)->andReturn($query); - $query->expects('orderBy')->with('migration', 'desc')->andReturn($query); - $query->expects('get')->andReturn(new Collection(['foo'])); - $query->expects('useWritePdo')->andReturn($query); + $query = Double::for(QueryBuilder::class); + $connectionMock = Double::for(Connection::class); + $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); + $query->expects('orderBy')->with('migration', 'desc')->returns($query); + $query->expects('get')->returns(new Collection(['foo'])); + $query->expects('useWritePdo')->returns($query); $this->assertSame(['foo'], $repository->getLast()); } @@ -53,12 +56,12 @@ public function testGetLastMigrationsGetsAllMigrationsWithTheLatestBatchNumber() public function testLogMethodInsertsRecordIntoMigrationTable(): void { $repository = $this->getRepository(); - $query = m::mock(QueryBuilder::class); - $connectionMock = m::mock(Connection::class); - $repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->andReturn($connectionMock); - $repository->getConnection()->expects('table')->with('migrations')->andReturn($query); + $query = Double::for(QueryBuilder::class); + $connectionMock = Double::for(Connection::class); + $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]); - $query->expects('useWritePdo')->andReturn($query); + $query->expects('useWritePdo')->returns($query); $repository->log('bar', 1); } @@ -66,13 +69,13 @@ public function testLogMethodInsertsRecordIntoMigrationTable(): void public function testDeleteMethodRemovesAMigrationFromTheTable(): void { $repository = $this->getRepository(); - $query = m::mock(QueryBuilder::class); - $connectionMock = m::mock(Connection::class); - $repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->andReturn($connectionMock); - $repository->getConnection()->expects('table')->with('migrations')->andReturn($query); - $query->expects('where')->with('migration', 'foo')->andReturn($query); + $query = Double::for(QueryBuilder::class); + $connectionMock = Double::for(Connection::class); + $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); $query->expects('delete'); - $query->expects('useWritePdo')->andReturn($query); + $query->expects('useWritePdo')->returns($query); $migration = (object) ['migration' => 'foo']; $repository->delete($migration); @@ -81,7 +84,7 @@ public function testDeleteMethodRemovesAMigrationFromTheTable(): void public function testGetNextBatchNumberReturnsLastBatchNumberPlusOne(): void { $repository = $this->getMockBuilder(DatabaseMigrationRepository::class)->onlyMethods(['getLastBatchNumber'])->setConstructorArgs([ - m::mock(ConnectionResolverInterface::class), 'migrations', + Double::for(ConnectionResolverInterface::class), 'migrations', ])->getMock(); $repository->expects($this->once())->method('getLastBatchNumber')->willReturn(1); @@ -92,12 +95,12 @@ public function testGetNextBatchNumberReturnsLastBatchNumberPlusOne(): void public function testGetLastBatchNumberReturnsMaxBatch(int|string|null $value, int $expected): void { $repository = $this->getRepository(); - $query = m::mock(QueryBuilder::class); - $connectionMock = m::mock(Connection::class); - $repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->andReturn($connectionMock); - $repository->getConnection()->expects('table')->with('migrations')->andReturn($query); - $query->expects('max')->with('batch')->andReturn($value); - $query->expects('useWritePdo')->andReturn($query); + $query = Double::for(QueryBuilder::class); + $connectionMock = Double::for(Connection::class); + $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); + $query->expects('useWritePdo')->returns($query); $this->assertSame($expected, $repository->getLastBatchNumber()); } @@ -117,10 +120,10 @@ public static function batchNumberProvider(): array public function testCreateRepositoryCreatesProperDatabaseTable(): void { $repository = $this->getRepository(); - $schema = m::mock(SchemaBuilder::class); - $connectionMock = m::mock(Connection::class); - $repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->andReturn($connectionMock); - $repository->getConnection()->expects('getSchemaBuilder')->andReturn($schema); + $schema = Double::for(SchemaBuilder::class); + $connectionMock = Double::for(Connection::class); + $repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->returns($connectionMock); + $repository->getConnection()->expects('getSchemaBuilder')->returns($schema); $schema->expects('createMigrationRepositoryTable')->with('migrations'); $repository->createRepository(); @@ -131,6 +134,6 @@ public function testCreateRepositoryCreatesProperDatabaseTable(): void */ protected function getRepository(): DatabaseMigrationRepository { - return new DatabaseMigrationRepository(m::mock(ConnectionResolverInterface::class), 'migrations'); + return new DatabaseMigrationRepository(Double::for(ConnectionResolverInterface::class), 'migrations'); } } diff --git a/tests/Database/DatabaseMigrationResetCommandTest.php b/tests/Database/DatabaseMigrationResetCommandTest.php index da72c1873..5420bfdbf 100755 --- a/tests/Database/DatabaseMigrationResetCommandTest.php +++ b/tests/Database/DatabaseMigrationResetCommandTest.php @@ -5,31 +5,34 @@ namespace Hypervel\Tests\Database; use Closure; -use Hypervel\Console\CommandMutex; use Hypervel\Database\Console\Migrations\ResetCommand; use Hypervel\Database\Migrations\Migrator; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; use UnitEnum; class DatabaseMigrationResetCommandTest extends TestCase { + use VerifiesDoubles; + public function testResetCommandCallsMigratorWithProperArguments(): void { - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $command = new ResetCommand($migrator); $app = new ApplicationDatabaseResetStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); $command->setHypervel($app); - $migrator->expects('paths')->andReturn([]); - $migrator->expects('usingConnection')->with(null, m::type(Closure::class))->andReturnUsing(function (?string $connection, callable $callback): mixed { + $migrator->expects('paths')->returns([]); + $migrator->expects('usingConnection')->with(null, Argument::type(Closure::class))->resolves(function (?string $connection, callable $callback): mixed { return $callback(); }); - $migrator->expects('repositoryExists')->andReturn(true); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('repositoryExists')->returns(true); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('reset')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], false); $this->runCommand($command); @@ -37,17 +40,17 @@ public function testResetCommandCallsMigratorWithProperArguments(): void public function testResetCommandCanBePretended(): void { - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $command = new ResetCommand($migrator); $app = new ApplicationDatabaseResetStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); $command->setHypervel($app); - $migrator->expects('paths')->andReturn([]); - $migrator->expects('usingConnection')->with('foo', m::type(Closure::class))->andReturnUsing(function (?string $connection, callable $callback): mixed { + $migrator->expects('paths')->returns([]); + $migrator->expects('usingConnection')->with('foo', Argument::type(Closure::class))->resolves(function (?string $connection, callable $callback): mixed { return $callback(); }); - $migrator->expects('repositoryExists')->andReturn(true); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('repositoryExists')->returns(true); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('reset')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], true); $this->runCommand($command, ['--pretend' => true, '--database' => 'foo']); @@ -55,7 +58,7 @@ public function testResetCommandCanBePretended(): void public function testResetCommandExitsWhenProhibited(): void { - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $command = new ResetCommand($migrator); $app = new ApplicationDatabaseResetStub(['path.database' => __DIR__]); @@ -68,7 +71,7 @@ public function testResetCommandExitsWhenProhibited(): void $this->assertSame(1, $code); - $migrator->shouldNotHaveReceived('paths'); + $migrator->received('paths')->never(); } /** @@ -87,10 +90,6 @@ class ApplicationDatabaseResetStub extends Application */ public function __construct(array $data = []) { - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); - $mutex->shouldReceive('release')->andReturn(true); - $this->instance(CommandMutex::class, $mutex); $this->instance('env', 'development'); foreach ($data as $abstract => $instance) { diff --git a/tests/Database/DatabaseMigrationRollbackCommandTest.php b/tests/Database/DatabaseMigrationRollbackCommandTest.php index a6bcfa184..b3ed9f0a3 100755 --- a/tests/Database/DatabaseMigrationRollbackCommandTest.php +++ b/tests/Database/DatabaseMigrationRollbackCommandTest.php @@ -4,30 +4,32 @@ namespace Hypervel\Tests\Database; -use Hypervel\Console\CommandMutex; use Hypervel\Database\Console\Migrations\RollbackCommand; use Hypervel\Database\Migrations\Migrator; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; use UnitEnum; class DatabaseMigrationRollbackCommandTest extends TestCase { + use VerifiesDoubles; + public function testRollbackCommandCallsMigratorWithProperArguments(): void { - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $command = new RollbackCommand($migrator); $app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); $command->setHypervel($app); - $migrator->expects('paths')->andReturn([]); - $migrator->expects('usingConnection')->andReturnUsing(function (?string $name, callable $callback): mixed { + $migrator->expects('paths')->returns([]); + $migrator->expects('usingConnection')->resolves(function (?string $name, callable $callback): mixed { return $callback(); }); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('rollback')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => 0, 'batch' => 0]); $this->runCommand($command); @@ -35,16 +37,16 @@ public function testRollbackCommandCallsMigratorWithProperArguments(): void public function testRollbackCommandCallsMigratorWithStepOption(): void { - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $command = new RollbackCommand($migrator); $app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); $command->setHypervel($app); - $migrator->expects('paths')->andReturn([]); - $migrator->expects('usingConnection')->andReturnUsing(function (?string $name, callable $callback): mixed { + $migrator->expects('paths')->returns([]); + $migrator->expects('usingConnection')->resolves(function (?string $name, callable $callback): mixed { return $callback(); }); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('rollback')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => 2, 'batch' => 0]); $this->runCommand($command, ['--step' => 2]); @@ -52,16 +54,16 @@ public function testRollbackCommandCallsMigratorWithStepOption(): void public function testRollbackCommandCanBePretended(): void { - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $command = new RollbackCommand($migrator); $app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); $command->setHypervel($app); - $migrator->expects('paths')->andReturn([]); - $migrator->expects('usingConnection')->andReturnUsing(function (?string $name, callable $callback): mixed { + $migrator->expects('paths')->returns([]); + $migrator->expects('usingConnection')->resolves(function (?string $name, callable $callback): mixed { return $callback(); }); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('rollback')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => true, 'step' => 0, 'batch' => 0]); $this->runCommand($command, ['--pretend' => true, '--database' => 'foo']); @@ -69,16 +71,16 @@ public function testRollbackCommandCanBePretended(): void public function testRollbackCommandCanBePretendedWithStepOption(): void { - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $command = new RollbackCommand($migrator); $app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); $command->setHypervel($app); - $migrator->expects('paths')->andReturn([]); - $migrator->expects('usingConnection')->andReturnUsing(function (?string $name, callable $callback): mixed { + $migrator->expects('paths')->returns([]); + $migrator->expects('usingConnection')->resolves(function (?string $name, callable $callback): mixed { return $callback(); }); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('rollback')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => true, 'step' => 2, 'batch' => 0]); $this->runCommand($command, ['--pretend' => true, '--database' => 'foo', '--step' => 2]); @@ -86,16 +88,16 @@ public function testRollbackCommandCanBePretendedWithStepOption(): void public function testRollbackCommandCallsMigratorWithBatchOption(): void { - $migrator = m::mock(Migrator::class); + $migrator = Double::for(Migrator::class); $command = new RollbackCommand($migrator); $app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); $command->setHypervel($app); - $migrator->expects('paths')->andReturn([]); - $migrator->expects('usingConnection')->andReturnUsing(function (?string $name, callable $callback): mixed { + $migrator->expects('paths')->returns([]); + $migrator->expects('usingConnection')->resolves(function (?string $name, callable $callback): mixed { return $callback(); }); - $migrator->expects('setOutput')->andReturn($migrator); + $migrator->expects('setOutput')->returns($migrator); $migrator->expects('rollback')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'], ['pretend' => false, 'step' => 0, 'batch' => 3]); $this->runCommand($command, ['--batch' => 3]); @@ -117,10 +119,6 @@ class ApplicationDatabaseRollbackStub extends Application */ public function __construct(array $data = []) { - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); - $mutex->shouldReceive('release')->andReturn(true); - $this->instance(CommandMutex::class, $mutex); $this->instance('env', 'development'); foreach ($data as $abstract => $instance) { diff --git a/tests/Database/DatabaseMigrationStatusCommandTest.php b/tests/Database/DatabaseMigrationStatusCommandTest.php index 7cf77a175..966774d76 100644 --- a/tests/Database/DatabaseMigrationStatusCommandTest.php +++ b/tests/Database/DatabaseMigrationStatusCommandTest.php @@ -4,7 +4,6 @@ namespace Hypervel\Tests\Database; -use Hypervel\Console\CommandMutex; use Hypervel\Database\Console\Migrations\StatusCommand; use Hypervel\Database\Migrations\MigrationRepositoryInterface; use Hypervel\Database\Migrations\Migrator; @@ -52,10 +51,6 @@ class ApplicationDatabaseStatusStub extends Application { public function __construct(array $data = []) { - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); - $mutex->shouldReceive('release')->andReturn(true); - $this->instance(CommandMutex::class, $mutex); $this->instance('env', 'development'); foreach ($data as $abstract => $instance) { diff --git a/tests/Database/DatabaseMigratorIntegrationTest.php b/tests/Database/DatabaseMigratorIntegrationTest.php index 11177fb21..e6444726f 100644 --- a/tests/Database/DatabaseMigratorIntegrationTest.php +++ b/tests/Database/DatabaseMigratorIntegrationTest.php @@ -12,10 +12,13 @@ use Hypervel\Support\Facades\DB; use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DatabaseMigratorIntegrationTest extends TestCase { + use VerifiesDoubles; + protected Migrator $migrator; protected function defineEnvironment(Application $app): void @@ -56,10 +59,10 @@ protected function setUpInCoroutine(): void new Filesystem ); - $output = m::mock(OutputStyle::class); - $output->shouldReceive('write'); - $output->shouldReceive('writeln'); - $output->shouldReceive('newLinesWritten'); + $output = Double::for(OutputStyle::class); + $output->allows('write'); + $output->allows('writeln'); + $output->allows('newLinesWritten'); $this->migrator->setOutput($output); diff --git a/tests/Database/DatabaseMigratorTest.php b/tests/Database/DatabaseMigratorTest.php index d81456742..874db5202 100644 --- a/tests/Database/DatabaseMigratorTest.php +++ b/tests/Database/DatabaseMigratorTest.php @@ -16,7 +16,8 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionClass; @@ -25,6 +26,8 @@ class DatabaseMigratorTest extends TestCase { + use VerifiesDoubles; + // REMOVED: Laravel's ::direct resolution and default-connection tests. // Hypervel routes migrations through configured named connections instead. @@ -82,10 +85,10 @@ public function testSetConnectionNullPreservesDefaultConnectionBehaviorWithoutDi public function testRunMethodPreservesWriteConnectionName(): void { CoroutineContext::set(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY, 'pgsql'); - $resolver = m::mock(Resolver::class); + $resolver = Double::for(Resolver::class); $migrator = $this->migrator($resolver); - $connection = m::mock(Connection::class); - $connection->expects('getNameWithReadWriteType')->andReturn('pgsql::write'); + $connection = Double::for(Connection::class); + $connection->expects('getNameWithReadWriteType')->returns('pgsql::write'); $migration = new class($this) { /** @@ -347,10 +350,10 @@ public function testSetConnectionWritesContextRepositorySourceAndStoredName(): v 'pgsql' => ['driver' => 'pgsql'], ]); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); - $repository->shouldReceive('setSource')->once()->with('pgsql'); + $repository->expects('setSource')->with('pgsql'); $migrator = new Migrator($repository, $resolver, new Filesystem); $migrator->setConnection('pgsql-pooled'); @@ -367,9 +370,9 @@ public function testSetConnectionRejectsNullWithoutAnEffectiveDefault(): void { $this->bindConfig([]); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldNotReceive('setSource'); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $repository->expects('setSource')->never(); $migrator = new Migrator($repository, $resolver, new Filesystem); @@ -385,10 +388,10 @@ public function testSetConnectionDoesNotSwapWhenNoMigrationsConnectionKey(): voi 'pgsql' => ['driver' => 'pgsql'], ]); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); - $repository->shouldReceive('setSource')->once()->with('pgsql'); + $repository->expects('setSource')->with('pgsql'); $migrator = new Migrator($repository, $resolver, new Filesystem); $migrator->setConnection('pgsql'); @@ -407,12 +410,12 @@ public function testResolveConnectionUsesStoredConnectionWhenArgumentIsNullOrEmp 'pgsql' => ['driver' => 'pgsql'], ]); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $resolvedConnection = m::mock(Connection::class); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $resolvedConnection = Double::for(Connection::class); - $repository->shouldReceive('setSource')->once()->with('pgsql'); - $resolver->shouldReceive('connection')->twice()->with('pgsql')->andReturn($resolvedConnection); + $repository->expects('setSource')->with('pgsql'); + $resolver->expects('connection')->times(2)->with('pgsql')->returns($resolvedConnection); $migrator = new Migrator($repository, $resolver, new Filesystem); $migrator->setConnection('pgsql-pooled'); @@ -431,11 +434,11 @@ public function testResolveConnectionPreservesExplicitZeroConnection(): void default: 'pgsql', ); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $resolvedConnection = m::mock(Connection::class); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $resolvedConnection = Double::for(Connection::class); - $resolver->shouldReceive('connection')->once()->with('0')->andReturn($resolvedConnection); + $resolver->expects('connection')->with('0')->returns($resolvedConnection); $migrator = new Migrator($repository, $resolver, new Filesystem); @@ -452,11 +455,11 @@ public function testResolveConnectionSwapsPerMigrationConnectionOverride(): void 'pgsql' => ['driver' => 'pgsql'], ]); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $resolvedConnection = m::mock(Connection::class); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $resolvedConnection = Double::for(Connection::class); - $resolver->shouldReceive('connection')->once()->with('pgsql')->andReturn($resolvedConnection); + $resolver->expects('connection')->with('pgsql')->returns($resolvedConnection); $migrator = new Migrator($repository, $resolver, new Filesystem); @@ -470,9 +473,9 @@ public function testResolveConnectionPassesSwappedNameToCustomCallback(): void 'pgsql' => ['driver' => 'pgsql'], ]); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $resolvedConnection = m::mock(Connection::class); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $resolvedConnection = Double::for(Connection::class); $capturedName = null; Migrator::resolveConnectionsUsing(function (Resolver $r, ?string $name) use (&$capturedName, $resolvedConnection) { @@ -500,9 +503,9 @@ public function testSetConnectionWithNullAndPooledDefaultRoutesToDirect(): void default: 'pgsql-pooled', ); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('setSource')->once()->with('pgsql'); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $repository->expects('setSource')->with('pgsql'); $migrator = new Migrator($repository, $resolver, new Filesystem); $migrator->setConnection(null); @@ -528,11 +531,11 @@ public function testResolveConnectionWithNullAndPooledDefaultRoutesToDirect(): v default: 'pgsql-pooled', ); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $resolvedConnection = m::mock(Connection::class); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $resolvedConnection = Double::for(Connection::class); - $resolver->shouldReceive('connection')->once()->with('pgsql')->andReturn($resolvedConnection); + $resolver->expects('connection')->with('pgsql')->returns($resolvedConnection); $migrator = new Migrator($repository, $resolver, new Filesystem); @@ -552,10 +555,10 @@ public function testUsingConnectionRestoresDistinctStoredAndContextState(): void default: 'stored', ); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('setSource')->twice()->with('stored'); - $repository->shouldReceive('setSource')->once()->with('inner-direct'); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $repository->expects('setSource')->times(2)->with('stored'); + $repository->expects('setSource')->with('inner-direct'); $migrator = new Migrator($repository, $resolver, new Filesystem); $migrator->setConnection('stored'); @@ -590,10 +593,10 @@ public function testUsingConnectionRestoresDistinctStoredAndContextStateAfterAnE default: 'stored', ); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('setSource')->twice()->with('stored'); - $repository->shouldReceive('setSource')->once()->with('inner-direct'); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $repository->expects('setSource')->times(2)->with('stored'); + $repository->expects('setSource')->with('inner-direct'); $migrator = new Migrator($repository, $resolver, new Filesystem); $migrator->setConnection('stored'); @@ -627,11 +630,11 @@ public function testUsingConnectionWithNullAndPooledDefaultRoutesAndRestores(): default: 'pgsql-pooled', ); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); - $repository->shouldReceive('setSource')->once()->with('pgsql'); - $repository->shouldReceive('setSource')->once()->with(null); + $repository->expects('setSource')->with('pgsql'); + $repository->expects('setSource')->with(null); $migrator = new Migrator($repository, $resolver, new Filesystem); @@ -666,10 +669,10 @@ public function testGetMigrationConnectionsDiscoversNamedAnonymousAndContextDecl default: 'default-pooled', ); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('setSource')->once()->with('default-direct'); - $repository->shouldReceive('setSource')->once()->with(null); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $repository->expects('setSource')->with('default-direct'); + $repository->expects('setSource')->with(null); $migrator = new Migrator($repository, $resolver, new Filesystem); $connections = $migrator->getMigrationConnections([ @@ -695,10 +698,10 @@ public function testGetMigrationConnectionsIncludesTheDefaultWithoutMigrationFil default: 'default-pooled', ); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); - $repository->shouldReceive('setSource')->once()->with('default-direct'); - $repository->shouldReceive('setSource')->once()->with(null); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); + $repository->expects('setSource')->with('default-direct'); + $repository->expects('setSource')->with(null); $migrator = new Migrator($repository, $resolver, new Filesystem); $this->assertSame( @@ -724,15 +727,15 @@ public function testNestedUsingConnectionPreservesEachLevelsState(): void default: null, ); - $resolver = m::mock(Resolver::class); - $repository = m::mock(MigrationRepositoryInterface::class); + $resolver = Double::for(Resolver::class); + $repository = Double::for(MigrationRepositoryInterface::class); // Outer enter: setSource('pgsql'). Inner enter: setSource('mysql'). // Inner exit: setSource back to 'pgsql' (outer's stored). Outer exit: // setSource back to null. - $repository->shouldReceive('setSource')->with('pgsql')->twice(); - $repository->shouldReceive('setSource')->with('mysql')->once(); - $repository->shouldReceive('setSource')->with(null)->once(); + $repository->expects('setSource')->with('pgsql')->times(2); + $repository->expects('setSource')->with('mysql'); + $repository->expects('setSource')->with(null); $migrator = new Migrator($repository, $resolver, new Filesystem); diff --git a/tests/Database/DatabaseMySQLSchemaBuilderTest.php b/tests/Database/DatabaseMySQLSchemaBuilderTest.php index f8aa01466..1f9076b8d 100755 --- a/tests/Database/DatabaseMySQLSchemaBuilderTest.php +++ b/tests/Database/DatabaseMySQLSchemaBuilderTest.php @@ -9,35 +9,38 @@ use Hypervel\Database\Schema\Grammars\MySqlGrammar; use Hypervel\Database\Schema\MySqlBuilder; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DatabaseMySQLSchemaBuilderTest extends TestCase { + use VerifiesDoubles; + public function testHasTable(): void { - $connection = m::mock(MySqlConnection::class); - $connection->shouldReceive('usesBackslashEscapes')->andReturnTrue(); + $connection = Double::for(MySqlConnection::class); + $connection->allows('usesBackslashEscapes')->returns(true); $grammar = new MySqlGrammar($connection); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getSchemaGrammar')->returns($grammar); $builder = new MySqlBuilder($connection); - $connection->expects('getTablePrefix')->andReturn('prefix_'); - $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists(null, 'prefix_table'))->andReturn([['exists' => 1]]); + $connection->expects('getTablePrefix')->returns('prefix_'); + $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists(null, 'prefix_table'))->returns([['exists' => 1]]); $this->assertTrue($builder->hasTable('table')); } public function testGetColumnListing(): void { - $connection = m::mock(MySqlConnection::class); - $connection->shouldReceive('usesBackslashEscapes')->andReturnTrue(); + $connection = Double::for(MySqlConnection::class); + $connection->allows('usesBackslashEscapes')->returns(true); $grammar = new MySqlGrammar($connection); $processor = new MySqlProcessor; - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('getPostProcessor')->andReturn($processor); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getPostProcessor')->returns($processor); $builder = new MySqlBuilder($connection); - $connection->expects('getTablePrefix')->andReturn('prefix_'); + $connection->expects('getTablePrefix')->returns('prefix_'); $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'prefix_table')) - ->andReturn([(object) ['name' => 'column', 'type_name' => 'int', 'type' => 'int', 'collation' => null, 'nullable' => 'YES', 'default' => null, 'comment' => null, 'expression' => null, 'extra' => '']]); + ->returns([(object) ['name' => 'column', 'type_name' => 'int', 'type' => 'int', 'collation' => null, 'nullable' => 'YES', 'default' => null, 'comment' => null, 'expression' => null, 'extra' => '']]); $this->assertSame(['column'], $builder->getColumnListing('table')); } diff --git a/tests/Database/DatabaseMySqlBuilderTest.php b/tests/Database/DatabaseMySqlBuilderTest.php index f735ce4ee..55a418df8 100644 --- a/tests/Database/DatabaseMySqlBuilderTest.php +++ b/tests/Database/DatabaseMySqlBuilderTest.php @@ -11,22 +11,25 @@ use Hypervel\Database\Schema\Grammars\MySqlGrammar as MySqlGrammarSchema; use Hypervel\Database\Schema\MySqlBuilder; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class DatabaseMySqlBuilderTest extends TestCase { + use VerifiesDoubles; + public function testCreateDatabase(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new MySqlGrammarSchema($connection); - $connection->expects('getConfig')->with('charset')->andReturn('utf8mb4'); - $connection->expects('getConfig')->with('collation')->andReturn('utf8mb4_unicode_ci'); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getConfig')->with('charset')->returns('utf8mb4'); + $connection->expects('getConfig')->with('collation')->returns('utf8mb4_unicode_ci'); + $connection->expects('getSchemaGrammar')->returns($grammar); $connection->expects('statement')->with( 'create database `my_temporary_database` default character set `utf8mb4` default collate `utf8mb4_unicode_ci`' - )->andReturn(true); + )->returns(true); $builder = new MySqlBuilder($connection); $builder->createDatabase('my_temporary_database'); @@ -34,13 +37,13 @@ public function testCreateDatabase(): void public function testDropDatabaseIfExists(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new MySqlGrammarSchema($connection); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getSchemaGrammar')->returns($grammar); $connection->expects('statement')->with( 'drop database if exists `my_database_a`' - )->andReturn(true); + )->returns(true); $builder = new MySqlBuilder($connection); @@ -49,11 +52,11 @@ public function testDropDatabaseIfExists(): void public function testDeleteWithJoinCompilesOrderByAndLimit(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $processor = new Processor; $grammar = new MySqlGrammar($connection); - $connection->expects('getTablePrefix')->times(5)->andReturn(''); + $connection->expects('getTablePrefix')->times(5)->returns(''); $builder = new Builder($connection, $grammar, $processor); @@ -72,67 +75,65 @@ public function testDeleteWithJoinCompilesOrderByAndLimit(): void public function testDropAllTablesPreservesEnabledForeignKeyConstraints(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new MySqlGrammarSchema($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $builder = m::mock(MySqlBuilder::class, [$connection])->makePartial(); - $connection->shouldReceive('getDatabaseName')->once()->andReturn('database'); - $builder->shouldReceive('getTableListing')->once()->with(['database'])->andReturn(['users']); - $connection->shouldReceive('beginForeignKeyConstraintSuppression')->once()->andReturnTrue(); - $connection->shouldReceive('pretending')->times(3)->andReturnFalse(); - $connection->shouldReceive('scalar')->once()->with('select @@foreign_key_checks', [], false)->andReturn(1); - $connection->shouldReceive('executeSessionStatement')->once()->with('SET FOREIGN_KEY_CHECKS=0;')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $builder = Double::for(new MySqlBuilder($connection))->passthru(); + $connection->expects('getDatabaseName')->returns('database'); + $builder->expects('getTableListing')->with(['database'])->returns(['users']); + $connection->expects('beginForeignKeyConstraintSuppression')->returns(true); + $connection->expects('pretending')->times(3)->returns(false); + $connection->expects('scalar')->with('select @@foreign_key_checks', [], false)->returns(1); + $connection->expects('executeSessionStatement')->with('SET FOREIGN_KEY_CHECKS=0;')->ordered(); + $connection->expects('statement') ->with($grammar->compileDropAllTables(['users'])) - ->andReturnTrue() + ->returns(true) ->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('SET FOREIGN_KEY_CHECKS=1;')->ordered(); - $connection->shouldReceive('endForeignKeyConstraintSuppression')->once(); + $connection->expects('executeSessionStatement')->with('SET FOREIGN_KEY_CHECKS=1;')->ordered(); + $connection->expects('endForeignKeyConstraintSuppression'); $builder->dropAllTables(); } public function testDropAllTablesPreservesDisabledForeignKeyConstraints(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new MySqlGrammarSchema($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $builder = m::mock(MySqlBuilder::class, [$connection])->makePartial(); - $connection->shouldReceive('getDatabaseName')->once()->andReturn('database'); - $builder->shouldReceive('getTableListing')->once()->with(['database'])->andReturn(['users']); - $connection->shouldReceive('beginForeignKeyConstraintSuppression')->once()->andReturnTrue(); - $connection->shouldReceive('pretending')->once()->andReturnFalse(); - $connection->shouldReceive('scalar')->once()->with('select @@foreign_key_checks', [], false)->andReturn(0); - $connection->shouldNotReceive('executeSessionStatement'); - $connection->shouldReceive('statement') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $builder = Double::for(new MySqlBuilder($connection))->passthru(); + $connection->expects('getDatabaseName')->returns('database'); + $builder->expects('getTableListing')->with(['database'])->returns(['users']); + $connection->expects('beginForeignKeyConstraintSuppression')->returns(true); + $connection->expects('pretending')->returns(false); + $connection->expects('scalar')->with('select @@foreign_key_checks', [], false)->returns(0); + $connection->expects('executeSessionStatement')->never(); + $connection->expects('statement') ->with($grammar->compileDropAllTables(['users'])) - ->andReturnTrue(); - $connection->shouldReceive('endForeignKeyConstraintSuppression')->once(); + ->returns(true); + $connection->expects('endForeignKeyConstraintSuppression'); $builder->dropAllTables(); } public function testDropAllTablesPropagatesAFalseStatementResultAfterRestoringConstraints(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new MySqlGrammarSchema($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $builder = m::mock(MySqlBuilder::class, [$connection])->makePartial(); - $connection->shouldReceive('getDatabaseName')->once()->andReturn('database'); - $builder->shouldReceive('getTableListing')->once()->with(['database'])->andReturn(['users']); - $connection->shouldReceive('beginForeignKeyConstraintSuppression')->once()->andReturnTrue(); - $connection->shouldReceive('pretending')->times(3)->andReturnFalse(); - $connection->shouldReceive('scalar')->once()->with('select @@foreign_key_checks', [], false)->andReturn(1); - $connection->shouldReceive('executeSessionStatement')->once()->with('SET FOREIGN_KEY_CHECKS=0;')->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $builder = Double::for(new MySqlBuilder($connection))->passthru(); + $connection->expects('getDatabaseName')->returns('database'); + $builder->expects('getTableListing')->with(['database'])->returns(['users']); + $connection->expects('beginForeignKeyConstraintSuppression')->returns(true); + $connection->expects('pretending')->times(3)->returns(false); + $connection->expects('scalar')->with('select @@foreign_key_checks', [], false)->returns(1); + $connection->expects('executeSessionStatement')->with('SET FOREIGN_KEY_CHECKS=0;')->ordered(); $statement = $grammar->compileDropAllTables(['users']); - $connection->shouldReceive('statement')->once()->with($statement)->andReturnFalse()->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('SET FOREIGN_KEY_CHECKS=1;')->ordered(); - $connection->shouldReceive('endForeignKeyConstraintSuppression')->once(); + $connection->expects('statement')->with($statement)->returns(false)->ordered(); + $connection->expects('executeSessionStatement')->with('SET FOREIGN_KEY_CHECKS=1;')->ordered(); + $connection->expects('endForeignKeyConstraintSuppression'); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs("Failed to execute schema statement [{$statement}]."); @@ -142,17 +143,17 @@ public function testDropAllTablesPropagatesAFalseStatementResultAfterRestoringCo public function testDropAllViewsPropagatesAFalseStatementResult(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new MySqlGrammarSchema($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $builder = m::mock(MySqlBuilder::class, [$connection])->makePartial(); - $builder->shouldReceive('getCurrentSchemaListing')->once()->andReturn(['database']); - $builder->shouldReceive('getViews')->once()->with(['database'])->andReturn([ + $connection->expects('getSchemaGrammar')->returns($grammar); + $builder = Double::for(new MySqlBuilder($connection))->passthru(); + $builder->expects('getCurrentSchemaListing')->returns(['database']); + $builder->expects('getViews')->with(['database'])->returns([ ['schema_qualified_name' => 'active_users'], ]); $statement = $grammar->compileDropAllViews(['active_users']); - $connection->shouldReceive('statement')->once()->with($statement)->andReturnFalse(); + $connection->expects('statement')->with($statement)->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs("Failed to execute schema statement [{$statement}]."); diff --git a/tests/Database/DatabaseMySqlQueryGrammarTest.php b/tests/Database/DatabaseMySqlQueryGrammarTest.php index ab86a3753..8f7598a13 100755 --- a/tests/Database/DatabaseMySqlQueryGrammarTest.php +++ b/tests/Database/DatabaseMySqlQueryGrammarTest.php @@ -13,17 +13,20 @@ use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use PDO; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseMySqlQueryGrammarTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('jsonPathEscapingProvider')] public function testJsonPathsEscapeKeysUsingTheConfiguredSqlMode(array $modes, string $path): void { - $connection = new MySqlConnection(m::mock(PDO::class), config: ['modes' => $modes]); + $connection = new MySqlConnection(Double::for(PDO::class), 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()); @@ -54,14 +57,14 @@ public function testUpdateBindingsRejectUnencodableArrays(): void { $this->expectException(JsonException::class); - (new MySqlGrammar(m::mock(Connection::class))) + (new MySqlGrammar(Double::for(Connection::class))) ->prepareBindingsForUpdate([], ['payload' => [NAN]]); } public function testToRawSql(): void { - $connection = m::mock(Connection::class); - $connection->expects('escape')->with('foo', false)->andReturn("'foo'"); + $connection = Double::for(Connection::class); + $connection->expects('escape')->with('foo', false)->returns("'foo'"); $grammar = new MySqlGrammar($connection); $query = $grammar->substituteBindingsIntoRawSql( @@ -155,8 +158,8 @@ public function testTimeoutDecoratesExistsAndLockingStatementsAtTheRoot(): void #[DataProvider('nestedUnionVersions')] public function testNestedUnionMembersUseTheSupportedServerSyntax(string $connectionClass, string $version, bool $wrapped): void { - $pdo = m::mock(PDO::class); - $pdo->shouldReceive('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->andReturn($version); + $pdo = Double::for(PDO::class); + $pdo->allows('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns($version); $connection = new $connectionClass($pdo, 'database'); $member = $connection->table('posts')->select('id')->where('id', '<=', 3) ->unionAll($connection->table('posts')->select('id')->whereBetween('id', [4, 6])) @@ -190,10 +193,10 @@ public static function nestedUnionVersions(): iterable public function testOrdinaryUnionMembersDoNotInspectTheServerVersion(): void { - $connection = m::mock(MySqlConnection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldNotReceive('getServerVersion'); - $connection->shouldNotReceive('isMaria'); + $connection = Double::for(MySqlConnection::class); + $connection->allows('getTablePrefix')->returns(''); + $connection->expects('getServerVersion')->never(); + $connection->expects('isMaria')->never(); $query = new Builder($connection, new MySqlGrammar($connection), new Processor); $query->from('posts')->select('id')->unionAll($query->newQuery()->from('archives')->select('id')); diff --git a/tests/Database/DatabaseMySqlSchemaGrammarTest.php b/tests/Database/DatabaseMySqlSchemaGrammarTest.php index fc8f05330..a90134f4c 100755 --- a/tests/Database/DatabaseMySqlSchemaGrammarTest.php +++ b/tests/Database/DatabaseMySqlSchemaGrammarTest.php @@ -13,20 +13,23 @@ use Hypervel\Database\Schema\MySqlBuilder; use Hypervel\Tests\Database\Fixtures\Enums\Foo; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; class DatabaseMySqlSchemaGrammarTest extends TestCase { + use VerifiesDoubles; + public function testBasicCreateTable(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -39,7 +42,7 @@ public function testBasicCreateTable(): void $this->assertSame("create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8 collate 'utf8_unicode_ci'", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->increments('id'); @@ -54,7 +57,7 @@ public function testBasicCreateTable(): void ], $statements); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -69,9 +72,9 @@ public function testBasicCreateTable(): void public function testAutoIncrementStartingValue(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -102,8 +105,8 @@ public function testAddColumnsWithMultipleAutoIncrementStartingValue(): void public function testEngineCreateTable(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -117,9 +120,9 @@ public function testEngineCreateTable(): void $this->assertSame("create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8 collate 'utf8_unicode_ci' engine = InnoDB", $statements[0]); $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn('InnoDB'); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns('InnoDB'); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -135,7 +138,7 @@ public function testEngineCreateTable(): void public function testCharsetCollationCreateTable(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -150,9 +153,9 @@ public function testCharsetCollationCreateTable(): void $this->assertSame("create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci'", $statements[0]); $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -168,7 +171,7 @@ public function testCharsetCollationCreateTable(): void public function testBasicCreateTableWithPrefix(): void { $conn = $this->getConnection(prefix: 'prefix_'); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -184,7 +187,7 @@ public function testBasicCreateTableWithPrefix(): void public function testCreateTemporaryTable(): void { $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -534,7 +537,7 @@ public function testAddingForeignID(): void $blueprint = new Blueprint($this->getConnection(), 'users'); $foreignId = $blueprint->foreignId('foo'); $blueprint->foreignId('company_id')->constrained(); - $blueprint->foreignId('laravel_idea_id')->constrained(); + $blueprint->foreignId('hypervel_idea_id')->constrained(); $blueprint->foreignId('team_id')->references('id')->on('teams'); $blueprint->foreignId('team_column_id')->constrained('teams'); @@ -545,8 +548,8 @@ public function testAddingForeignID(): void 'alter table `users` add `foo` bigint unsigned not null', 'alter table `users` add `company_id` bigint unsigned not null', 'alter table `users` add constraint `users_company_id_foreign` foreign key (`company_id`) references `companies` (`id`)', - 'alter table `users` add `laravel_idea_id` bigint unsigned not null', - 'alter table `users` add constraint `users_laravel_idea_id_foreign` foreign key (`laravel_idea_id`) references `laravel_ideas` (`id`)', + 'alter table `users` add `hypervel_idea_id` bigint unsigned not null', + 'alter table `users` add constraint `users_hypervel_idea_id_foreign` foreign key (`hypervel_idea_id`) references `hypervel_ideas` (`id`)', 'alter table `users` add `team_id` bigint unsigned not null', 'alter table `users` add constraint `users_team_id_foreign` foreign key (`team_id`) references `teams` (`id`)', 'alter table `users` add `team_column_id` bigint unsigned not null', @@ -882,7 +885,7 @@ public function testAddingEnum(): void #[DataProvider('escapedSchemaLiteralsProvider')] public function testSchemaLiteralsUseTheConfiguredSqlMode(array $modes, string $literal, string $path): void { - $connection = new MySqlConnection(m::mock(PDO::class), config: ['modes' => $modes]); + $connection = new MySqlConnection(Double::for(PDO::class), config: ['modes' => $modes]); $connection->useDefaultSchemaGrammar(); $blueprint = new Blueprint($connection, 'users'); $value = "O'Brien\\User"; @@ -951,8 +954,8 @@ public function testAddingJsonb(): void public function testAddingDate(): void { $conn = $this->getConnection(); - $conn->shouldReceive('isMaria')->andReturn(false); - $conn->shouldReceive('getServerVersion')->andReturn('8.0.13'); + $conn->expects('isMaria')->returns(false); + $conn->expects('getServerVersion')->returns('8.0.13'); $blueprint = new Blueprint($conn, 'users'); $blueprint->date('foo'); @@ -965,8 +968,8 @@ public function testAddingDate(): void public function testAddingDateWithDefaultCurrent(): void { $conn = $this->getConnection(); - $conn->shouldReceive('isMaria')->andReturn(false); - $conn->shouldReceive('getServerVersion')->andReturn('8.0.13'); + $conn->expects('isMaria')->returns(false); + $conn->expects('getServerVersion')->returns('8.0.13'); $blueprint = new Blueprint($conn, 'users'); $blueprint->date('foo')->useCurrent(); @@ -979,8 +982,8 @@ public function testAddingDateWithDefaultCurrent(): void public function testAddingDateWithDefaultCurrentOn57(): void { $conn = $this->getConnection(); - $conn->shouldReceive('isMaria')->andReturn(false); - $conn->shouldReceive('getServerVersion')->andReturn('5.7'); + $conn->expects('isMaria')->returns(false); + $conn->expects('getServerVersion')->returns('5.7'); $blueprint = new Blueprint($conn, 'users'); $blueprint->date('foo')->useCurrent(); @@ -993,8 +996,8 @@ public function testAddingDateWithDefaultCurrentOn57(): void public function testAddingYear(): void { $conn = $this->getConnection(); - $conn->shouldReceive('isMaria')->andReturn(false); - $conn->shouldReceive('getServerVersion')->andReturn('8.0.13'); + $conn->expects('isMaria')->returns(false); + $conn->expects('getServerVersion')->returns('8.0.13'); $blueprint = new Blueprint($conn, 'users'); $blueprint->year('birth_year'); @@ -1006,8 +1009,8 @@ public function testAddingYear(): void public function testAddingYearWithDefaultCurrent(): void { $conn = $this->getConnection(); - $conn->shouldReceive('isMaria')->andReturn(false); - $conn->shouldReceive('getServerVersion')->andReturn('8.0.13'); + $conn->expects('isMaria')->returns(false); + $conn->expects('getServerVersion')->returns('8.0.13'); $blueprint = new Blueprint($conn, 'users'); $blueprint->year('birth_year')->useCurrent(); @@ -1020,8 +1023,8 @@ public function testAddingYearWithDefaultCurrent(): void public function testAddingYearWithDefaultCurrentOn57(): void { $conn = $this->getConnection(); - $conn->shouldReceive('isMaria')->andReturn(false); - $conn->shouldReceive('getServerVersion')->andReturn('5.7'); + $conn->expects('isMaria')->returns(false); + $conn->expects('getServerVersion')->returns('5.7'); $blueprint = new Blueprint($conn, 'users'); $blueprint->year('birth_year')->useCurrent(); @@ -1295,7 +1298,7 @@ public function testAddingForeignUuid(): void $blueprint = new Blueprint($this->getConnection(), 'users'); $foreignUuid = $blueprint->foreignUuid('foo'); $blueprint->foreignUuid('company_id')->constrained(); - $blueprint->foreignUuid('laravel_idea_id')->constrained(); + $blueprint->foreignUuid('hypervel_idea_id')->constrained(); $blueprint->foreignUuid('team_id')->references('id')->on('teams'); $blueprint->foreignUuid('team_column_id')->constrained('teams'); @@ -1306,8 +1309,8 @@ public function testAddingForeignUuid(): void 'alter table `users` add `foo` char(36) not null', 'alter table `users` add `company_id` char(36) not null', 'alter table `users` add constraint `users_company_id_foreign` foreign key (`company_id`) references `companies` (`id`)', - 'alter table `users` add `laravel_idea_id` char(36) not null', - 'alter table `users` add constraint `users_laravel_idea_id_foreign` foreign key (`laravel_idea_id`) references `laravel_ideas` (`id`)', + 'alter table `users` add `hypervel_idea_id` char(36) not null', + 'alter table `users` add constraint `users_hypervel_idea_id_foreign` foreign key (`hypervel_idea_id`) references `hypervel_ideas` (`id`)', 'alter table `users` add `team_id` char(36) not null', 'alter table `users` add constraint `users_team_id_foreign` foreign key (`team_id`) references `teams` (`id`)', 'alter table `users` add `team_column_id` char(36) not null', @@ -1479,7 +1482,7 @@ public function testAddingVector(): void { $blueprint = new Blueprint($this->getConnection(), 'embeddings'); $blueprint->vector('embedding', 384); - $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); + $statements = $blueprint->toSql(); $this->assertCount(1, $statements); $this->assertSame('alter table `embeddings` add `embedding` vector(384) not null', $statements[0]); @@ -1488,8 +1491,8 @@ public function testAddingVector(): void public function testCreateDatabase(): void { $connection = $this->getConnection(); - $connection->expects('getConfig')->with('charset')->andReturn('utf8mb4_foo'); - $connection->expects('getConfig')->with('collation')->andReturn('utf8mb4_unicode_ci_foo'); + $connection->expects('getConfig')->with('charset')->returns('utf8mb4_foo'); + $connection->expects('getConfig')->with('collation')->returns('utf8mb4_unicode_ci_foo'); $statement = $this->getGrammar($connection)->compileCreateDatabase('my_database_a'); @@ -1499,8 +1502,8 @@ public function testCreateDatabase(): void ); $connection = $this->getConnection(); - $connection->expects('getConfig')->with('charset')->andReturn('utf8mb4_bar'); - $connection->expects('getConfig')->with('collation')->andReturn('utf8mb4_unicode_ci_bar'); + $connection->expects('getConfig')->with('charset')->returns('utf8mb4_bar'); + $connection->expects('getConfig')->with('collation')->returns('utf8mb4_unicode_ci_bar'); $statement = $this->getGrammar($connection)->compileCreateDatabase('my_database_b'); @@ -1513,9 +1516,9 @@ public function testCreateDatabase(): void public function testCreateTableWithVirtualAsColumn(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1528,7 +1531,7 @@ public function testCreateTableWithVirtualAsColumn(): void $this->assertSame("create table `users` (`my_column` varchar(255) not null, `my_other_column` varchar(255) as (my_column)) default character set utf8 collate 'utf8_unicode_ci'", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1541,7 +1544,7 @@ public function testCreateTableWithVirtualAsColumn(): void $this->assertSame("create table `users` (`my_json_column` varchar(255) not null, `my_other_column` varchar(255) as (json_unquote(json_extract(`my_json_column`, '$.\"some_attribute\"'))))", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1557,7 +1560,7 @@ public function testCreateTableWithVirtualAsColumn(): void public function testCreateTableWithVirtualAsColumnWhenJsonColumnHasArrayKey(): void { $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1572,9 +1575,9 @@ public function testCreateTableWithVirtualAsColumnWhenJsonColumnHasArrayKey(): v public function testCreateTableWithStoredAsColumn(): void { $conn = $this->getConnection(); - $conn->expects('getConfig')->with('charset')->andReturn('utf8'); - $conn->expects('getConfig')->with('collation')->andReturn('utf8_unicode_ci'); - $conn->expects('getConfig')->with('engine')->andReturn(null); + $conn->expects('getConfig')->with('charset')->returns('utf8'); + $conn->expects('getConfig')->with('collation')->returns('utf8_unicode_ci'); + $conn->expects('getConfig')->with('engine')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1587,7 +1590,7 @@ public function testCreateTableWithStoredAsColumn(): void $this->assertSame("create table `users` (`my_column` varchar(255) not null, `my_other_column` varchar(255) as (my_column) stored) default character set utf8 collate 'utf8_unicode_ci'", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1600,7 +1603,7 @@ public function testCreateTableWithStoredAsColumn(): void $this->assertSame("create table `users` (`my_json_column` varchar(255) not null, `my_other_column` varchar(255) as (json_unquote(json_extract(`my_json_column`, '$.\"some_attribute\"'))) stored)", $statements[0]); $conn = $this->getConnection(); - $conn->shouldReceive('getConfig')->andReturn(null); + $conn->allows('getConfig')->returns(null); $blueprint = new Blueprint($conn, 'users'); $blueprint->create(); @@ -1679,19 +1682,17 @@ protected function getConnection( ?MySqlGrammar $grammar = null, ?MySqlBuilder $builder = null, string $prefix = '' - ): Connection&MockInterface { - $connection = m::mock(MySqlConnection::class); - $connection->shouldReceive('usesBackslashEscapes')->passthru(); - $connection->shouldReceive('getConfig')->with('modes')->andReturn(null); - $connection->shouldReceive('getTablePrefix')->andReturn($prefix); - $connection->shouldReceive('getConfig')->with('prefix_indexes')->andReturn(null); - $connection->shouldReceive('isMaria')->andReturn(false); + ): Connection&DoubleInterface { + $connection = Double::for(MySqlConnection::class); + $connection->allows('usesBackslashEscapes')->returns(true); + $connection->allows('getTablePrefix')->returns($prefix); + $connection->allows('getConfig')->with('prefix_indexes')->returns(null); $grammar ??= $this->getGrammar($connection); $builder ??= $this->getBuilder(); - $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); - $connection->shouldReceive('getSchemaBuilder')->andReturn($builder); + $connection->allows('getSchemaGrammar')->returns($grammar); + $connection->allows('getSchemaBuilder')->returns($builder); return $connection; } @@ -1995,6 +1996,6 @@ public function getGrammar(?Connection $connection = null): MySqlGrammar */ public function getBuilder(): MySqlBuilder { - return mock(MySqlBuilder::class); + return Double::for(MySqlBuilder::class); } } diff --git a/tests/Database/DatabasePdoConnectionTest.php b/tests/Database/DatabasePdoConnectionTest.php index f6580b6be..90ab26ebe 100755 --- a/tests/Database/DatabasePdoConnectionTest.php +++ b/tests/Database/DatabasePdoConnectionTest.php @@ -26,8 +26,10 @@ use Hypervel\Http\Client\RequestException; use Hypervel\Http\Client\Response; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PDO; use PDOException; use PDOStatement; @@ -41,6 +43,8 @@ class DatabasePdoConnectionTest extends TestCase { + use VerifiesDoubles; + public function testSelectProperlyCallsPDO(): void { $pdo = $this->getMockBuilder(PDOStub::class)->onlyMethods(['prepare'])->getMock(); @@ -360,12 +364,11 @@ public function testStatementPreparedIsDispatchedFromThePdoPreparationPath(): vo $statement->expects($this->once())->method('execute')->willReturn(true); $statement->expects($this->once())->method('fetchAll')->willReturn([]); $connection = $this->getMockConnection([], $pdo); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(StatementPrepared::class)->andReturn(true); - $events->shouldReceive('hasListeners')->once()->with(QueryExecuted::class)->andReturn(false); - $events->shouldReceive('dispatch') - ->once() - ->with(m::on(static fn (StatementPrepared $event): bool => $event->connection === $connection + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(StatementPrepared::class)->returns(true); + $events->expects('hasListeners')->with(QueryExecuted::class)->returns(false); + $events->expects('dispatch') + ->with(Argument::satisfies(static fn (StatementPrepared $event): bool => $event->connection === $connection && $event->statement === $statement)); $connection->setEventDispatcher($events); @@ -393,10 +396,10 @@ protected function event(object $event): void parent::event($event); } }; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(StatementPrepared::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->once()->with(QueryExecuted::class)->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(StatementPrepared::class)->returns(false); + $events->expects('hasListeners')->with(QueryExecuted::class)->returns(false); + $events->expects('dispatch')->never(); $connection->setEventDispatcher($events); $this->assertSame([], $connection->select('select 1', useReadPdo: false)); @@ -409,10 +412,10 @@ 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 = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->with(StatementPrepared::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->once()->with(m::type(StatementPrepared::class))->andThrow($failure); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnFalse(); + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->with(StatementPrepared::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(StatementPrepared::class))->throws($failure); + $events->allows('hasListeners')->returns(false); $connection->setEventDispatcher($events); try { @@ -811,11 +814,11 @@ public function testOnLostConnectionPDOIsNotSwappedWithinATransaction(): void $this->expectException(QueryException::class); $this->expectExceptionMessageIs('server has gone away (Connection: test, Host: , Port: , Database: , SQL: foo)'); - $pdo = m::mock(PDO::class); - $pdo->shouldReceive('beginTransaction')->once(); - $statement = m::mock(PDOStatement::class); - $pdo->shouldReceive('prepare')->once()->andReturn($statement); - $statement->shouldReceive('execute')->once()->andThrow(new PDOException('server has gone away')); + $pdo = Double::for(PDO::class); + $pdo->expects('beginTransaction')->returns(true); + $statement = Double::for(PDOStatement::class); + $pdo->expects('prepare')->returns($statement); + $statement->expects('execute')->throws(new PDOException('server has gone away')); $connection = new PdoConnection($pdo, '', '', ['name' => 'test', 'driver' => 'mysql']); $connection->beginTransaction(); @@ -861,27 +864,33 @@ public function testQueryExceptionMasksBindingsWhenEnabledOnTheConnection(): voi */ protected function getFailingPdo(): PDO { - $statement = m::mock(PDOStatement::class); - $statement->shouldReceive('bindValue')->once(); - $statement->shouldReceive('execute')->once()->andThrow( + $statement = Double::for(PDOStatement::class); + $statement->expects('bindValue')->returns(true); + $statement->expects('execute')->throws( new PDOException('SQLSTATE[42S02]: Base table or view not found') ); - $pdo = m::mock(PDO::class); - $pdo->shouldReceive('prepare')->once()->andReturn($statement); + $pdo = Double::for(PDO::class); + $pdo->expects('prepare')->returns($statement); return $pdo; } public function testOnLostConnectionPDOIsSwappedOutsideTransaction(): void { - $pdo = m::mock(PDO::class); + $pdo = Double::for(PDO::class); + + $statement = Double::for(PDOStatement::class); + $executions = 0; + $statement->expects('execute')->times(2)->resolves(function () use (&$executions): bool { + if ($executions++ === 0) { + throw new PDOException('server has gone away'); + } - $statement = m::mock(PDOStatement::class); - $statement->expects('execute')->andThrow(new PDOException('server has gone away')); - $statement->expects('execute')->andReturn(true); + return true; + }); - $pdo->expects('prepare')->times(2)->andReturn($statement); + $pdo->expects('prepare')->times(2)->returns($statement); $connection = new PdoConnection($pdo, '', '', ['name' => 'test', 'driver' => 'mysql']); @@ -898,13 +907,13 @@ public function testOnLostConnectionPDOIsSwappedOutsideTransaction(): void public function testQueriesRunWhileReconnectingDoNotReconnectAgain(): void { - $statement = m::mock(PDOStatement::class); - $statement->shouldReceive('execute')->andThrow( + $statement = Double::for(PDOStatement::class); + $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 = m::mock(PDO::class); - $pdo->shouldReceive('prepare')->andReturn($statement); + $pdo = Double::for(PDO::class); + $pdo->expects('prepare')->times(2)->returns($statement); $connection = new PdoConnection($pdo); @@ -1059,15 +1068,15 @@ public function testLostConnectionDuringCommitDiscardsPdoSoTheNextTransactionRec public function testLostTransactionCleanupPreservesAConnectionOpenedByARollbackCallback(string $operation): void { $failure = new PDOException('server has gone away'); - $pdo = m::mock(PDO::class); - $pdo->expects('beginTransaction')->andReturnTrue(); - $pdo->shouldNotReceive('prepare'); + $pdo = Double::for(PDO::class); + $pdo->expects('beginTransaction')->returns(true); + $pdo->expects('prepare')->never(); if ($operation === 'rollback') { - $pdo->expects('inTransaction')->andReturnTrue(); - $pdo->expects('rollBack')->andThrow($failure); + $pdo->expects('inTransaction')->returns(true); + $pdo->expects('rollBack')->throws($failure); } else { - $pdo->expects('commit')->andThrow($failure); + $pdo->expects('commit')->throws($failure); } $connection = $this->getMockConnection([], $pdo); @@ -1498,13 +1507,19 @@ public function testDisconnectReleasesEveryPdoWhenReleasingThemRaisesWarnings(): public function testLostConnectionIsRetriedWhenReleasingADeadReadPdoRaisesAWarning(): void { - $statement = m::mock(PDOStatement::class); - $statement->expects('execute')->andThrow(new PDOException('server has gone away')); - $statement->expects('execute')->andReturn(true); + $statement = Double::for(PDOStatement::class); + $executions = 0; + $statement->expects('execute')->times(2)->resolves(function () use (&$executions): bool { + if ($executions++ === 0) { + throw new PDOException('server has gone away'); + } + + return true; + }); - $pdo = m::mock(PDO::class); - $pdo->expects('prepare')->times(2)->andReturn($statement); - $pdo->expects('inTransaction')->andReturnFalse(); + $pdo = Double::for(PDO::class); + $pdo->expects('prepare')->times(2)->returns($statement); + $pdo->expects('inTransaction')->returns(false); $connection = new PdoConnection(fn () => $pdo); $connection->setReadPdo(new PdoThatWarnsWhenReleased); @@ -1834,7 +1849,7 @@ protected function getMockConnection($methods = [], $pdo = null) if ($methods === []) { $connection = new PdoConnection($pdo, 'test_db', '', ['name' => 'test', 'driver' => 'mysql']); - $connection->setSchemaGrammar(m::mock(SchemaGrammar::class)); + $connection->setSchemaGrammar(Double::for(SchemaGrammar::class)); $connection->enableQueryLog(); return $connection; @@ -1842,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(m::mock(SchemaGrammar::class)); + $connection->method('getDefaultSchemaGrammar')->willReturn(Double::for(SchemaGrammar::class)); $connection->enableQueryLog(); return $connection; diff --git a/tests/Database/DatabasePostgresBuilderTest.php b/tests/Database/DatabasePostgresBuilderTest.php index bd1ba4ba1..d1c1d2414 100644 --- a/tests/Database/DatabasePostgresBuilderTest.php +++ b/tests/Database/DatabasePostgresBuilderTest.php @@ -13,23 +13,26 @@ use Hypervel\Support\Fluent; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Override; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; class DatabasePostgresBuilderTest extends TestCase { + use VerifiesDoubles; + public function testCreateDatabase(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresGrammar($connection); - $connection->expects('getConfig')->with('charset')->andReturn('utf8'); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getConfig')->with('charset')->returns('utf8'); + $connection->expects('getSchemaGrammar')->returns($grammar); $connection->expects('statement')->with( 'create database "my_temporary_database" encoding "utf8"' - )->andReturn(true); + )->returns(true); $builder = $this->getBuilder($connection); $builder->createDatabase('my_temporary_database'); @@ -37,13 +40,13 @@ public function testCreateDatabase(): void public function testDropDatabaseIfExists(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresGrammar($connection); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getSchemaGrammar')->returns($grammar); $connection->expects('statement')->with( 'drop database if exists "my_database_a"' - )->andReturn(true); + )->returns(true); $builder = $this->getBuilder($connection); @@ -52,130 +55,128 @@ public function testDropDatabaseIfExists(): void public function testExecuteBlueprintWrapsKnownMultiStatementCommandsInATransaction(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresGrammar($connection); $blueprint = $this->executionBlueprint( ['first statement', 'second statement'], [new Fluent(['name' => 'create'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('transaction') - ->once() - ->andReturnUsing(static fn (Closure $callback) => $callback()); - $connection->shouldReceive('statement')->once()->with('first statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('transaction') + ->resolves(static fn (Closure $callback) => $callback()); + $connection->expects('statement')->with('first statement')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); (new PostgresBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintDoesNotNestAnExistingTransaction(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresGrammar($connection); $blueprint = $this->executionBlueprint( ['first statement', 'second statement'], [new Fluent(['name' => 'create'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(1); - $connection->shouldReceive('transaction')->never(); - $connection->shouldReceive('statement')->once()->with('first statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('transaction')->never(); + $connection->expects('statement')->with('first statement')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); (new PostgresBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintDoesNotWrapASingleStatement(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresGrammar($connection); $blueprint = $this->executionBlueprint( ['statement'], [new Fluent(['name' => 'create'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->never(); - $connection->shouldReceive('transaction')->never(); - $connection->shouldReceive('statement')->once()->with('statement')->andReturnTrue(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->never(); + $connection->expects('transaction')->never(); + $connection->expects('statement')->with('statement')->returns(true); (new PostgresBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintDoesNotWrapOnlineCommands(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresGrammar($connection); $blueprint = $this->executionBlueprint( ['create index concurrently', 'attach constraint'], [new Fluent(['name' => 'unique', 'online' => true])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('transaction')->never(); - $connection->shouldReceive('statement')->once()->with('create index concurrently')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('attach constraint')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('transaction')->never(); + $connection->expects('statement')->with('create index concurrently')->returns(true)->ordered(); + $connection->expects('statement')->with('attach constraint')->returns(true)->ordered(); (new PostgresBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintDoesNotWrapCommandsAddedByAnExtensionGrammar(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresGrammar($connection); $blueprint = $this->executionBlueprint( ['extension statement one', 'extension statement two'], [new Fluent(['name' => 'extensionCommand'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('transaction')->never(); - $connection->shouldReceive('statement')->once()->with('extension statement one')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('extension statement two')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('transaction')->never(); + $connection->expects('statement')->with('extension statement one')->returns(true)->ordered(); + $connection->expects('statement')->with('extension statement two')->returns(true)->ordered(); (new PostgresBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintWrapsFrameworkCommandsOverriddenByAnExtensionGrammar(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresBuilderExtensionGrammar($connection); $blueprint = $this->executionBlueprint( ['overridden create', 'second statement'], [new Fluent(['name' => 'create'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('transaction') - ->once() - ->andReturnUsing(static fn (Closure $callback) => $callback()); - $connection->shouldReceive('statement')->once()->with('overridden create')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('transaction') + ->resolves(static fn (Closure $callback) => $callback()); + $connection->expects('statement')->with('overridden create')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); (new PostgresBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintHonorsTheRuntimeGrammarTransactionFlag(): void { - $connection = m::mock(Connection::class); - $grammar = m::mock(PostgresGrammar::class, [$connection])->makePartial(); + $connection = Double::for(Connection::class); + $grammar = Double::for(new PostgresGrammar($connection))->passthru(); $blueprint = $this->executionBlueprint( ['first statement', 'second statement'], [new Fluent(['name' => 'create'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $grammar->shouldReceive('supportsSchemaTransactions')->once()->andReturnFalse(); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('transaction')->never(); - $connection->shouldReceive('statement')->once()->with('first statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $grammar->expects('supportsSchemaTransactions')->returns(false); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('transaction')->never(); + $connection->expects('statement')->with('first statement')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); (new PostgresBuilder($connection))->executeBlueprint($blueprint); } @@ -183,10 +184,10 @@ public function testExecuteBlueprintHonorsTheRuntimeGrammarTransactionFlag(): vo public function testHasTableWhenSchemaUnqualifiedAndSearchPathMissing(): void { $connection = $this->getConnection(); - $grammar = m::mock(PostgresGrammar::class); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $grammar->expects('compileTableExists')->times(2)->andReturn('sql'); - $connection->expects('selectFromWriteConnection')->times(2)->with('sql')->andReturn([['exists' => 1]]); + $grammar = Double::for(PostgresGrammar::class); + $connection->expects('getSchemaGrammar')->returns($grammar); + $grammar->expects('compileTableExists')->times(2)->returns('sql'); + $connection->expects('selectFromWriteConnection')->times(2)->with('sql')->returns([['exists' => 1]]); $connection->expects('getTablePrefix')->times(2); $builder = $this->getBuilder($connection); @@ -197,10 +198,10 @@ public function testHasTableWhenSchemaUnqualifiedAndSearchPathMissing(): void public function testHasTableWhenSchemaUnqualifiedAndSearchPathFilled(): void { $connection = $this->getConnection(); - $grammar = m::mock(PostgresGrammar::class); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $grammar->expects('compileTableExists')->times(2)->andReturn('sql'); - $connection->expects('selectFromWriteConnection')->times(2)->with('sql')->andReturn([['exists' => 1]]); + $grammar = Double::for(PostgresGrammar::class); + $connection->expects('getSchemaGrammar')->returns($grammar); + $grammar->expects('compileTableExists')->times(2)->returns('sql'); + $connection->expects('selectFromWriteConnection')->times(2)->with('sql')->returns([['exists' => 1]]); $connection->expects('getTablePrefix')->times(2); $builder = $this->getBuilder($connection); @@ -211,10 +212,10 @@ public function testHasTableWhenSchemaUnqualifiedAndSearchPathFilled(): void public function testHasTableWhenSchemaUnqualifiedAndSearchPathFallbackFilled(): void { $connection = $this->getConnection(); - $grammar = m::mock(PostgresGrammar::class); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $grammar->expects('compileTableExists')->times(2)->andReturn('sql'); - $connection->expects('selectFromWriteConnection')->times(2)->with('sql')->andReturn([['exists' => 1]]); + $grammar = Double::for(PostgresGrammar::class); + $connection->expects('getSchemaGrammar')->returns($grammar); + $grammar->expects('compileTableExists')->times(2)->returns('sql'); + $connection->expects('selectFromWriteConnection')->times(2)->with('sql')->returns([['exists' => 1]]); $connection->expects('getTablePrefix')->times(2); $builder = $this->getBuilder($connection); @@ -225,10 +226,10 @@ public function testHasTableWhenSchemaUnqualifiedAndSearchPathFallbackFilled(): public function testHasTableWhenSchemaUnqualifiedAndSearchPathIsUserVariable(): void { $connection = $this->getConnection(); - $grammar = m::mock(PostgresGrammar::class); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $grammar->expects('compileTableExists')->times(2)->andReturn('sql'); - $connection->expects('selectFromWriteConnection')->times(2)->with('sql')->andReturn([['exists' => 1]]); + $grammar = Double::for(PostgresGrammar::class); + $connection->expects('getSchemaGrammar')->returns($grammar); + $grammar->expects('compileTableExists')->times(2)->returns('sql'); + $connection->expects('selectFromWriteConnection')->times(2)->with('sql')->returns([['exists' => 1]]); $connection->expects('getTablePrefix')->times(2); $builder = $this->getBuilder($connection); @@ -240,8 +241,8 @@ public function testHasTableWhenSchemaQualifiedAndSearchPathMismatches(): void { $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists('myapp', 'foo'))->andReturn([['exists' => 1]]); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists('myapp', 'foo'))->returns([['exists' => 1]]); $connection->expects('getTablePrefix'); $builder = $this->getBuilder($connection); @@ -254,7 +255,7 @@ public function testHasTableWhenDatabaseAndSchemaQualifiedAndSearchPathMismatche $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getSchemaGrammar')->returns($grammar); $builder = $this->getBuilder($connection); $builder->hasTable('mydatabase.myapp.foo'); @@ -264,13 +265,13 @@ public function testGetColumnListingWhenSchemaUnqualifiedAndSearchPathMissing(): { $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->shouldReceive('getServerVersion')->andReturn('12.0.0'); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'foo'))->andReturn([['name' => 'some_column']]); + $connection->allows('getServerVersion')->returns('12.0.0'); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'foo'))->returns([['name' => 'some_column']]); $connection->expects('getTablePrefix'); - $processor = m::mock(PostgresProcessor::class); - $connection->expects('getPostProcessor')->andReturn($processor); - $processor->expects('processColumns')->andReturn([['name' => 'some_column']]); + $processor = Double::for(PostgresProcessor::class); + $connection->expects('getPostProcessor')->returns($processor); + $processor->expects('processColumns')->returns([['name' => 'some_column']]); $builder = $this->getBuilder($connection); $this->assertSame(['some_column'], $builder->getColumnListing('foo')); @@ -280,13 +281,13 @@ public function testGetColumnListingWhenSchemaUnqualifiedAndSearchPathFilled(): { $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->shouldReceive('getServerVersion')->andReturn('12.0.0'); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'foo'))->andReturn([['name' => 'some_column']]); + $connection->allows('getServerVersion')->returns('12.0.0'); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'foo'))->returns([['name' => 'some_column']]); $connection->expects('getTablePrefix'); - $processor = m::mock(PostgresProcessor::class); - $connection->expects('getPostProcessor')->andReturn($processor); - $processor->expects('processColumns')->andReturn([['name' => 'some_column']]); + $processor = Double::for(PostgresProcessor::class); + $connection->expects('getPostProcessor')->returns($processor); + $processor->expects('processColumns')->returns([['name' => 'some_column']]); $builder = $this->getBuilder($connection); $this->assertSame(['some_column'], $builder->getColumnListing('foo')); @@ -296,13 +297,13 @@ public function testGetColumnListingWhenSchemaUnqualifiedAndSearchPathIsUserVari { $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->shouldReceive('getServerVersion')->andReturn('12.0.0'); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'foo'))->andReturn([['name' => 'some_column']]); + $connection->allows('getServerVersion')->returns('12.0.0'); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'foo'))->returns([['name' => 'some_column']]); $connection->expects('getTablePrefix'); - $processor = m::mock(PostgresProcessor::class); - $connection->expects('getPostProcessor')->andReturn($processor); - $processor->expects('processColumns')->andReturn([['name' => 'some_column']]); + $processor = Double::for(PostgresProcessor::class); + $connection->expects('getPostProcessor')->returns($processor); + $processor->expects('processColumns')->returns([['name' => 'some_column']]); $builder = $this->getBuilder($connection); $this->assertSame(['some_column'], $builder->getColumnListing('foo')); @@ -312,13 +313,13 @@ public function testGetColumnListingWhenSchemaQualifiedAndSearchPathMismatches() { $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->shouldReceive('getServerVersion')->andReturn('12.0.0'); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns('myapp', 'foo'))->andReturn([['name' => 'some_column']]); + $connection->allows('getServerVersion')->returns('12.0.0'); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns('myapp', 'foo'))->returns([['name' => 'some_column']]); $connection->expects('getTablePrefix'); - $processor = m::mock(PostgresProcessor::class); - $connection->expects('getPostProcessor')->andReturn($processor); - $processor->expects('processColumns')->andReturn([['name' => 'some_column']]); + $processor = Double::for(PostgresProcessor::class); + $connection->expects('getPostProcessor')->returns($processor); + $processor->expects('processColumns')->returns([['name' => 'some_column']]); $builder = $this->getBuilder($connection); $this->assertSame(['some_column'], $builder->getColumnListing('myapp.foo')); @@ -330,7 +331,7 @@ public function testGetColumnWhenDatabaseAndSchemaQualifiedAndSearchPathMismatch $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getSchemaGrammar')->returns($grammar); $builder = $this->getBuilder($connection); $builder->getColumnListing('mydatabase.myapp.foo'); @@ -339,13 +340,12 @@ public function testGetColumnWhenDatabaseAndSchemaQualifiedAndSearchPathMismatch public function testCurrentSchemaNameQueriesTheConnectionRatherThanConfiguredSearchPathOrder(): void { $connection = $this->getConnection(); - $connection->shouldReceive('getConfig')->once()->with('username')->andReturn('foouser'); - $connection->shouldReceive('getConfig')->once()->with('search_path')->andReturn('"$user", public'); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(m::mock(PostgresGrammar::class)); - $connection->shouldReceive('scalar') - ->once() + $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('scalar') ->with('select current_schema()', [], false) - ->andReturn('public'); + ->returns('public'); $builder = $this->getBuilder($connection); @@ -357,9 +357,9 @@ public function testCurrentSchemaNameQueriesTheConnectionRatherThanConfiguredSea public function testCurrentSchemaListingFollowsTheConnectorSettingPrecedence(?string $searchPath, ?string $schema, array $expected): void { $connection = $this->getConnection(); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(m::mock(PostgresGrammar::class)); - $connection->shouldReceive('getConfig')->with('search_path')->andReturn($searchPath); - $connection->shouldReceive('getConfig')->with('schema')->andReturn($schema); + $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class)); + $connection->allows('getConfig')->with('search_path')->returns($searchPath); + $connection->allows('getConfig')->with('schema')->returns($schema); $this->assertSame($expected, $this->getBuilder($connection)->getCurrentSchemaListing()); } @@ -380,12 +380,11 @@ public static function currentSchemaListingConfigurationProvider(): array public function testHasViewIsFalseWithoutACurrentSchema(): void { $connection = $this->getConnection(); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(m::mock(PostgresGrammar::class)); - $connection->shouldReceive('scalar') - ->once() + $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class)); + $connection->expects('scalar') ->with('select current_schema()', [], false) - ->andReturnNull(); - $connection->shouldNotReceive('selectFromWriteConnection'); + ->returns(null); + $connection->expects('selectFromWriteConnection')->never(); $this->assertFalse($this->getBuilder($connection)->hasView('active_users')); } @@ -393,21 +392,20 @@ public function testHasViewIsFalseWithoutACurrentSchema(): void public function testHasViewUsesTheActualCurrentSchema(): void { $connection = $this->getConnection(); - $grammar = m::mock(PostgresGrammar::class); - $processor = m::mock(PostgresProcessor::class); + $grammar = Double::for(PostgresGrammar::class); + $processor = Double::for(PostgresProcessor::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('getTablePrefix')->once()->andReturn(''); - $connection->shouldReceive('scalar') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getTablePrefix')->returns(''); + $connection->expects('scalar') ->with('select current_schema()', [], false) - ->andReturn('tenant.example'); - $grammar->shouldReceive('compileViews')->once()->with('tenant.example')->andReturn('sql'); - $connection->shouldReceive('selectFromWriteConnection')->once()->with('sql')->andReturn([ + ->returns('tenant.example'); + $grammar->expects('compileViews')->with('tenant.example')->returns('sql'); + $connection->expects('selectFromWriteConnection')->with('sql')->returns([ ['name' => 'active_users'], ]); - $connection->shouldReceive('getPostProcessor')->once()->andReturn($processor); - $processor->shouldReceive('processViews')->once()->andReturn([ + $connection->expects('getPostProcessor')->returns($processor); + $processor->expects('processViews')->returns([ ['name' => 'active_users'], ]); @@ -419,19 +417,19 @@ public function testHasViewUsesTheActualCurrentSchema(): void public function testDropAllTablesWhenSearchPathIsString(): void { $connection = $this->getConnection(); - $connection->expects('getConfig')->with('search_path')->andReturn('public'); - $connection->expects('getConfig')->with('dont_drop')->andReturn(['foo']); + $connection->expects('getConfig')->with('search_path')->returns('public'); + $connection->expects('getConfig')->with('dont_drop')->returns(['foo']); $grammar = new PostgresGrammar($connection); $processor = new PostgresProcessor; - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('getPostProcessor')->andReturn($processor); - $connection->expects('selectFromWriteConnection')->with($grammar->compileTables(['public']))->andReturn([ + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getPostProcessor')->returns($processor); + $connection->expects('selectFromWriteConnection')->with($grammar->compileTables(['public']))->returns([ (object) ['name' => 'foo', 'schema' => 'public', 'partition_of' => null], (object) ['name' => 'foo_1', 'schema' => 'public', 'partition_of' => 'public.foo'], (object) ['name' => 'users', 'schema' => 'public', 'partition_of' => null], (object) ['name' => 'users_1', 'schema' => 'public', 'partition_of' => 'public.users'], ]); - $connection->expects('statement')->with('drop table "public"."users" cascade')->andReturnTrue(); + $connection->expects('statement')->with('drop table "public"."users" cascade')->returns(true); $builder = $this->getBuilder($connection); $builder->dropAllTables(); @@ -440,17 +438,17 @@ public function testDropAllTablesWhenSearchPathIsString(): void public function testDropAllTablesWhenSearchPathIsStringOfMany(): void { $connection = $this->getConnection(); - $connection->expects('getConfig')->with('username')->andReturn('foouser'); - $connection->expects('getConfig')->with('search_path')->andReturn('"$user", public, foo_bar-Baz.Áüõß'); - $connection->expects('getConfig')->with('dont_drop')->andReturn(['foo']); + $connection->expects('getConfig')->with('username')->returns('foouser'); + $connection->expects('getConfig')->with('search_path')->returns('"$user", public, foo_bar-Baz.Áüõß'); + $connection->expects('getConfig')->with('dont_drop')->returns(['foo']); $grammar = new PostgresGrammar($connection); $processor = new PostgresProcessor; - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('getPostProcessor')->andReturn($processor); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getPostProcessor')->returns($processor); $connection->expects('selectFromWriteConnection') ->with($grammar->compileTables(['foouser', 'public', 'foo_bar-Baz.Áüõß'])) - ->andReturn([(object) ['name' => 'users', 'schema' => 'foouser']]); - $connection->expects('statement')->with('drop table "foouser"."users" cascade')->andReturnTrue(); + ->returns([(object) ['name' => 'users', 'schema' => 'foouser']]); + $connection->expects('statement')->with('drop table "foouser"."users" cascade')->returns(true); $builder = $this->getBuilder($connection); $builder->dropAllTables(); @@ -459,22 +457,22 @@ public function testDropAllTablesWhenSearchPathIsStringOfMany(): void public function testDropAllTablesWhenSearchPathIsArrayOfMany(): void { $connection = $this->getConnection(); - $connection->expects('getConfig')->with('username')->andReturn('foouser'); - $connection->expects('getConfig')->with('search_path')->andReturn([ + $connection->expects('getConfig')->with('username')->returns('foouser'); + $connection->expects('getConfig')->with('search_path')->returns([ '$user', '"dev"', "'test'", 'spaced schema', ]); - $connection->expects('getConfig')->with('dont_drop')->andReturn(['foo']); + $connection->expects('getConfig')->with('dont_drop')->returns(['foo']); $grammar = new PostgresGrammar($connection); $processor = new PostgresProcessor; - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('getPostProcessor')->andReturn($processor); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getPostProcessor')->returns($processor); $connection->expects('selectFromWriteConnection') ->with($grammar->compileTables(['foouser', 'dev', 'test', 'spaced schema'])) - ->andReturn([(object) ['name' => 'users', 'schema' => 'foouser']]); - $connection->expects('statement')->with('drop table "foouser"."users" cascade')->andReturnTrue(); + ->returns([(object) ['name' => 'users', 'schema' => 'foouser']]); + $connection->expects('statement')->with('drop table "foouser"."users" cascade')->returns(true); $builder = $this->getBuilder($connection); $builder->dropAllTables(); @@ -483,10 +481,10 @@ public function testDropAllTablesWhenSearchPathIsArrayOfMany(): void public function testDropAllObjectsWithAnEmptySearchPathLeavesEverySchemaUntouched(): void { $connection = $this->getConnection(); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(m::mock(PostgresGrammar::class)); - $connection->shouldReceive('getConfig')->times(3)->with('search_path')->andReturn(''); - $connection->shouldNotReceive('selectFromWriteConnection'); - $connection->shouldNotReceive('statement'); + $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class)); + $connection->expects('getConfig')->times(3)->with('search_path')->returns(''); + $connection->expects('selectFromWriteConnection')->never(); + $connection->expects('statement')->never(); $builder = $this->getBuilder($connection); $builder->dropAllTables(); @@ -499,15 +497,15 @@ public function testDropAllTablesPropagatesAFalseStatementResult(): void $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('getConfig')->once()->with('dont_drop')->andReturn([]); - $builder = m::mock(PostgresBuilder::class, [$connection])->makePartial(); - $builder->shouldReceive('getCurrentSchemaListing')->once()->andReturn(['public']); - $builder->shouldReceive('getTables')->once()->with(['public'])->andReturn([ + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getConfig')->with('dont_drop')->returns([]); + $builder = Double::for(new PostgresBuilder($connection))->passthru(); + $builder->expects('getCurrentSchemaListing')->returns(['public']); + $builder->expects('getTables')->with(['public'])->returns([ ['name' => 'users', 'schema_qualified_name' => 'public.users', 'partition_of' => null], ]); $statement = $grammar->compileDropAllTables(['public.users']); - $connection->shouldReceive('statement')->once()->with($statement)->andReturnFalse(); + $connection->expects('statement')->with($statement)->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs("Failed to execute schema statement [{$statement}]."); @@ -520,14 +518,14 @@ public function testDropAllViewsPropagatesAFalseStatementResult(): void $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $builder = m::mock(PostgresBuilder::class, [$connection])->makePartial(); - $builder->shouldReceive('getCurrentSchemaListing')->once()->andReturn(['public']); - $builder->shouldReceive('getViews')->once()->with(['public'])->andReturn([ + $connection->expects('getSchemaGrammar')->returns($grammar); + $builder = Double::for(new PostgresBuilder($connection))->passthru(); + $builder->expects('getCurrentSchemaListing')->returns(['public']); + $builder->expects('getViews')->with(['public'])->returns([ ['schema_qualified_name' => 'public.active_users'], ]); $statement = $grammar->compileDropAllViews(['public.active_users']); - $connection->shouldReceive('statement')->once()->with($statement)->andReturnFalse(); + $connection->expects('statement')->with($statement)->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs("Failed to execute schema statement [{$statement}]."); @@ -540,14 +538,14 @@ public function testDropAllTypesPropagatesAFalseStatementResult(): void $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $builder = m::mock(PostgresBuilder::class, [$connection])->makePartial(); - $builder->shouldReceive('getCurrentSchemaListing')->once()->andReturn(['public']); - $builder->shouldReceive('getTypes')->once()->with(['public'])->andReturn([ + $connection->expects('getSchemaGrammar')->returns($grammar); + $builder = Double::for(new PostgresBuilder($connection))->passthru(); + $builder->expects('getCurrentSchemaListing')->returns(['public']); + $builder->expects('getTypes')->with(['public'])->returns([ ['implicit' => false, 'type' => 'enum', 'schema_qualified_name' => 'public.status'], ]); $statement = $grammar->compileDropAllTypes(['public.status']); - $connection->shouldReceive('statement')->once()->with($statement)->andReturnFalse(); + $connection->expects('statement')->with($statement)->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs("Failed to execute schema statement [{$statement}]."); @@ -560,14 +558,14 @@ public function testDropAllDomainsPropagatesAFalseStatementResult(): void $connection = $this->getConnection(); $grammar = new PostgresGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $builder = m::mock(PostgresBuilder::class, [$connection])->makePartial(); - $builder->shouldReceive('getCurrentSchemaListing')->once()->andReturn(['public']); - $builder->shouldReceive('getTypes')->once()->with(['public'])->andReturn([ + $connection->expects('getSchemaGrammar')->returns($grammar); + $builder = Double::for(new PostgresBuilder($connection))->passthru(); + $builder->expects('getCurrentSchemaListing')->returns(['public']); + $builder->expects('getTypes')->with(['public'])->returns([ ['implicit' => false, 'type' => 'domain', 'schema_qualified_name' => 'public.email'], ]); $statement = $grammar->compileDropAllDomains(['public.email']); - $connection->shouldReceive('statement')->once()->with($statement)->andReturnFalse(); + $connection->expects('statement')->with($statement)->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs("Failed to execute schema statement [{$statement}]."); @@ -580,7 +578,7 @@ public function testDropAllDomainsPropagatesAFalseStatementResult(): void */ protected function getConnection(): Connection { - return m::mock(Connection::class); + return Double::for(Connection::class); } /** @@ -591,9 +589,9 @@ protected function getConnection(): Connection */ protected function executionBlueprint(array $statements, array $commands): Blueprint { - $blueprint = m::mock(Blueprint::class); - $blueprint->shouldReceive('toSql')->once()->andReturn($statements); - $blueprint->shouldReceive('getCommands')->andReturn($commands); + $blueprint = Double::for(Blueprint::class); + $blueprint->expects('toSql')->returns($statements); + $blueprint->allows('getCommands')->returns($commands); return $blueprint; } diff --git a/tests/Database/DatabasePostgresQueryGrammarTest.php b/tests/Database/DatabasePostgresQueryGrammarTest.php index 2b3cb9dd2..c627a05ce 100755 --- a/tests/Database/DatabasePostgresQueryGrammarTest.php +++ b/tests/Database/DatabasePostgresQueryGrammarTest.php @@ -10,17 +10,20 @@ use Hypervel\Database\Query\Grammars\PostgresGrammar; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use PDO; class DatabasePostgresQueryGrammarTest extends TestCase { + use VerifiesDoubles; + public function testUpdateBindingsRejectUnencodableArrays(): void { $this->expectException(JsonException::class); - (new PostgresGrammar(m::mock(Connection::class))) + (new PostgresGrammar(Double::for(Connection::class))) ->prepareBindingsForUpdate([], ['payload' => [NAN]]); } @@ -34,14 +37,14 @@ public function testUpdateFromBindingsRejectArraysOverTheNativeDepthLimit(): voi $this->expectException(JsonException::class); - (new PostgresGrammar(m::mock(Connection::class))) + (new PostgresGrammar(Double::for(Connection::class))) ->prepareBindingsForUpdateFrom([], ['payload' => $value]); } public function testToRawSql(): void { - $connection = m::mock(Connection::class); - $connection->expects('escape')->with('foo', false)->andReturn("'foo'"); + $connection = Double::for(Connection::class); + $connection->expects('escape')->with('foo', false)->returns("'foo'"); $grammar = new PostgresGrammar($connection); $query = $grammar->substituteBindingsIntoRawSql( @@ -72,8 +75,8 @@ public function testCustomOperators(): void public function testCompileTruncate(): void { - $connection = m::mock(Connection::class); - $connection->expects('getTablePrefix')->times(3)->andReturn(''); + $connection = Double::for(Connection::class); + $connection->expects('getTablePrefix')->times(3)->returns(''); $postgres = new PostgresGrammar($connection); $builder = new Builder($connection, $postgres, new Processor); @@ -98,11 +101,11 @@ public function testCompileTruncate(): void public function testFlushStateRestoresDefaults(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); $postgres = new PostgresGrammar($connection); - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class); $builder->from = 'users'; PostgresGrammar::customOperators(['@@@']); diff --git a/tests/Database/DatabasePostgresSchemaBuilderTest.php b/tests/Database/DatabasePostgresSchemaBuilderTest.php index 51a973c75..b8040585d 100755 --- a/tests/Database/DatabasePostgresSchemaBuilderTest.php +++ b/tests/Database/DatabasePostgresSchemaBuilderTest.php @@ -9,19 +9,22 @@ use Hypervel\Database\Schema\Grammars\PostgresGrammar; use Hypervel\Database\Schema\PostgresBuilder; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DatabasePostgresSchemaBuilderTest extends TestCase { + use VerifiesDoubles; + public function testHasTable(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresGrammar($connection); - $connection->expects('getSchemaGrammar')->andReturn($grammar); + $connection->expects('getSchemaGrammar')->returns($grammar); $builder = new PostgresBuilder($connection); - $connection->expects('getTablePrefix')->times(2)->andReturn('prefix_'); - $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists(null, 'prefix_table'))->andReturn([['exists' => 1]]); - $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists('public', 'prefix_table'))->andReturn([['exists' => 1]]); + $connection->expects('getTablePrefix')->times(2)->returns('prefix_'); + $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists(null, 'prefix_table'))->returns([['exists' => 1]]); + $connection->expects('selectFromWriteConnection')->with($grammar->compileTableExists('public', 'prefix_table'))->returns([['exists' => 1]]); $this->assertTrue($builder->hasTable('table')); $this->assertTrue($builder->hasTable('public.table')); @@ -29,16 +32,16 @@ public function testHasTable(): void public function testGetColumnListing(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new PostgresGrammar($connection); - $connection->shouldReceive('getServerVersion')->andReturn('12.0.0'); + $connection->allows('getServerVersion')->returns('12.0.0'); $processor = new PostgresProcessor; - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('getPostProcessor')->andReturn($processor); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getPostProcessor')->returns($processor); $builder = new PostgresBuilder($connection); - $connection->expects('getTablePrefix')->andReturn('prefix_'); + $connection->expects('getTablePrefix')->returns('prefix_'); $connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'prefix_table')) - ->andReturn([(object) ['name' => 'column', 'type_name' => 'int4', 'type' => 'integer', 'collation' => null, 'nullable' => 'YES', 'default' => null, 'comment' => null, 'generated' => null]]); + ->returns([(object) ['name' => 'column', 'type_name' => 'int4', 'type' => 'integer', 'collation' => null, 'nullable' => 'YES', 'default' => null, 'comment' => null, 'generated' => null]]); $this->assertSame(['column'], $builder->getColumnListing('table')); } diff --git a/tests/Database/DatabasePostgresSchemaGrammarTest.php b/tests/Database/DatabasePostgresSchemaGrammarTest.php index 764cc4e5b..38c2145c8 100755 --- a/tests/Database/DatabasePostgresSchemaGrammarTest.php +++ b/tests/Database/DatabasePostgresSchemaGrammarTest.php @@ -13,13 +13,16 @@ use Hypervel\Database\Schema\PostgresBuilder; use Hypervel\Tests\Database\Fixtures\Enums\Foo; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; class DatabasePostgresSchemaGrammarTest extends TestCase { + use VerifiesDoubles; + public function testBasicCreateTable(): void { $blueprint = new Blueprint($this->getConnection(), 'users'); @@ -48,7 +51,7 @@ public function testAddingVector(): void { $blueprint = new Blueprint($this->getConnection(), 'embeddings'); $blueprint->vector('embedding', 384); - $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); + $statements = $blueprint->toSql(); $this->assertCount(1, $statements); $this->assertSame('alter table "embeddings" add column "embedding" vector(384) not null', $statements[0]); @@ -183,8 +186,8 @@ public function testCreateRangePartitionedTable(): void public function testCreateRangePartition(): void { $connection = $this->getConnection(prefix: 'prefix_'); - $connection->expects('escape')->with(1, false)->twice()->andReturn('1'); - $connection->expects('escape')->with("0190'a", false)->andReturn("'0190''a'"); + $connection->expects('escape')->with(1, false)->times(2)->returns('1'); + $connection->expects('escape')->with("0190'a", false)->returns("'0190''a'"); $this->assertSame( 'create table "prefix_attempts_1" partition of "prefix_attempts" for values from (1, \'0190\'\'a\') to (1, maxvalue)', @@ -251,7 +254,7 @@ public function testDropColumn(): void public function testDropPrimary(): void { $connection = $this->getConnection(); - $connection->getSchemaBuilder()->shouldReceive('parseSchemaAndTable')->andReturn([null, 'users']); + $connection->getSchemaBuilder()->expects('parseSchemaAndTable')->returns([null, 'users']); $blueprint = new Blueprint($connection, 'users'); $blueprint->dropPrimary(); @@ -541,7 +544,7 @@ public function testPartialRawIndexComposesWithAlgorithmAndOnlineCreation(): voi public function testCompileIndexesIncludesOnlyKeysAndPartialMetadata(string $version, string $keyCondition): void { $connection = $this->getConnection(); - $connection->expects('getServerVersion')->andReturn($version); + $connection->expects('getServerVersion')->returns($version); $this->assertSame( 'select ic.relname as name, a.attname as column_name, ' . 'am.amname as "type", i.indisunique as "unique", i.indisprimary as "primary", ' @@ -801,7 +804,7 @@ public function testAddingForeignID(): void $blueprint = new Blueprint($this->getConnection(), 'users'); $foreignId = $blueprint->foreignId('foo'); $blueprint->foreignId('company_id')->constrained(); - $blueprint->foreignId('laravel_idea_id')->constrained(); + $blueprint->foreignId('hypervel_idea_id')->constrained(); $blueprint->foreignId('team_id')->references('id')->on('teams'); $blueprint->foreignId('team_column_id')->constrained('teams'); @@ -812,8 +815,8 @@ public function testAddingForeignID(): void 'alter table "users" add column "foo" bigint not null', 'alter table "users" add column "company_id" bigint not null', 'alter table "users" add constraint "users_company_id_foreign" foreign key ("company_id") references "companies" ("id")', - 'alter table "users" add column "laravel_idea_id" bigint not null', - 'alter table "users" add constraint "users_laravel_idea_id_foreign" foreign key ("laravel_idea_id") references "laravel_ideas" ("id")', + 'alter table "users" add column "hypervel_idea_id" bigint not null', + 'alter table "users" add constraint "users_hypervel_idea_id_foreign" foreign key ("hypervel_idea_id") references "hypervel_ideas" ("id")', 'alter table "users" add column "team_id" bigint not null', 'alter table "users" add constraint "users_team_id_foreign" foreign key ("team_id") references "teams" ("id")', 'alter table "users" add column "team_column_id" bigint not null', @@ -1221,7 +1224,7 @@ public function testAddingForeignUuid(): void $blueprint = new Blueprint($this->getConnection(), 'users'); $foreignUuid = $blueprint->foreignUuid('foo'); $blueprint->foreignUuid('company_id')->constrained(); - $blueprint->foreignUuid('laravel_idea_id')->constrained(); + $blueprint->foreignUuid('hypervel_idea_id')->constrained(); $blueprint->foreignUuid('team_id')->references('id')->on('teams'); $blueprint->foreignUuid('team_column_id')->constrained('teams'); @@ -1232,8 +1235,8 @@ public function testAddingForeignUuid(): void 'alter table "users" add column "foo" uuid not null', 'alter table "users" add column "company_id" uuid not null', 'alter table "users" add constraint "users_company_id_foreign" foreign key ("company_id") references "companies" ("id")', - 'alter table "users" add column "laravel_idea_id" uuid not null', - 'alter table "users" add constraint "users_laravel_idea_id_foreign" foreign key ("laravel_idea_id") references "laravel_ideas" ("id")', + 'alter table "users" add column "hypervel_idea_id" uuid not null', + 'alter table "users" add constraint "users_hypervel_idea_id_foreign" foreign key ("hypervel_idea_id") references "hypervel_ideas" ("id")', 'alter table "users" add column "team_id" uuid not null', 'alter table "users" add constraint "users_team_id_foreign" foreign key ("team_id") references "teams" ("id")', 'alter table "users" add column "team_column_id" uuid not null', @@ -1548,7 +1551,7 @@ public function testAddingMultiPolygon(): void public function testCreateDatabase(): void { $connection = $this->getConnection(); - $connection->expects('getConfig')->with('charset')->andReturn('utf8_foo'); + $connection->expects('getConfig')->with('charset')->returns('utf8_foo'); $statement = $this->getGrammar($connection)->compileCreateDatabase('my_database_a'); $this->assertSame( @@ -1557,7 +1560,7 @@ public function testCreateDatabase(): void ); $connection = $this->getConnection(); - $connection->expects('getConfig')->with('charset')->andReturn('utf8_bar'); + $connection->expects('getConfig')->with('charset')->returns('utf8_bar'); $statement = $this->getGrammar($connection)->compileCreateDatabase('my_database_b'); $this->assertSame( @@ -1639,7 +1642,7 @@ public function testDropAllDomainsWithPrefixAndSchema(): void public function testCompileColumns(): void { $connection = $this->getConnection(); - $connection->expects('getServerVersion')->andReturn('12.0.0'); + $connection->expects('getServerVersion')->returns('12.0.0'); $statement = $connection->getSchemaGrammar()->compileColumns('public', 'table'); @@ -1649,10 +1652,11 @@ public function testCompileColumns(): void $this->assertStringContainsString('a.attidentity as identity', $statement); } + // REMOVED: Laravel's PostgreSQL 8 metadata case; Hypervel requires PostgreSQL 10+. public function testCompileColumnsOnPostgresTen(): void { $connection = $this->getConnection(); - $connection->expects('getServerVersion')->andReturn('10.23'); + $connection->expects('getServerVersion')->returns('10.23'); $statement = $connection->getSchemaGrammar()->compileColumns('public', 'table'); @@ -1666,7 +1670,7 @@ public function testCompileColumnsOnPostgresTen(): void public function testCompileMetadataQueriesForSchemaNamedZero(): void { $connection = $this->getConnection(); - $connection->expects('getServerVersion')->twice()->andReturn('12.0.0'); + $connection->expects('getServerVersion')->times(2)->returns('12.0.0'); $grammar = $connection->getSchemaGrammar(); $this->assertStringContainsString("n.nspname = '0' and", $grammar->compileTableExists('0', 'users')); @@ -1709,16 +1713,16 @@ protected function getConnection( ?PostgresGrammar $grammar = null, ?PostgresBuilder $builder = null, string $prefix = '' - ): Connection&MockInterface { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn($prefix); - $connection->shouldReceive('getConfig')->with('prefix_indexes')->andReturn(null); + ): Connection&DoubleInterface { + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns($prefix); + $connection->allows('getConfig')->with('prefix_indexes')->returns(null); $grammar ??= $this->getGrammar($connection); $builder ??= $this->getBuilder(); - $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); - $connection->shouldReceive('getSchemaBuilder')->andReturn($builder); + $connection->allows('getSchemaGrammar')->returns($grammar); + $connection->allows('getSchemaBuilder')->returns($builder); return $connection; } @@ -1736,7 +1740,7 @@ public function getGrammar(?Connection $connection = null): PostgresGrammar */ public function getBuilder(): PostgresBuilder { - return m::mock(PostgresBuilder::class)->makePartial(); + return Double::for(PostgresBuilder::class)->passthru(); } public function testGrammarsAreMacroable(): void diff --git a/tests/Database/DatabaseProcessorTest.php b/tests/Database/DatabaseProcessorTest.php index 244a33eb0..733d15210 100755 --- a/tests/Database/DatabaseProcessorTest.php +++ b/tests/Database/DatabaseProcessorTest.php @@ -8,18 +8,21 @@ use Hypervel\Database\Query\Builder; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class DatabaseProcessorTest extends TestCase { + use VerifiesDoubles; + public function testInsertGetIdProcessing(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $connection->expects('insert')->with('sql', ['foo']); - $connection->expects('getLastInsertId')->with('id')->andReturn('1'); - $builder = m::mock(Builder::class); - $builder->expects('getConnection')->twice()->andReturn($connection); + $connection->expects('getLastInsertId')->with('id')->returns('1'); + $builder = Double::for(Builder::class); + $builder->expects('getConnection')->times(2)->returns($connection); $processor = new Processor; $result = $processor->processInsertGetId($builder, 'sql', ['foo'], 'id'); $this->assertSame(1, $result); @@ -28,11 +31,11 @@ public function testInsertGetIdProcessing(): void public function testInsertGetIdPreservesTheConnectionFailureAfterTheInsertCompletes(): void { $failure = new RuntimeException('The database driver could not retrieve the last insert ID.'); - $connection = m::mock(Connection::class); - $connection->shouldReceive('insert')->once()->with('sql', ['foo'])->andReturnTrue(); - $connection->shouldReceive('getLastInsertId')->once()->with('id')->andThrow($failure); - $builder = m::mock(Builder::class); - $builder->shouldReceive('getConnection')->twice()->andReturn($connection); + $connection = Double::for(Connection::class); + $connection->expects('insert')->with('sql', ['foo'])->returns(true); + $connection->expects('getLastInsertId')->with('id')->throws($failure); + $builder = Double::for(Builder::class); + $builder->expects('getConnection')->times(2)->returns($connection); $exception = null; diff --git a/tests/Database/DatabaseQueryBuilderTest.php b/tests/Database/DatabaseQueryBuilderTest.php index b66dd2932..7d2d5e1fa 100755 --- a/tests/Database/DatabaseQueryBuilderTest.php +++ b/tests/Database/DatabaseQueryBuilderTest.php @@ -32,6 +32,7 @@ use Hypervel\Database\Query\Processors\PostgresProcessor; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Database\RecordNotFoundException; +use Hypervel\Database\Schema\Builder as SchemaBuilder; use Hypervel\Pagination\AbstractPaginator as Paginator; use Hypervel\Pagination\Cursor; use Hypervel\Pagination\CursorPaginator; @@ -46,7 +47,10 @@ use Hypervel\Tests\Database\Fixtures\Enums\StringStatus; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionMethod; @@ -58,6 +62,8 @@ class DatabaseQueryBuilderTest extends TestCase { + use VerifiesDoubles; + public function testBasicSelect(): void { $builder = $this->getBuilder(); @@ -83,17 +89,10 @@ public function testFlushStateClearsMacros(): void public function testBasicSelectWithGetColumns(): void { $builder = $this->getBuilder(); + $queries = []; $builder->getProcessor()->expects('processSelect')->times(3); - $builder->getConnection()->expects('select')->andReturnUsing(function (string $sql): array { - $this->assertSame('select * from "users"', $sql); - return []; - }); - $builder->getConnection()->expects('select')->andReturnUsing(function (string $sql): array { - $this->assertSame('select "foo", "bar" from "users"', $sql); - return []; - }); - $builder->getConnection()->expects('select')->andReturnUsing(function (string $sql): array { - $this->assertSame('select "baz" from "users"', $sql); + $builder->getConnection()->expects('select')->times(3)->resolves(function (string $sql) use (&$queries): array { + $queries[] = $sql; return []; }); @@ -108,6 +107,12 @@ public function testBasicSelectWithGetColumns(): void $this->assertSame('select * from "users"', $builder->toSql()); $this->assertNull($builder->columns); + + $this->assertSame([ + 'select * from "users"', + 'select "foo", "bar" from "users"', + 'select "baz" from "users"', + ], $queries); } public function testBasicSelectUseWritePdo(): void @@ -2397,8 +2402,8 @@ public function testHavingAggregate(): void { $expected = 'select count(*) as `aggregate` from (select (select `count(*)` from `videos` where `posts`.`id` = `videos`.`post_id`) as `videos_count` from `posts` having `videos_count` > ?) as `temp_table`'; $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('select')->with($expected, [0 => 1], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function (Builder $builder, array $results): array { + $builder->getConnection()->expects('select')->with($expected, [0 => 1], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function (Builder $builder, array $results): array { return $results; }); @@ -2972,7 +2977,7 @@ public function testHavingExpression(): void $builder = $this->getBuilder(); $builder->select('*')->from('users')->having( new class implements ConditionExpression { - public function getValue(\Hypervel\Database\Grammar $grammar): string|int|float + public function getValue(BaseGrammar $grammar): string|int|float { return '1 = 1'; } @@ -2993,8 +2998,8 @@ public function testHavingFollowedBySelectGet(): void { $builder = $this->getBuilder(); $query = 'select "category", count(*) as "total" from "item" where "department" = ? group by "category" having "total" > ?'; - $builder->getConnection()->expects('select')->with($query, ['popular', 3], true, [])->andReturn([['category' => 'rock', 'total' => 5]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function (Builder $builder, array $results): array { + $builder->getConnection()->expects('select')->with($query, ['popular', 3], true, [])->returns([['category' => 'rock', 'total' => 5]]); + $builder->getProcessor()->expects('processSelect')->resolves(function (Builder $builder, array $results): array { return $results; }); $builder->from('item'); @@ -3004,8 +3009,8 @@ public function testHavingFollowedBySelectGet(): void // Using \Raw value $builder = $this->getBuilder(); $query = 'select "category", count(*) as "total" from "item" where "department" = ? group by "category" having "total" > 3'; - $builder->getConnection()->expects('select')->with($query, ['popular'], true, [])->andReturn([['category' => 'rock', 'total' => 5]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function (Builder $builder, array $results): array { + $builder->getConnection()->expects('select')->with($query, ['popular'], true, [])->returns([['category' => 'rock', 'total' => 5]]); + $builder->getProcessor()->expects('processSelect')->resolves(function (Builder $builder, array $results): array { return $results; }); $builder->from('item'); @@ -3108,8 +3113,8 @@ public function testUnsupportedWriteConstraintsFailBeforeExecuting(string $drive 'mariadb' => $this->getMariaDbBuilder(), default => $this->getPostgresBuilder(), }; - $builder->getConnection()->shouldNotReceive('update'); - $builder->getConnection()->shouldNotReceive('delete'); + $builder->getConnection()->expects('update')->never(); + $builder->getConnection()->expects('delete')->never(); $builder->from('users')->limit($limit)->offset($offset); if ($join) { @@ -3149,7 +3154,7 @@ public static function unsupportedWriteConstraints(): array public function testOffsetOnlyWritesUseRowIdentifiers(string $driver, string $operation, string $sql): void { $builder = $driver === 'sqlite' ? $this->getSQLiteBuilder() : $this->getPostgresBuilder(); - $builder->getConnection()->expects($operation)->with($sql, $operation === 'update' ? [false] : [])->andReturn(3); + $builder->getConnection()->expects($operation)->with($sql, $operation === 'update' ? [false] : [])->returns(3); $builder->selectRaw('? as display_value', ['original'])->from('users')->orderBy('id')->offset(2); $originalSelect = $builder->toSql(); @@ -3263,8 +3268,8 @@ public function testGetCountForPaginationWithBindings(): void $q->select('body')->from('posts')->where('id', 4); }, 'post'); - $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); @@ -3279,8 +3284,8 @@ public function testGetCountForPaginationWithColumnAliases(): void $columns = ['body as post_body', 'teaser', 'posts.created as published']; $builder->from('posts')->select($columns); - $builder->getConnection()->expects('select')->with('select count("body", "teaser", "posts"."created") as "aggregate" from "posts"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select count("body", "teaser", "posts"."created") as "aggregate" from "posts"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); @@ -3293,8 +3298,8 @@ public function testGetCountForPaginationWithUnion(): void $builder = $this->getBuilder(); $builder->from('posts')->select('id')->union($this->getBuilder()->from('videos')->select('id')); - $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "id" from "posts") union (select "id" from "videos")) as "temp_table"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "id" from "posts") union (select "id" from "videos")) as "temp_table"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); @@ -3307,8 +3312,8 @@ public function testGetCountForPaginationWithUnionOrders(): void $builder = $this->getBuilder(); $builder->from('posts')->select('id')->union($this->getBuilder()->from('videos')->select('id'))->latest(); - $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "id" from "posts") union (select "id" from "videos")) as "temp_table"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "id" from "posts") union (select "id" from "videos")) as "temp_table"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); @@ -3321,8 +3326,8 @@ public function testGetCountForPaginationWithUnionLimitAndOffset(): void $builder = $this->getBuilder(); $builder->from('posts')->select('id')->union($this->getBuilder()->from('videos')->select('id'))->limit(15)->offset(1); - $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "id" from "posts") union (select "id" from "videos")) as "temp_table"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "id" from "posts") union (select "id" from "videos")) as "temp_table"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); @@ -3335,8 +3340,8 @@ public function testGetCountForPaginationWithGroupedUnionLimitAndOffset(): void $builder = $this->getBuilder(); $builder->from('posts')->select('category')->groupBy('category')->unionAll($this->getBuilder()->from('videos')->select('category'))->limit(15)->offset(1); - $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "category" from "posts" group by "category") union all (select "category" from "videos")) as "aggregate_table"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "category" from "posts" group by "category") union all (select "category" from "videos")) as "aggregate_table"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); @@ -3349,8 +3354,8 @@ public function testGetCountForPaginationWithGroupedUnionOrders(): void $builder = $this->getBuilder(); $builder->from('posts')->select('category')->groupBy('category')->unionAll($this->getBuilder()->from('videos')->select('category'))->orderBy('category')->orderByRaw('field(category, ?)', ['news']); - $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "category" from "posts" group by "category") union all (select "category" from "videos")) as "aggregate_table"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from ((select "category" from "posts" group by "category") union all (select "category" from "videos")) as "aggregate_table"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); @@ -3400,8 +3405,8 @@ public function testGroupLimitCompilationWithAndWithoutOffset(): void [], true, [] - )->andReturn([]); - $implicitColumns->getProcessor()->expects('processSelect')->andReturn([]); + )->returns([]); + $implicitColumns->getProcessor()->expects('processSelect')->returns([]); $implicitColumns->get(['id']); } @@ -3411,8 +3416,8 @@ public function testGroupLimitBindingsStayInSqlOrderWhenEmbedded(string $driver, $inner = $driver === 'sqlite' ? $this->getSQLiteBuilder() : $this->getMySqlBuilder(); $legacy = $driver === 'mysql-legacy'; if ($driver !== 'sqlite') { - $inner->getConnection()->shouldReceive('getServerVersion')->andReturn($legacy ? '5.7.44' : '8.4.0'); - $inner->getConnection()->shouldReceive('isMaria')->andReturn(false); + $inner->getConnection()->allows('getServerVersion')->returns($legacy ? '5.7.44' : '8.4.0'); + $inner->getConnection()->allows('isMaria')->returns(false); } $inner->select('id')->from('posts')->where('enabled', true) @@ -3489,8 +3494,8 @@ public function testGroupedPaginationAppliesTimeoutToTheOuterCountStatement(): v [true, 10], true, [], - )->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + )->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); @@ -3753,7 +3758,7 @@ public function testExplainKeepsUntimedStatementSqlAndBindings(): void $builder->getConnection()->expects('select')->with( 'EXPLAIN select * from `users` where `id` = ?', [1], - )->andReturn([$explanation]); + )->returns([$explanation]); $this->assertSame([$explanation], $builder->explain()->all()); } @@ -3783,14 +3788,14 @@ public function testRelationSubqueriesCompileInSelectAndFromClausesAcrossDatabas public function testCrossDatabaseQualificationKeepsQualifiedDerivedTablesAndTablelessSubqueriesUnchanged(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getDatabaseName')->andReturn('other_database'); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getDatabaseName')->returns('other_database'); + $connection->allows('getTablePrefix')->returns(''); - $derived = new Builder($connection, new Grammar($connection), m::mock(Processor::class)); + $derived = new Builder($connection, new Grammar($connection), Double::for(Processor::class)); $derived->from('other_database.events'); - $subquery = new Builder($connection, new Grammar($connection), m::mock(Processor::class)); + $subquery = new Builder($connection, new Grammar($connection), Double::for(Processor::class)); $subquery->fromSub($derived, 'derived'); $outer = $this->getBuilder()->from('users')->whereIn('id', $subquery); @@ -3800,7 +3805,7 @@ public function testCrossDatabaseQualificationKeepsQualifiedDerivedTablesAndTabl $outer->toSql() ); - $tableless = new Builder($connection, new Grammar($connection), m::mock(Processor::class)); + $tableless = new Builder($connection, new Grammar($connection), Double::for(Processor::class)); $tableless->selectRaw('1'); $this->assertSame( @@ -3844,7 +3849,7 @@ public function testRelationSubqueryCompilesForInsertUsing(): void $builder->getConnection()->expects('affectingStatement')->with( 'insert into "archived_scores" ("score") select "score" from "queryable_subquery_related" where "queryable_subquery_related"."parent_id" = ? and "queryable_subquery_related"."parent_id" is not null', [7], - )->andReturn(1); + )->returns(1); $this->assertSame( 1, @@ -4923,8 +4928,8 @@ public function testRawExpressionsInSelect(): void public function testFindReturnsFirstResultByID(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select * from "users" where "id" = ? limit 1', [1], true, [])->andReturn([['foo' => 'bar']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['foo' => 'bar']])->andReturnUsing(function ($query, $results) { + $builder->getConnection()->expects('select')->with('select * from "users" where "id" = ? limit 1', [1], true, [])->returns([['foo' => 'bar']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['foo' => 'bar']])->resolves(function ($query, $results) { return $results; }); $results = $builder->from('users')->find(1); @@ -4944,20 +4949,24 @@ public function testFindOrReturnsFirstResultByID(): void { $builder = $this->getMockQueryBuilder(); $data = new stdClass; - $builder->expects('get')->with(['*'])->andReturn(new Collection([$data])); - $builder->expects('get')->with(['column'])->andReturn(new Collection([$data])); - $builder->expects('get')->with(['*'])->andReturn(new Collection); + $columns = []; + $builder->expects('get')->times(3)->resolves(function (array $requested) use (&$columns, $data): Collection { + $columns[] = $requested; + + return count($columns) === 3 ? new Collection : new Collection([$data]); + }); $this->assertSame($data, $builder->findOr(1, fn (): string => 'callback result')); $this->assertSame($data, $builder->findOr(1, ['column'], fn (): string => 'callback result')); $this->assertSame('callback result', $builder->findOr(1, fn (): string => 'callback result')); + $this->assertSame([['*'], ['column'], ['*']], $columns); } public function testFirstMethodReturnsFirstResult(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select * from "users" where "id" = ? limit 1', [1], true, [])->andReturn([['foo' => 'bar']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['foo' => 'bar']])->andReturnUsing(function ($query, $results) { + $builder->getConnection()->expects('select')->with('select * from "users" where "id" = ? limit 1', [1], true, [])->returns([['foo' => 'bar']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['foo' => 'bar']])->resolves(function ($query, $results) { return $results; }); $results = $builder->from('users')->where('id', '=', 1)->first(); @@ -4967,8 +4976,8 @@ public function testFirstMethodReturnsFirstResult(): void public function testFirstOrFailMethodReturnsFirstResult(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select * from "users" where "id" = ? limit 1', [1], true, [])->andReturn([['foo' => 'bar']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['foo' => 'bar']])->andReturnUsing(function ($query, $results) { + $builder->getConnection()->expects('select')->with('select * from "users" where "id" = ? limit 1', [1], true, [])->returns([['foo' => 'bar']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['foo' => 'bar']])->resolves(function ($query, $results) { return $results; }); $results = $builder->from('users')->where('id', '=', 1)->firstOrFail(); @@ -4978,9 +4987,9 @@ public function testFirstOrFailMethodReturnsFirstResult(): void public function testFirstOrFailMethodThrowsRecordNotFoundException(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select * from "users" where "id" = ? limit 1', [1], true, [])->andReturn([]); + $builder->getConnection()->expects('select')->with('select * from "users" where "id" = ? limit 1', [1], true, [])->returns([]); - $builder->getProcessor()->expects('processSelect')->with($builder, [])->andReturn([]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [])->returns([]); $this->expectExceptionObject(new RecordNotFoundException('No record found for the given query.')); @@ -4990,16 +4999,16 @@ public function testFirstOrFailMethodThrowsRecordNotFoundException(): void public function testPluckMethodGetsCollectionOfColumnValues(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->andReturn([['foo' => 'bar'], ['foo' => 'baz']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['foo' => 'bar'], ['foo' => 'baz']])->andReturnUsing(function ($query, $results) { + $builder->getConnection()->expects('select')->returns([['foo' => 'bar'], ['foo' => 'baz']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['foo' => 'bar'], ['foo' => 'baz']])->resolves(function ($query, $results) { return $results; }); $results = $builder->from('users')->where('id', '=', 1)->pluck('foo'); $this->assertEquals(['bar', 'baz'], $results->all()); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->andReturn([['id' => 1, 'foo' => 'bar'], ['id' => 10, 'foo' => 'baz']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['id' => 1, 'foo' => 'bar'], ['id' => 10, 'foo' => 'baz']])->andReturnUsing(function ($query, $results) { + $builder->getConnection()->expects('select')->returns([['id' => 1, 'foo' => 'bar'], ['id' => 10, 'foo' => 'baz']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['id' => 1, 'foo' => 'bar'], ['id' => 10, 'foo' => 'baz']])->resolves(function ($query, $results) { return $results; }); $results = $builder->from('users')->where('id', '=', 1)->pluck('foo', 'id'); @@ -5010,7 +5019,7 @@ public function testPluckFetchesColumnDirectlyForPdoConnections(): void { $connection = $this->getConnection(connectionClass: PdoConnection::class); $builder = new Builder($connection, new Grammar($connection), new Processor); - $connection->expects('select')->with('select "foo" from "users"', [], true, [PDO::FETCH_COLUMN])->andReturn(['bar', 'baz']); + $connection->expects('select')->with('select "foo" from "users"', [], true, [PDO::FETCH_COLUMN])->returns(['bar', 'baz']); $this->assertSame(['bar', 'baz'], $builder->from('users')->pluck('foo')->all()); } @@ -5018,8 +5027,8 @@ public function testPluckFetchesColumnDirectlyForPdoConnections(): void public function testPluckAvoidsDuplicateColumnSelection(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select "foo" from "users" where "id" = ?', [1], true, [])->andReturn([['foo' => 'bar']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['foo' => 'bar']])->andReturnUsing(function ($query, $results) { + $builder->getConnection()->expects('select')->with('select "foo" from "users" where "id" = ?', [1], true, [])->returns([['foo' => 'bar']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['foo' => 'bar']])->resolves(function ($query, $results) { return $results; }); $results = $builder->from('users')->where('id', '=', 1)->pluck('foo', 'foo'); @@ -5030,8 +5039,8 @@ public function testImplode(): void { // Test without glue. $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->andReturn([['foo' => 'bar'], ['foo' => 'baz']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['foo' => 'bar'], ['foo' => 'baz']])->andReturnUsing(function ($query, $results) { + $builder->getConnection()->expects('select')->returns([['foo' => 'bar'], ['foo' => 'baz']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['foo' => 'bar'], ['foo' => 'baz']])->resolves(function ($query, $results) { return $results; }); $results = $builder->from('users')->where('id', '=', 1)->implode('foo'); @@ -5039,8 +5048,8 @@ public function testImplode(): void // Test with glue. $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->andReturn([['foo' => 'bar'], ['foo' => 'baz']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['foo' => 'bar'], ['foo' => 'baz']])->andReturnUsing(function ($query, $results) { + $builder->getConnection()->expects('select')->returns([['foo' => 'bar'], ['foo' => 'baz']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['foo' => 'bar'], ['foo' => 'baz']])->resolves(function ($query, $results) { return $results; }); $results = $builder->from('users')->where('id', '=', 1)->implode('foo', ','); @@ -5050,8 +5059,8 @@ public function testImplode(): void public function testValueMethodReturnsSingleColumn(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select "foo" from "users" where "id" = ? limit 1', [1], true, [])->andReturn([['foo' => 'bar']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['foo' => 'bar']])->andReturn([['foo' => 'bar']]); + $builder->getConnection()->expects('select')->with('select "foo" from "users" where "id" = ? limit 1', [1], true, [])->returns([['foo' => 'bar']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['foo' => 'bar']])->returns([['foo' => 'bar']]); $results = $builder->from('users')->where('id', '=', 1)->value('foo'); $this->assertSame('bar', $results); } @@ -5059,8 +5068,8 @@ public function testValueMethodReturnsSingleColumn(): void public function testRawValueMethodReturnsSingleColumn(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select UPPER("foo") from "users" where "id" = ? limit 1', [1], true, [])->andReturn([['UPPER("foo")' => 'BAR']]); - $builder->getProcessor()->expects('processSelect')->with($builder, [['UPPER("foo")' => 'BAR']])->andReturn([['UPPER("foo")' => 'BAR']]); + $builder->getConnection()->expects('select')->with('select UPPER("foo") from "users" where "id" = ? limit 1', [1], true, [])->returns([['UPPER("foo")' => 'BAR']]); + $builder->getProcessor()->expects('processSelect')->with(Argument::same($builder), [['UPPER("foo")' => 'BAR']])->returns([['UPPER("foo")' => 'BAR']]); $results = $builder->from('users')->where('id', '=', 1)->rawValue('UPPER("foo")'); $this->assertSame('BAR', $results); } @@ -5068,58 +5077,58 @@ public function testRawValueMethodReturnsSingleColumn(): void public function testAggregateFunctions(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); $results = $builder->from('users')->count(); $this->assertEquals(1, $results); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select exists(select * from "users") as "exists"', [], true)->andReturn([['exists' => 1]]); + $builder->getConnection()->expects('select')->with('select exists(select * from "users") as "exists"', [], true)->returns([['exists' => 1]]); $results = $builder->from('users')->exists(); $this->assertTrue($results); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select exists(select * from "users") as "exists"', [], true)->andReturn([['exists' => 0]]); + $builder->getConnection()->expects('select')->with('select exists(select * from "users") as "exists"', [], true)->returns([['exists' => 0]]); $results = $builder->from('users')->doesntExist(); $this->assertTrue($results); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select max("id") as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select max("id") as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); $results = $builder->from('users')->max('id'); $this->assertEquals(1, $results); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select min("id") as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select min("id") as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); $results = $builder->from('users')->min('id'); $this->assertEquals(1, $results); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select sum("id") as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select sum("id") as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); $results = $builder->from('users')->sum('id'); $this->assertEquals(1, $results); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select avg("id") as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select avg("id") as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); $results = $builder->from('users')->avg('id'); $this->assertEquals(1, $results); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select avg("id") as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select avg("id") as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); $results = $builder->from('users')->average('id'); @@ -5129,13 +5138,13 @@ public function testAggregateFunctions(): void public function testExistsOr(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->andReturn([['exists' => 1]]); + $builder->getConnection()->expects('select')->returns([['exists' => 1]]); $results = $builder->from('users')->doesntExistOr(function (): int { return 123; }); $this->assertSame(123, $results); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->andReturn([['exists' => 0]]); + $builder->getConnection()->expects('select')->returns([['exists' => 0]]); $results = $builder->from('users')->doesntExistOr(function (): never { throw new RuntimeException; }); @@ -5145,13 +5154,13 @@ public function testExistsOr(): void public function testDoesntExistsOr(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->andReturn([['exists' => 0]]); + $builder->getConnection()->expects('select')->returns([['exists' => 0]]); $results = $builder->from('users')->existsOr(function (): int { return 123; }); $this->assertSame(123, $results); $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->andReturn([['exists' => 1]]); + $builder->getConnection()->expects('select')->returns([['exists' => 1]]); $results = $builder->from('users')->existsOr(function (): never { throw new RuntimeException; }); @@ -5161,10 +5170,10 @@ public function testDoesntExistsOr(): void public function testAggregateResetFollowedByGet(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getConnection()->expects('select')->with('select sum("id") as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 2]]); - $builder->getConnection()->expects('select')->with('select "column1", "column2" from "users"', [], true, [])->andReturn([['column1' => 'foo', 'column2' => 'bar']]); - $builder->getProcessor()->expects('processSelect')->times(3)->andReturnUsing(function (Builder $builder, array $results): array { + $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getConnection()->expects('select')->with('select sum("id") as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 2]]); + $builder->getConnection()->expects('select')->with('select "column1", "column2" from "users"', [], true, [])->returns([['column1' => 'foo', 'column2' => 'bar']]); + $builder->getProcessor()->expects('processSelect')->times(3)->resolves(function (Builder $builder, array $results): array { return $results; }); $builder->from('users')->select('column1', 'column2'); @@ -5179,9 +5188,9 @@ public function testAggregateResetFollowedByGet(): void public function testAggregateResetFollowedBySelectGet(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select count("column1") as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getConnection()->expects('select')->with('select "column2", "column3" from "users"', [], true, [])->andReturn([['column2' => 'foo', 'column3' => 'bar']]); - $builder->getProcessor()->expects('processSelect')->times(2)->andReturnUsing(function (Builder $builder, array $results): array { + $builder->getConnection()->expects('select')->with('select count("column1") as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getConnection()->expects('select')->with('select "column2", "column3" from "users"', [], true, [])->returns([['column2' => 'foo', 'column3' => 'bar']]); + $builder->getProcessor()->expects('processSelect')->times(2)->resolves(function (Builder $builder, array $results): array { return $results; }); $builder->from('users'); @@ -5194,9 +5203,9 @@ public function testAggregateResetFollowedBySelectGet(): void public function testAggregateResetFollowedByGetWithColumns(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select count("column1") as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getConnection()->expects('select')->with('select "column2", "column3" from "users"', [], true, [])->andReturn([['column2' => 'foo', 'column3' => 'bar']]); - $builder->getProcessor()->expects('processSelect')->times(2)->andReturnUsing(function (Builder $builder, array $results): array { + $builder->getConnection()->expects('select')->with('select count("column1") as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getConnection()->expects('select')->with('select "column2", "column3" from "users"', [], true, [])->returns([['column2' => 'foo', 'column3' => 'bar']]); + $builder->getProcessor()->expects('processSelect')->times(2)->resolves(function (Builder $builder, array $results): array { return $results; }); $builder->from('users'); @@ -5209,8 +5218,8 @@ public function testAggregateResetFollowedByGetWithColumns(): void public function testAggregateWithSubSelect(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from "users"', [], true, [])->andReturn([['aggregate' => 1]]); - $builder->getProcessor()->expects('processSelect')->andReturnUsing(function ($builder, $results) { + $builder->getConnection()->expects('select')->with('select count(*) as "aggregate" from "users"', [], true, [])->returns([['aggregate' => 1]]); + $builder->getProcessor()->expects('processSelect')->resolves(function ($builder, $results) { return $results; }); $builder->from('users')->selectSub(function ($query) { @@ -5242,7 +5251,7 @@ public function testSubqueriesBindings(): void public function testInsertMethod(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('insert')->with('insert into "users" ("email") values (?)', ['foo'])->andReturn(true); + $builder->getConnection()->expects('insert')->with('insert into "users" ("email") values (?)', ['foo'])->returns(true); $result = $builder->from('users')->insert(['email' => 'foo']); $this->assertTrue($result); } @@ -5250,7 +5259,7 @@ public function testInsertMethod(): void public function testInsertUsingMethod(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert into "table1" ("foo") select "bar" from "table2" where "foreign_id" = ?', [5])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert into "table1" ("foo") select "bar" from "table2" where "foreign_id" = ?', [5])->returns(1); $result = $builder->from('table1')->insertUsing( ['foo'], @@ -5265,7 +5274,7 @@ function (Builder $query) { public function testInsertUsingWithEmptyColumns(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert into "table1" select * from "table2" where "foreign_id" = ?', [5])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert into "table1" select * from "table2" where "foreign_id" = ?', [5])->returns(1); $result = $builder->from('table1')->insertUsing( [], @@ -5294,7 +5303,7 @@ public function testInsertOrIgnoreMethod(): void public function testMySqlInsertOrIgnoreMethod(): void { $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert ignore into `users` (`email`) values (?)', ['foo'])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert ignore into `users` (`email`) values (?)', ['foo'])->returns(1); $result = $builder->from('users')->insertOrIgnore(['email' => 'foo']); $this->assertEquals(1, $result); } @@ -5302,7 +5311,7 @@ public function testMySqlInsertOrIgnoreMethod(): void public function testPostgresInsertOrIgnoreMethod(): void { $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email") values (?) on conflict do nothing', ['foo'])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email") values (?) on conflict do nothing', ['foo'])->returns(1); $result = $builder->from('users')->insertOrIgnore(['email' => 'foo']); $this->assertEquals(1, $result); } @@ -5310,7 +5319,7 @@ public function testPostgresInsertOrIgnoreMethod(): void public function testSQLiteInsertOrIgnoreMethod(): void { $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert or ignore into "users" ("email") values (?)', ['foo'])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert or ignore into "users" ("email") values (?)', ['foo'])->returns(1); $result = $builder->from('users')->insertOrIgnore(['email' => 'foo']); $this->assertEquals(1, $result); } @@ -5344,7 +5353,7 @@ public function testPostgresInsertOrIgnoreReturningMethod(): void $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "users" ("email") values (?) on conflict do nothing returning "id"', ['foo'] - )->andReturn([['id' => 1]]); + )->returns([['id' => 1]]); $result = $builder->from('users')->insertOrIgnoreReturning(['email' => 'foo'], ['id']); $this->assertInstanceOf(Collection::class, $result); $this->assertSame([['id' => 1]], $result->all()); @@ -5357,7 +5366,7 @@ public function testPostgresInsertOrIgnoreReturningMethodWithUniqueByColumn(): v $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "users" ("email", "name") values (?, ?) on conflict ("email") do nothing returning *', ['foo', 'bar'] - )->andReturn([['id' => 1, 'email' => 'foo', 'name' => 'bar']]); + )->returns([['id' => 1, 'email' => 'foo', 'name' => 'bar']]); $result = $builder->from('users')->insertOrIgnoreReturning(['email' => 'foo', 'name' => 'bar'], ['*'], 'email'); $this->assertInstanceOf(Collection::class, $result); $this->assertSame([['id' => 1, 'email' => 'foo', 'name' => 'bar']], $result->all()); @@ -5370,7 +5379,7 @@ public function testPostgresInsertOrIgnoreReturningMethodWithUniqueByColumns(): $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "users" ("email", "name") values (?, ?) on conflict ("email", "name") do nothing returning *', ['foo', 'bar'] - )->andReturn([['id' => 1, 'email' => 'foo', 'name' => 'bar']]); + )->returns([['id' => 1, 'email' => 'foo', 'name' => 'bar']]); $result = $builder->from('users')->insertOrIgnoreReturning(['email' => 'foo', 'name' => 'bar'], ['*'], ['email', 'name']); $this->assertInstanceOf(Collection::class, $result); $this->assertSame([['id' => 1, 'email' => 'foo', 'name' => 'bar']], $result->all()); @@ -5383,7 +5392,7 @@ public function testPostgresInsertOrIgnoreReturningMethodWithMultipleRecords(): $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "users" ("email") values (?), (?) on conflict do nothing returning "id", "email"', ['foo', 'bar'] - )->andReturn([['id' => 1, 'email' => 'foo']]); + )->returns([['id' => 1, 'email' => 'foo']]); $result = $builder->from('users')->insertOrIgnoreReturning( [['email' => 'foo'], ['email' => 'bar']], ['id', 'email'] @@ -5399,7 +5408,7 @@ public function testSqliteInsertOrIgnoreReturningMethod(): void $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "users" ("email") values (?) on conflict do nothing returning "id"', ['foo'] - )->andReturn([['id' => 1]]); + )->returns([['id' => 1]]); $result = $builder->from('users')->insertOrIgnoreReturning(['email' => 'foo'], ['id']); $this->assertInstanceOf(Collection::class, $result); $this->assertSame([['id' => 1]], $result->all()); @@ -5412,7 +5421,7 @@ public function testSqliteInsertOrIgnoreReturningMethodWithUniqueByColumn(): voi $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "users" ("email", "name") values (?, ?) on conflict ("email") do nothing returning *', ['foo', 'bar'] - )->andReturn([['id' => 1, 'email' => 'foo', 'name' => 'bar']]); + )->returns([['id' => 1, 'email' => 'foo', 'name' => 'bar']]); $result = $builder->from('users')->insertOrIgnoreReturning(['email' => 'foo', 'name' => 'bar'], ['*'], 'email'); $this->assertInstanceOf(Collection::class, $result); $this->assertSame([['id' => 1, 'email' => 'foo', 'name' => 'bar']], $result->all()); @@ -5425,7 +5434,7 @@ public function testSqliteInsertOrIgnoreReturningMethodWithUniqueByColumns(): vo $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "users" ("email", "name") values (?, ?) on conflict ("email", "name") do nothing returning *', ['foo', 'bar'] - )->andReturn([['id' => 1, 'email' => 'foo', 'name' => 'bar']]); + )->returns([['id' => 1, 'email' => 'foo', 'name' => 'bar']]); $result = $builder->from('users')->insertOrIgnoreReturning(['email' => 'foo', 'name' => 'bar'], ['*'], ['email', 'name']); $this->assertInstanceOf(Collection::class, $result); $this->assertSame([['id' => 1, 'email' => 'foo', 'name' => 'bar']], $result->all()); @@ -5438,7 +5447,7 @@ public function testSqliteInsertOrIgnoreReturningMethodWithMultipleRecords(): vo $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "users" ("email") values (?), (?) on conflict do nothing returning "id", "email"', ['foo', 'bar'] - )->andReturn([['id' => 1, 'email' => 'foo']]); + )->returns([['id' => 1, 'email' => 'foo']]); $result = $builder->from('users')->insertOrIgnoreReturning( [['email' => 'foo'], ['email' => 'bar']], ['id', 'email'] @@ -5474,7 +5483,7 @@ public function testInsertOrIgnoreReturningDoesNotMarkRecordsModifiedWhenNoRowsW $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "users" ("email") values (?) on conflict do nothing returning *', ['foo'] - )->andReturn([]); + )->returns([]); $builder->getConnection()->expects('recordsHaveBeenModified')->with(false); $result = $builder->from('users')->insertOrIgnoreReturning(['email' => 'foo']); $this->assertInstanceOf(Collection::class, $result); @@ -5488,7 +5497,7 @@ public function testInsertOrIgnoreReturningRunsBeforeQueryCallbacks(): void $builder->getConnection()->expects('selectFromWriteConnection')->with( 'insert into "members" ("email") values (?) on conflict do nothing returning *', ['foo'] - )->andReturn([['email' => 'foo']]); + )->returns([['email' => 'foo']]); $result = $builder->from('users') ->beforeQuery(fn (Builder $query) => $query->from('members')) @@ -5507,7 +5516,7 @@ public function testInsertOrIgnoreUsingMethod(): void public function testMySqlInsertOrIgnoreUsingMethod(): void { $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert ignore into `table1` (`foo`) select `bar` from `table2` where `foreign_id` = ?', [0 => 5])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert ignore into `table1` (`foo`) select `bar` from `table2` where `foreign_id` = ?', [0 => 5])->returns(1); $result = $builder->from('table1')->insertOrIgnoreUsing( ['foo'], @@ -5522,7 +5531,7 @@ function (Builder $query): void { public function testMySqlInsertOrIgnoreUsingWithEmptyColumns(): void { $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert ignore into `table1` select * from `table2` where `foreign_id` = ?', [0 => 5])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert ignore into `table1` select * from `table2` where `foreign_id` = ?', [0 => 5])->returns(1); $result = $builder->from('table1')->insertOrIgnoreUsing( [], @@ -5544,7 +5553,7 @@ public function testMySqlInsertOrIgnoreUsingInvalidSubquery(): void public function testPostgresInsertOrIgnoreUsingMethod(): void { $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert into "table1" ("foo") select "bar" from "table2" where "foreign_id" = ? on conflict do nothing', [5])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert into "table1" ("foo") select "bar" from "table2" where "foreign_id" = ? on conflict do nothing', [5])->returns(1); $result = $builder->from('table1')->insertOrIgnoreUsing( ['foo'], @@ -5559,7 +5568,7 @@ function (Builder $query) { public function testPostgresInsertOrIgnoreUsingWithEmptyColumns(): void { $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert into "table1" select * from "table2" where "foreign_id" = ? on conflict do nothing', [5])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert into "table1" select * from "table2" where "foreign_id" = ? on conflict do nothing', [5])->returns(1); $result = $builder->from('table1')->insertOrIgnoreUsing( [], @@ -5581,7 +5590,7 @@ public function testPostgresInsertOrIgnoreUsingInvalidSubquery(): void public function testSQLiteInsertOrIgnoreUsingMethod(): void { $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert or ignore into "table1" ("foo") select "bar" from "table2" where "foreign_id" = ?', [5])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert or ignore into "table1" ("foo") select "bar" from "table2" where "foreign_id" = ?', [5])->returns(1); $result = $builder->from('table1')->insertOrIgnoreUsing( ['foo'], @@ -5596,7 +5605,7 @@ function (Builder $query): void { public function testSQLiteInsertOrIgnoreUsingWithEmptyColumns(): void { $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert or ignore into "table1" select * from "table2" where "foreign_id" = ?', [5])->andReturn(1); + $builder->getConnection()->expects('affectingStatement')->with('insert or ignore into "table1" select * from "table2" where "foreign_id" = ?', [5])->returns(1); $result = $builder->from('table1')->insertOrIgnoreUsing( [], @@ -5618,7 +5627,7 @@ public function testSQLiteInsertOrIgnoreUsingInvalidSubquery(): void public function testInsertGetIdMethod(): void { $builder = $this->getBuilder(); - $builder->getProcessor()->expects('processInsertGetId')->with($builder, 'insert into "users" ("email") values (?)', ['foo'], 'id')->andReturn(1); + $builder->getProcessor()->expects('processInsertGetId')->with(Argument::same($builder), 'insert into "users" ("email") values (?)', ['foo'], 'id')->returns(1); $result = $builder->from('users')->insertGetId(['email' => 'foo'], 'id'); $this->assertEquals(1, $result); } @@ -5626,7 +5635,7 @@ public function testInsertGetIdMethod(): void public function testInsertGetIdMethodRemovesExpressions(): void { $builder = $this->getBuilder(); - $builder->getProcessor()->expects('processInsertGetId')->with($builder, 'insert into "users" ("email", "bar") values (?, bar)', ['foo'], 'id')->andReturn(1); + $builder->getProcessor()->expects('processInsertGetId')->with(Argument::same($builder), 'insert into "users" ("email", "bar") values (?, bar)', ['foo'], 'id')->returns(1); $result = $builder->from('users')->insertGetId(['email' => 'foo', 'bar' => new Raw('bar')], 'id'); $this->assertEquals(1, $result); } @@ -5634,22 +5643,22 @@ public function testInsertGetIdMethodRemovesExpressions(): void public function testInsertGetIdWithEmptyValues(): void { $builder = $this->getMySqlBuilder(); - $builder->getProcessor()->expects('processInsertGetId')->with($builder, 'insert into `users` () values ()', [], null); + $builder->getProcessor()->expects('processInsertGetId')->with(Argument::same($builder), 'insert into `users` () values ()', [], null); $builder->from('users')->insertGetId([]); $builder = $this->getPostgresBuilder(); - $builder->getProcessor()->expects('processInsertGetId')->with($builder, 'insert into "users" default values returning "id"', [], null); + $builder->getProcessor()->expects('processInsertGetId')->with(Argument::same($builder), 'insert into "users" default values returning "id"', [], null); $builder->from('users')->insertGetId([]); $builder = $this->getSQLiteBuilder(); - $builder->getProcessor()->expects('processInsertGetId')->with($builder, 'insert into "users" default values', [], null); + $builder->getProcessor()->expects('processInsertGetId')->with(Argument::same($builder), 'insert into "users" default values', [], null); $builder->from('users')->insertGetId([]); } public function testInsertMethodRespectsRawBindings(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('insert')->with('insert into "users" ("email") values (CURRENT TIMESTAMP)', [])->andReturn(true); + $builder->getConnection()->expects('insert')->with('insert into "users" ("email") values (CURRENT TIMESTAMP)', [])->returns(true); $result = $builder->from('users')->insert(['email' => new Raw('CURRENT TIMESTAMP')]); $this->assertTrue($result); } @@ -5657,7 +5666,7 @@ public function testInsertMethodRespectsRawBindings(): void public function testMultipleInsertsWithExpressionValues(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('insert')->with('insert into "users" ("email") values (UPPER(\'Foo\')), (LOWER(\'Foo\'))', [])->andReturn(true); + $builder->getConnection()->expects('insert')->with('insert into "users" ("email") values (UPPER(\'Foo\')), (LOWER(\'Foo\'))', [])->returns(true); $result = $builder->from('users')->insert([['email' => new Raw("UPPER('Foo')")], ['email' => new Raw("LOWER('Foo')")]]); $this->assertTrue($result); } @@ -5665,12 +5674,12 @@ public function testMultipleInsertsWithExpressionValues(): void public function testUpdateMethod(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->where('id', '=', 1)->update(['email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('update')->with('update `users` set `email` = ?, `name` = ? where `id` = ? order by `foo` desc limit 5', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update `users` set `email` = ?, `name` = ? where `id` = ? order by `foo` desc limit 5', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->where('id', '=', 1)->orderBy('foo', 'desc')->limit(5)->update(['email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); } @@ -5678,24 +5687,24 @@ public function testUpdateMethod(): void public function testUpsertMethod(): void { $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->andReturn(false); - $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`, `name`) values (?, ?), (?, ?) on duplicate key update `email` = values(`email`), `name` = values(`name`)', ['foo', 'bar', 'foo2', 'bar2'])->andReturn(2); + $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->returns(false); + $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`, `name`) values (?, ?), (?, ?) on duplicate key update `email` = values(`email`), `name` = values(`name`)', ['foo', 'bar', 'foo2', 'bar2'])->returns(2); $result = $builder->from('users')->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], 'email'); $this->assertEquals(2, $result); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->andReturn(true); - $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`, `name`) values (?, ?), (?, ?) as hypervel_upsert_alias on duplicate key update `email` = `hypervel_upsert_alias`.`email`, `name` = `hypervel_upsert_alias`.`name`', ['foo', 'bar', 'foo2', 'bar2'])->andReturn(2); + $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->returns(true); + $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`, `name`) values (?, ?), (?, ?) as hypervel_upsert_alias on duplicate key update `email` = `hypervel_upsert_alias`.`email`, `name` = `hypervel_upsert_alias`.`name`', ['foo', 'bar', 'foo2', 'bar2'])->returns(2); $result = $builder->from('users')->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], 'email'); $this->assertEquals(2, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email", "name") values (?, ?), (?, ?) on conflict ("email") do update set "email" = "excluded"."email", "name" = "excluded"."name"', ['foo', 'bar', 'foo2', 'bar2'])->andReturn(2); + $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email", "name") values (?, ?), (?, ?) on conflict ("email") do update set "email" = "excluded"."email", "name" = "excluded"."name"', ['foo', 'bar', 'foo2', 'bar2'])->returns(2); $result = $builder->from('users')->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], 'email'); $this->assertEquals(2, $result); $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email", "name") values (?, ?), (?, ?) on conflict ("email") do update set "email" = "excluded"."email", "name" = "excluded"."name"', ['foo', 'bar', 'foo2', 'bar2'])->andReturn(2); + $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email", "name") values (?, ?), (?, ?) on conflict ("email") do update set "email" = "excluded"."email", "name" = "excluded"."name"', ['foo', 'bar', 'foo2', 'bar2'])->returns(2); $result = $builder->from('users')->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], 'email'); $this->assertEquals(2, $result); } @@ -5703,24 +5712,24 @@ public function testUpsertMethod(): void public function testUpsertMethodWithUpdateColumns(): void { $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->andReturn(false); - $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`, `name`) values (?, ?), (?, ?) on duplicate key update `name` = values(`name`)', ['foo', 'bar', 'foo2', 'bar2'])->andReturn(2); + $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->returns(false); + $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`, `name`) values (?, ?), (?, ?) on duplicate key update `name` = values(`name`)', ['foo', 'bar', 'foo2', 'bar2'])->returns(2); $result = $builder->from('users')->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], 'email', ['name']); $this->assertEquals(2, $result); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->andReturn(true); - $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`, `name`) values (?, ?), (?, ?) as hypervel_upsert_alias on duplicate key update `name` = `hypervel_upsert_alias`.`name`', ['foo', 'bar', 'foo2', 'bar2'])->andReturn(2); + $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->returns(true); + $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`, `name`) values (?, ?), (?, ?) as hypervel_upsert_alias on duplicate key update `name` = `hypervel_upsert_alias`.`name`', ['foo', 'bar', 'foo2', 'bar2'])->returns(2); $result = $builder->from('users')->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], 'email', ['name']); $this->assertEquals(2, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email", "name") values (?, ?), (?, ?) on conflict ("email") do update set "name" = "excluded"."name"', ['foo', 'bar', 'foo2', 'bar2'])->andReturn(2); + $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email", "name") values (?, ?), (?, ?) on conflict ("email") do update set "name" = "excluded"."name"', ['foo', 'bar', 'foo2', 'bar2'])->returns(2); $result = $builder->from('users')->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], 'email', ['name']); $this->assertEquals(2, $result); $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email", "name") values (?, ?), (?, ?) on conflict ("email") do update set "name" = "excluded"."name"', ['foo', 'bar', 'foo2', 'bar2'])->andReturn(2); + $builder->getConnection()->expects('affectingStatement')->with('insert into "users" ("email", "name") values (?, ?), (?, ?) on conflict ("email") do update set "name" = "excluded"."name"', ['foo', 'bar', 'foo2', 'bar2'])->returns(2); $result = $builder->from('users')->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], 'email', ['name']); $this->assertEquals(2, $result); } @@ -5742,12 +5751,12 @@ public function testUpsertMethodWithEmptyUniqueByString(): void public function testUpdateMethodWithJoins(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('update')->with('update "users" inner join "orders" on "users"."id" = "orders"."user_id" set "email" = ?, "name" = ? where "users"."id" = ?', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" inner join "orders" on "users"."id" = "orders"."user_id" set "email" = ?, "name" = ? where "users"."id" = ?', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(['email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); $builder = $this->getBuilder(); - $builder->getConnection()->expects('update')->with('update "users" inner join "orders" on "users"."id" = "orders"."user_id" and "users"."id" = ? set "email" = ?, "name" = ?', [1, 'foo', 'bar'])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" inner join "orders" on "users"."id" = "orders"."user_id" and "users"."id" = ? set "email" = ?, "name" = ?', [1, 'foo', 'bar'])->returns(1); $result = $builder->from('users')->join('orders', function ($join) { $join->on('users.id', '=', 'orders.user_id') ->where('users.id', '=', 1); @@ -5758,12 +5767,12 @@ public function testUpdateMethodWithJoins(): void public function testUpdateMethodWithJoinsOnMySql(): void { $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('update')->with('update `users` inner join `orders` on `users`.`id` = `orders`.`user_id` set `email` = ?, `name` = ? where `users`.`id` = ?', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update `users` inner join `orders` on `users`.`id` = `orders`.`user_id` set `email` = ?, `name` = ? where `users`.`id` = ?', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(['email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('update')->with('update `users` inner join `orders` on `users`.`id` = `orders`.`user_id` and `users`.`id` = ? set `email` = ?, `name` = ?', [1, 'foo', 'bar'])->andReturn(1); + $builder->getConnection()->expects('update')->with('update `users` inner join `orders` on `users`.`id` = `orders`.`user_id` and `users`.`id` = ? set `email` = ?, `name` = ?', [1, 'foo', 'bar'])->returns(1); $result = $builder->from('users')->join('orders', function ($join) { $join->on('users.id', '=', 'orders.user_id') ->where('users.id', '=', 1); @@ -5774,17 +5783,17 @@ public function testUpdateMethodWithJoinsOnMySql(): void public function testUpdateMethodWithJoinsOnSQLite(): void { $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "rowid" in (select "users"."rowid" from "users" where "users"."id" > ? order by "id" asc limit 3)', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "rowid" in (select "users"."rowid" from "users" where "users"."id" > ? order by "id" asc limit 3)', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->where('users.id', '>', 1)->limit(3)->oldest('id')->update(['email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "rowid" in (select "users"."rowid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" where "users"."id" = ?)', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "rowid" in (select "users"."rowid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" where "users"."id" = ?)', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(['email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "rowid" in (select "users"."rowid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" and "users"."id" = ?)', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "rowid" in (select "users"."rowid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" and "users"."id" = ?)', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->join('orders', function ($join) { $join->on('users.id', '=', 'orders.user_id') ->where('users.id', '=', 1); @@ -5792,7 +5801,7 @@ public function testUpdateMethodWithJoinsOnSQLite(): void $this->assertEquals(1, $result); $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('update')->with('update "users" as "u" set "email" = ?, "name" = ? where "rowid" in (select "u"."rowid" from "users" as "u" inner join "orders" as "o" on "u"."id" = "o"."user_id")', ['foo', 'bar'])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" as "u" set "email" = ?, "name" = ? where "rowid" in (select "u"."rowid" from "users" as "u" inner join "orders" as "o" on "u"."id" = "o"."user_id")', ['foo', 'bar'])->returns(1); $result = $builder->from('users as u')->join('orders as o', 'u.id', '=', 'o.user_id')->update(['email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); } @@ -5800,17 +5809,17 @@ public function testUpdateMethodWithJoinsOnSQLite(): void public function testUpdateMethodWithoutJoinsOnPostgres(): void { $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->where('id', '=', 1)->update(['users.email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->where('id', '=', 1)->selectRaw('?', ['ignore'])->update(['users.email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('update')->with('update "users"."users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users"."users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users.users')->where('id', '=', 1)->selectRaw('?', ['ignore'])->update(['users.users.email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); } @@ -5818,12 +5827,12 @@ public function testUpdateMethodWithoutJoinsOnPostgres(): void public function testUpdateMethodWithJoinsOnPostgres(): void { $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" where "users"."id" = ?)', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" where "users"."id" = ?)', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(['email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" and "users"."id" = ?)', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" and "users"."id" = ?)', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->join('orders', function ($join) { $join->on('users.id', '=', 'orders.user_id') ->where('users.id', '=', 1); @@ -5831,7 +5840,7 @@ public function testUpdateMethodWithJoinsOnPostgres(): void $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" and "users"."id" = ? where "name" = ?)', ['foo', 'bar', 1, 'baz'])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "orders" on "users"."id" = "orders"."user_id" and "users"."id" = ? where "name" = ?)', ['foo', 'bar', 1, 'baz'])->returns(1); $result = $builder->from('users') ->join('orders', function ($join) { $join->on('users.id', '=', 'orders.user_id') @@ -5859,7 +5868,7 @@ public function testUpdateWithRawSourceAndLimit(string $database, ?string $alias $builder->getConnection()->expects('update')->with( 'update ' . $source . ' set "email" = ? where ' . $rowIdentifier . ' in (select ' . $selection . ' from ' . $source . $join . ' where "active" = ? limit 1)', ['new@example.com', 1], - )->andReturn(1); + )->returns(1); } $this->assertSame(1, $builder->where('active', 1)->limit(1)->update(['email' => 'new@example.com'])); @@ -5885,12 +5894,12 @@ public static function rawSourcesForLimitedWrites(): array public function testUpdateFromMethodWithJoinsOnPostgres(): void { $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? from "orders" where "users"."id" = ? and "users"."id" = "orders"."user_id"', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? from "orders" where "users"."id" = ? and "users"."id" = "orders"."user_id"', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->updateFrom(['email' => 'foo', 'name' => 'bar']); $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? from "orders" where "users"."id" = "orders"."user_id" and "users"."id" = ?', ['foo', 'bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? from "orders" where "users"."id" = "orders"."user_id" and "users"."id" = ?', ['foo', 'bar', 1])->returns(1); $result = $builder->from('users')->join('orders', function ($join) { $join->on('users.id', '=', 'orders.user_id') ->where('users.id', '=', 1); @@ -5898,7 +5907,7 @@ public function testUpdateFromMethodWithJoinsOnPostgres(): void $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? from "orders" where "name" = ? and "users"."id" = "orders"."user_id" and "users"."id" = ?', ['foo', 'bar', 'baz', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ?, "name" = ? from "orders" where "name" = ? and "users"."id" = "orders"."user_id" and "users"."id" = ?', ['foo', 'bar', 'baz', 1])->returns(1); $result = $builder->from('users') ->join('orders', function ($join) { $join->on('users.id', '=', 'orders.user_id') @@ -5914,7 +5923,7 @@ public function testUpdateFromWithJoinedSubqueryBindingsOnPostgres(): void $builder->getConnection()->expects('update')->with( 'update "users" as "target" set "email" = ?, "options" = jsonb_set("target"."options"::jsonb, \'{"enabled"}\', ?) from (select ? as marker) as "first", (select ? as marker) as "second", (select ? as marker) as "third" where "target"."name" = ? and "first"."marker" = ? and "second"."marker" = ?', ['after', 'true', 7, 9, 11, 'before', 8, 10], - )->andReturn(1); + )->returns(1); $builder->from('users', 'target') ->joinSub($this->getPostgresBuilder()->selectRaw('? as marker', [7]), 'first', function (JoinClause $join): void { @@ -5933,7 +5942,7 @@ public function testUpdateFromWithJoinedSubqueryBindingsOnPostgres(): void public function testUpdateMethodRespectsRaw(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = foo, "name" = ? where "id" = ?', ['bar', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = foo, "name" = ? where "id" = ?', ['bar', 1])->returns(1); $result = $builder->from('users')->where('id', '=', 1)->update(['email' => new Raw('foo'), 'name' => 'bar']); $this->assertEquals(1, $result); } @@ -5941,7 +5950,7 @@ public function testUpdateMethodRespectsRaw(): void public function testUpdateMethodWorksWithQueryAsValue(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "credits" = (select sum(credits) from "transactions" where "transactions"."user_id" = "users"."id" and "type" = ?) where "id" = ?', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "credits" = (select sum(credits) from "transactions" where "transactions"."user_id" = "users"."id" and "type" = ?) where "id" = ?', ['foo', 1])->returns(1); $result = $builder->from('users')->where('id', '=', 1)->update(['credits' => $this->getBuilder()->from('transactions')->selectRaw('sum(credits)')->whereColumn('transactions.user_id', 'users.id')->where('type', 'foo')]); $this->assertEquals(1, $result); @@ -5954,7 +5963,7 @@ public function testUpdateMethodWorksWithQueryAsValue(): void ->whereColumn('transactions.user_id', 'users.id') ->where('type', 'foo') ); - $builder->getConnection()->expects('update')->with('update "users" set "credits" = (select sum(credits) from "transactions" where "transactions"."user_id" = "users"."id" and "type" = ?) where "id" = ?', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "credits" = (select sum(credits) from "transactions" where "transactions"."user_id" = "users"."id" and "type" = ?) where "id" = ?', ['foo', 1])->returns(1); $result = $builder->from('users')->where('id', '=', 1)->update(['credits' => $subquery]); $this->assertSame(1, $result); @@ -5963,28 +5972,20 @@ public function testUpdateMethodWorksWithQueryAsValue(): void public function testUpdateOrInsertMethod(): void { $connection = new PdoConnection(new PDO('sqlite::memory:')); - $builder = m::mock(Builder::class . '[where,exists,insert]', [ - $connection, - new Grammar($connection), - new Processor, - ]); + $builder = Double::for(new Builder($connection, new Grammar($connection), new Processor))->passthru(); - $builder->expects('where')->with(['email' => 'foo'])->andReturn(m::self()); - $builder->expects('exists')->andReturn(false); - $builder->expects('insert')->with(['email' => 'foo', 'name' => 'bar'])->andReturn(true); + $builder->expects('where')->with(['email' => 'foo'])->returns($builder); + $builder->expects('exists')->returns(false); + $builder->expects('insert')->with(['email' => 'foo', 'name' => 'bar'])->returns(true); $this->assertTrue($builder->updateOrInsert(['email' => 'foo'], ['name' => 'bar'])); $connection = new PdoConnection(new PDO('sqlite::memory:')); - $builder = m::mock(Builder::class . '[where,exists,update]', [ - $connection, - new Grammar($connection), - new Processor, - ]); + $builder = Double::for(new Builder($connection, new Grammar($connection), new Processor))->passthru(); - $builder->expects('where')->with(['email' => 'foo'])->andReturn(m::self()); - $builder->expects('exists')->andReturn(true); - $builder->expects('update')->with(['name' => 'bar'])->andReturn(1); + $builder->expects('where')->with(['email' => 'foo'])->returns($builder); + $builder->expects('exists')->returns(true); + $builder->expects('update')->with(['name' => 'bar'])->returns(1); $this->assertTrue($builder->updateOrInsert(['email' => 'foo'], ['name' => 'bar'])); } @@ -5995,20 +5996,20 @@ public function testUpdateOrInsertMethodWithCallback(callable $values): void $builder = $this->getBuilder()->from('users'); $builder->getConnection()->expects('select') ->with('select exists(select * from "users" where ("email" = ?)) as "exists"', ['foo'], true) - ->andReturn([['exists' => false]]); + ->returns([['exists' => false]]); $builder->getConnection()->expects('insert') ->with('insert into "users" ("email", "name") values (?, ?)', ['foo', 'new']) - ->andReturn(true); + ->returns(true); $this->assertTrue($builder->updateOrInsert(['email' => 'foo'], $values)); $builder = $this->getBuilder()->from('users'); $builder->getConnection()->expects('select') ->with('select exists(select * from "users" where ("email" = ?)) as "exists"', ['foo'], true) - ->andReturn([['exists' => true]]); + ->returns([['exists' => true]]); $builder->getConnection()->expects('update') ->with('update "users" set "name" = ? where ("email" = ?)', ['updated', 'foo']) - ->andReturn(1); + ->returns(1); $this->assertTrue($builder->updateOrInsert(['email' => 'foo'], $values)); } @@ -6037,43 +6038,39 @@ public function __invoke(bool $exists): array public function testUpdateOrInsertMethodWorksWithEmptyUpdateValues(): void { $connection = new PdoConnection(new PDO('sqlite::memory:')); - $builder = m::spy(Builder::class . '[where,exists,update]', [ - $connection, - new Grammar($connection), - new Processor, - ]); + $builder = Double::for(new Builder($connection, new Grammar($connection), new Processor))->passthru(); - $builder->expects('where')->with(['email' => 'foo'])->andReturn(m::self()); - $builder->expects('exists')->andReturn(true); + $builder->expects('where')->with(['email' => 'foo'])->returns($builder); + $builder->expects('exists')->returns(true); $this->assertTrue($builder->updateOrInsert(['email' => 'foo'])); - $builder->shouldNotHaveReceived('update'); + $builder->received('update')->never(); } public function testDeleteMethod(): void { $builder = $this->getBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where "email" = ?', ['foo'])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where "email" = ?', ['foo'])->returns(1); $result = $builder->from('users')->where('email', '=', 'foo')->delete(); $this->assertEquals(1, $result); $builder = $this->getBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where "users"."id" = ?', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where "users"."id" = ?', [1])->returns(1); $result = $builder->from('users')->delete(1); $this->assertEquals(1, $result); $builder = $this->getBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where "users"."id" = ?', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where "users"."id" = ?', [1])->returns(1); $result = $builder->from('users')->selectRaw('?', ['ignore'])->delete(1); $this->assertEquals(1, $result); $builder = $this->getSqliteBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" where "email" = ? order by "id" asc limit 1)', ['foo'])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" where "email" = ? order by "id" asc limit 1)', ['foo'])->returns(1); $result = $builder->from('users')->where('email', '=', 'foo')->orderBy('id')->limit(1)->delete(); $this->assertEquals(1, $result); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('delete')->with('delete from `users` where `email` = ? order by `id` asc limit 1', ['foo'])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from `users` where `email` = ? order by `id` asc limit 1', ['foo'])->returns(1); $result = $builder->from('users')->where('email', '=', 'foo')->orderBy('id')->limit(1)->delete(); $this->assertEquals(1, $result); } @@ -6081,47 +6078,47 @@ public function testDeleteMethod(): void public function testDeleteWithJoinMethod(): void { $builder = $this->getSqliteBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" inner join "contacts" on "users"."id" = "contacts"."id" where "users"."email" = ? order by "users"."id" asc limit 1)', ['foo'])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" inner join "contacts" on "users"."id" = "contacts"."id" where "users"."email" = ? order by "users"."id" asc limit 1)', ['foo'])->returns(1); $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('users.email', '=', 'foo')->orderBy('users.id')->limit(1)->delete(); $this->assertEquals(1, $result); $builder = $this->getSqliteBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" as "u" where "rowid" in (select "u"."rowid" from "users" as "u" inner join "contacts" as "c" on "u"."id" = "c"."id")', [])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" as "u" where "rowid" in (select "u"."rowid" from "users" as "u" inner join "contacts" as "c" on "u"."id" = "c"."id")', [])->returns(1); $result = $builder->from('users as u')->join('contacts as c', 'u.id', '=', 'c.id')->delete(); $this->assertEquals(1, $result); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('delete')->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `email` = ?', ['foo'])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `email` = ?', ['foo'])->returns(1); $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('email', '=', 'foo')->delete(); $this->assertEquals(1, $result); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('delete')->with('delete `a` from `users` as `a` inner join `users` as `b` on `a`.`id` = `b`.`user_id` where `email` = ?', ['foo'])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete `a` from `users` as `a` inner join `users` as `b` on `a`.`id` = `b`.`user_id` where `email` = ?', ['foo'])->returns(1); $result = $builder->from('users AS a')->join('users AS b', 'a.id', '=', 'b.user_id')->where('email', '=', 'foo')->delete(); $this->assertEquals(1, $result); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('delete')->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `users`.`id` = ?', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `users`.`id` = ?', [1])->returns(1); $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->delete(1); $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "contacts" on "users"."id" = "contacts"."id" where "users"."email" = ?)', ['foo'])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "contacts" on "users"."id" = "contacts"."id" where "users"."email" = ?)', ['foo'])->returns(1); $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('users.email', '=', 'foo')->delete(); $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" as "a" where ("tableoid", "ctid") in (select "a"."tableoid", "a"."ctid" from "users" as "a" inner join "users" as "b" on "a"."id" = "b"."user_id" where "email" = ? order by "id" asc limit 1)', ['foo'])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" as "a" where ("tableoid", "ctid") in (select "a"."tableoid", "a"."ctid" from "users" as "a" inner join "users" as "b" on "a"."id" = "b"."user_id" where "email" = ? order by "id" asc limit 1)', ['foo'])->returns(1); $result = $builder->from('users AS a')->join('users AS b', 'a.id', '=', 'b.user_id')->where('email', '=', 'foo')->orderBy('id')->limit(1)->delete(); $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "contacts" on "users"."id" = "contacts"."id" where "users"."id" = ? order by "id" asc limit 1)', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "contacts" on "users"."id" = "contacts"."id" where "users"."id" = ? order by "id" asc limit 1)', [1])->returns(1); $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->orderBy('id')->limit(1)->delete(1); $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "contacts" on "users"."id" = "contacts"."user_id" and "users"."id" = ? where "name" = ?)', [1, 'baz'])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "contacts" on "users"."id" = "contacts"."user_id" and "users"."id" = ? where "name" = ?)', [1, 'baz'])->returns(1); $result = $builder->from('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id') @@ -6131,7 +6128,7 @@ public function testDeleteWithJoinMethod(): void $this->assertEquals(1, $result); $builder = $this->getPostgresBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "contacts" on "users"."id" = "contacts"."id")', [])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where ("tableoid", "ctid") in (select "users"."tableoid", "users"."ctid" from "users" inner join "contacts" on "users"."id" = "contacts"."id")', [])->returns(1); $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->delete(); $this->assertEquals(1, $result); } @@ -6154,7 +6151,7 @@ public function testDeleteWithRawSourceAndLimit(string $database, ?string $alias $builder->getConnection()->expects('delete')->with( 'delete from ' . $source . ' where ' . $rowIdentifier . ' in (select ' . $selection . ' from ' . $source . $join . ' where "active" = ? limit 1)', [1], - )->andReturn(1); + )->returns(1); } $this->assertSame(1, $builder->where('active', 1)->limit(1)->delete()); @@ -6168,7 +6165,9 @@ public function testTruncateMethod(): void $builder->from('users')->truncate(); $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('getSchemaBuilder->parseSchemaAndTable')->andReturn([null, 'users']); + $schemaBuilder = Double::for(SchemaBuilder::class); + $schemaBuilder->expects('parseSchemaAndTable')->returns([null, 'users']); + $builder->getConnection()->expects('getSchemaBuilder')->returns($schemaBuilder); $builder->from('users'); $this->assertEquals([ 'delete from sqlite_sequence where name = ?' => ['users'], @@ -6184,7 +6183,9 @@ public function testTruncateMethodWithPrefix(): void $builder->from('users')->truncate(); $builder = $this->getSQLiteBuilder(prefix: 'prefix_'); - $builder->getConnection()->expects('getSchemaBuilder->parseSchemaAndTable')->andReturn([null, 'users']); + $schemaBuilder = Double::for(SchemaBuilder::class); + $schemaBuilder->expects('parseSchemaAndTable')->returns([null, 'users']); + $builder->getConnection()->expects('getSchemaBuilder')->returns($schemaBuilder); $builder->from('users'); $this->assertEquals([ 'delete from sqlite_sequence where name = ?' => ['prefix_users'], @@ -6200,7 +6201,9 @@ public function testTruncateMethodWithPrefixAndSchema(): void $builder->from('my_schema.users')->truncate(); $builder = $this->getSQLiteBuilder(prefix: 'prefix_'); - $builder->getConnection()->expects('getSchemaBuilder->parseSchemaAndTable')->andReturn(['my_schema', 'users']); + $schemaBuilder = Double::for(SchemaBuilder::class); + $schemaBuilder->expects('parseSchemaAndTable')->returns(['my_schema', 'users']); + $builder->getConnection()->expects('getSchemaBuilder')->returns($schemaBuilder); $builder->from('my_schema.users'); $this->assertEquals([ 'delete from "my_schema".sqlite_sequence where name = ?' => ['prefix_users'], @@ -6208,7 +6211,9 @@ public function testTruncateMethodWithPrefixAndSchema(): void ], $builder->getGrammar()->compileTruncate($builder)); $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('getSchemaBuilder->parseSchemaAndTable')->andReturn(['0', 'users']); + $schemaBuilder = Double::for(SchemaBuilder::class); + $schemaBuilder->expects('parseSchemaAndTable')->returns(['0', 'users']); + $builder->getConnection()->expects('getSchemaBuilder')->returns($schemaBuilder); $builder->from('0.users'); $this->assertSame([ 'delete from "0".sqlite_sequence where name = ?' => ['users'], @@ -6258,7 +6263,7 @@ public function testPreservedAreAppliedByInsert(): void public function testPreservedAreAppliedByInsertGetId(): void { $builder = $this->getBuilder(); - $builder->getProcessor()->expects('processInsertGetId')->with($builder, 'insert into "users" ("email") values (?)', ['foo'], 'id'); + $builder->getProcessor()->expects('processInsertGetId')->with(Argument::same($builder), 'insert into "users" ("email") values (?)', ['foo'], 'id'); $builder->beforeQuery(function (Builder $builder): void { $builder->from('users'); }); @@ -6278,7 +6283,7 @@ public function testPreservedAreAppliedByInsertUsing(): void public function testPreservedAreAppliedByUpsert(): void { $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->andReturn(false); + $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->returns(false); $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`) values (?) on duplicate key update `email` = values(`email`)', ['foo']); $builder->beforeQuery(function (Builder $builder): void { $builder->from('users'); @@ -6286,7 +6291,7 @@ public function testPreservedAreAppliedByUpsert(): void $builder->upsert(['email' => 'foo'], 'id'); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->andReturn(true); + $builder->getConnection()->expects('getConfig')->with('use_upsert_alias')->returns(true); $builder->getConnection()->expects('affectingStatement')->with('insert into `users` (`email`) values (?) as hypervel_upsert_alias on duplicate key update `email` = `hypervel_upsert_alias`.`email`', ['foo']); $builder->beforeQuery(function (Builder $builder): void { $builder->from('users'); @@ -6337,7 +6342,7 @@ public function testPreservedAreAppliedByExists(): void public function testPostgresInsertGetId(): void { $builder = $this->getPostgresBuilder(); - $builder->getProcessor()->expects('processInsertGetId')->with($builder, 'insert into "users" ("email") values (?) returning "id"', ['foo'], 'id')->andReturn(1); + $builder->getProcessor()->expects('processInsertGetId')->with(Argument::same($builder), 'insert into "users" ("email") values (?) returning "id"', ['foo'], 'id')->returns(1); $result = $builder->from('users')->insertGetId(['email' => 'foo'], 'id'); $this->assertEquals(1, $result); } @@ -6396,7 +6401,7 @@ public function testMySqlUpdateWrappingJsonArray(): void ->with( 'update `users` set `options` = ?, `meta` = json_set(`meta`, \'$."tags"\', cast(? as json)), `group_id` = 45, `created_at` = ? where `active` = ?', [ - json_encode(['2fa' => false, 'presets' => ['laravel', 'vue']]), + json_encode(['2fa' => false, 'presets' => ['hypervel', 'vue']]), json_encode(['white', 'large']), new DateTime('2019-08-06'), 1, @@ -6405,7 +6410,7 @@ public function testMySqlUpdateWrappingJsonArray(): void $builder = new Builder($connection, $grammar, $processor); $builder->from('users')->where('active', 1)->update([ - 'options' => ['2fa' => false, 'presets' => ['laravel', 'vue']], + 'options' => ['2fa' => false, 'presets' => ['hypervel', 'vue']], 'meta->tags' => ['white', 'large'], 'group_id' => new Raw('45'), 'created_at' => new DateTime('2019-08-06'), @@ -6488,7 +6493,7 @@ public function testMySqlUpdateWithJsonPreparesBindingsCorrectly(): void $builder->getConnection()->expects('update')->with( 'update `users` inner join (select ? as id) as `source` on `users`.`id` = `source`.`id` inner join `posts` on `posts`.`user_id` = `users`.`id` set `users`.`options` = json_set(`users`.`options`, \'$."a"\', ?, \'$."b"\', ?), `name` = ?, `posts`.`options` = json_set(`posts`.`options`, \'$."c"\', ?) where `active` = ?', [7, 1, 2, 'John', 3, 1], - )->andReturn(1); + )->returns(1); $this->assertSame(1, $builder->from('users') ->joinSub($this->getMySqlBuilder()->selectRaw('? as id', [7]), 'source', 'users.id', '=', 'source.id') @@ -6513,7 +6518,7 @@ public function testPostgresUpdateWrappingJson(): void $builder->getConnection()->expects('update')->with( 'update "users" set "options" = jsonb_set(jsonb_set("options"::jsonb, \'{"a"}\', ?), \'{"b"}\', ?), "name" = ? where "active" = ?', ['1', '2', 'John', 1], - )->andReturn(1); + )->returns(1); $this->assertSame(1, $builder->from('users')->where('active', 1) ->update(['options->a' => 1, 'name' => 'John', 'users.options->b' => 2])); @@ -6524,13 +6529,13 @@ public function testPostgresUpdateWrappingJsonArray(): void $builder = $this->getPostgresBuilder(); $builder->getConnection()->expects('update') ->with('update "users" set "options" = ?, "meta" = jsonb_set("meta"::jsonb, \'{"tags"}\', ?), "group_id" = 45, "created_at" = ?', [ - json_encode(['2fa' => false, 'presets' => ['laravel', 'vue']]), + json_encode(['2fa' => false, 'presets' => ['hypervel', 'vue']]), json_encode(['white', 'large']), new DateTime('2019-08-06'), ]); $builder->from('users')->update([ - 'options' => ['2fa' => false, 'presets' => ['laravel', 'vue']], + 'options' => ['2fa' => false, 'presets' => ['hypervel', 'vue']], 'meta->tags' => ['white', 'large'], 'group_id' => new Raw('45'), 'created_at' => new DateTime('2019-08-06'), @@ -6558,12 +6563,12 @@ public function testSQLiteUpdateWrappingJsonArray(): void $builder->getConnection()->expects('update') ->with('update "users" set "options" = ?, "group_id" = 45, "created_at" = ?', [ - json_encode(['2fa' => false, 'presets' => ['laravel', 'vue']]), + json_encode(['2fa' => false, 'presets' => ['hypervel', 'vue']]), new DateTime('2019-08-06'), ]); $builder->from('users')->update([ - 'options' => ['2fa' => false, 'presets' => ['laravel', 'vue']], + 'options' => ['2fa' => false, 'presets' => ['hypervel', 'vue']], 'group_id' => new Raw('45'), 'created_at' => new DateTime('2019-08-06'), ]); @@ -6575,7 +6580,7 @@ public function testSQLiteUpdateWrappingNestedJsonArray(): void $builder->getConnection()->expects('update') ->with('update "users" set "options" = json_set(ifnull("options", json(\'{}\')), \'$."name"\', json(?), \'$."security"\', json(?), \'$."sharing"."twitter"\', json(?)), "group_id" = 45, "created_at" = ?', [ '"Taylor"', - json_encode(['2fa' => false, 'presets' => ['laravel', 'vue']]), + json_encode(['2fa' => false, 'presets' => ['hypervel', 'vue']]), '"username"', new DateTime('2019-08-06'), ]); @@ -6583,7 +6588,7 @@ public function testSQLiteUpdateWrappingNestedJsonArray(): void $builder->from('users')->update([ 'options->name' => 'Taylor', 'group_id' => new Raw('45'), - 'options->security' => ['2fa' => false, 'presets' => ['laravel', 'vue']], + 'options->security' => ['2fa' => false, 'presets' => ['hypervel', 'vue']], 'options->sharing->twitter' => 'username', 'created_at' => new DateTime('2019-08-06'), ]); @@ -6735,7 +6740,7 @@ public function testPostgresUpdateJsonPathEscaping(): void $builder = $this->getPostgresBuilder(); $builder->getConnection()->expects('update') ->with('update "users" set "options" = jsonb_set("options"::jsonb, \'{"\'\'))#"}\', ?)', ['"John"']) - ->andReturn(1); + ->returns(1); $builder->from('users')->update(["options->'))#" => 'John']); } @@ -6744,7 +6749,7 @@ public function testPostgresUpdateJsonPathEscapesArrayAttributes(): void $builder = $this->getPostgresBuilder(); $builder->getConnection()->expects('update')->with(<<<'SQL' update "users" set "options" = jsonb_set("options"::jsonb, '{"a\\\"b",0}', ?) -SQL, ['"John"'])->andReturn(1); +SQL, ['"John"'])->returns(1); $builder->from('users')->update(['options->a\"b[0]' => 'John']); } @@ -6909,11 +6914,11 @@ public function testDynamicWhere(): void { $method = 'whereFooBarAndBazOrQux'; $parameters = ['corge', 'waldo', 'fred']; - $builder = m::mock(Builder::class)->makePartial(); + $builder = Double::for(Builder::class)->passthru(); - $builder->expects('where')->with('foo_bar', '=', $parameters[0], 'and')->andReturnSelf(); - $builder->expects('where')->with('baz', '=', $parameters[1], 'and')->andReturnSelf(); - $builder->expects('where')->with('qux', '=', $parameters[2], 'or')->andReturnSelf(); + $builder->expects('where')->with('foo_bar', '=', $parameters[0], 'and')->returns($builder); + $builder->expects('where')->with('baz', '=', $parameters[1], 'and')->returns($builder); + $builder->expects('where')->with('qux', '=', $parameters[2], 'or')->returns($builder); $this->assertEquals($builder, $builder->dynamicWhere($method, $parameters)); } @@ -6922,11 +6927,11 @@ public function testDynamicWhereIsNotGreedy(): void { $method = 'whereIosVersionAndAndroidVersionOrOrientation'; $parameters = ['6.1', '4.2', 'Vertical']; - $builder = m::mock(Builder::class)->makePartial(); + $builder = Double::for(Builder::class)->passthru(); - $builder->expects('where')->with('ios_version', '=', '6.1', 'and')->andReturnSelf(); - $builder->expects('where')->with('android_version', '=', '4.2', 'and')->andReturnSelf(); - $builder->expects('where')->with('orientation', '=', 'Vertical', 'or')->andReturnSelf(); + $builder->expects('where')->with('ios_version', '=', '6.1', 'and')->returns($builder); + $builder->expects('where')->with('android_version', '=', '4.2', 'and')->returns($builder); + $builder->expects('where')->with('orientation', '=', 'Vertical', 'or')->returns($builder); $builder->dynamicWhere($method, $parameters); } @@ -6994,10 +6999,10 @@ public function testSkipLockedUsesTheServerLockSyntax( ): void { $builder = $this->{$factory}()->from('jobs'); $connection = $builder->getConnection(); - $connection->shouldReceive('supportsSkipLocked')->andReturn($supported); + $connection->allows('supportsSkipLocked')->returns($supported); if ($isMaria !== null) { - $connection->shouldReceive('isMaria')->andReturn($isMaria); + $connection->allows('isMaria')->returns($isMaria); } $builder->lockForUpdate(); @@ -7047,12 +7052,12 @@ public function testSelectWithLockUsesWritePdo(): void { $builder = $this->getMySqlBuilderWithProcessor(); $builder->getConnection()->expects('select') - ->with(m::any(), m::any(), false, []); + ->with(Argument::any(), Argument::any(), false, []); $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock()->get(); $builder = $this->getMySqlBuilderWithProcessor(); $builder->getConnection()->expects('select') - ->with(m::any(), m::any(), false, []); + ->with(Argument::any(), Argument::any(), false, []); $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false)->get(); } @@ -7284,13 +7289,13 @@ public function testChunkWithLastChunkComplete(): void $chunk2 = collect(['foo3', 'foo4']); $chunk3 = collect([]); - $builder->expects('getOffset')->andReturnNull(); - $builder->expects('getLimit')->andReturnNull(); - $builder->expects('offset')->with(0)->andReturnSelf(); - $builder->expects('offset')->with(2)->andReturnSelf(); - $builder->expects('offset')->with(4)->andReturnSelf(); - $builder->expects('limit')->times(3)->with(2)->andReturnSelf(); - $builder->expects('get')->times(3)->andReturn($chunk1, $chunk2, $chunk3); + $builder->expects('getOffset')->returns(null); + $builder->expects('getLimit')->returns(null); + $builder->expects('offset')->with(0)->returns($builder); + $builder->expects('offset')->with(2)->returns($builder); + $builder->expects('offset')->with(4)->returns($builder); + $builder->expects('limit')->times(3)->with(2)->returns($builder); + $builder->expects('get')->times(3)->returns($chunk1, $chunk2, $chunk3); $seen = []; @@ -7309,12 +7314,12 @@ public function testChunkWithLastChunkPartial(): void $chunk1 = collect(['foo1', 'foo2']); $chunk2 = collect(['foo3']); - $builder->expects('getOffset')->andReturnNull(); - $builder->expects('getLimit')->andReturnNull(); - $builder->expects('offset')->with(0)->andReturnSelf(); - $builder->expects('offset')->with(2)->andReturnSelf(); - $builder->expects('limit')->times(2)->with(2)->andReturnSelf(); - $builder->expects('get')->times(2)->andReturn($chunk1, $chunk2); + $builder->expects('getOffset')->returns(null); + $builder->expects('getLimit')->returns(null); + $builder->expects('offset')->with(0)->returns($builder); + $builder->expects('offset')->with(2)->returns($builder); + $builder->expects('limit')->times(2)->with(2)->returns($builder); + $builder->expects('get')->times(2)->returns($chunk1, $chunk2); $seen = []; @@ -7331,12 +7336,11 @@ public function testChunkCanBeStoppedByReturningFalse(): void $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc']; $chunk1 = collect(['foo1', 'foo2']); - $chunk2 = collect(['foo3']); - $builder->expects('getOffset')->andReturnNull(); - $builder->expects('getLimit')->andReturnNull(); - $builder->expects('offset')->with(0)->andReturnSelf(); - $builder->expects('limit')->with(2)->andReturnSelf(); - $builder->expects('get')->andReturn($chunk1); + $builder->expects('getOffset')->returns(null); + $builder->expects('getLimit')->returns(null); + $builder->expects('offset')->with(0)->returns($builder); + $builder->expects('limit')->with(2)->returns($builder); + $builder->expects('get')->returns($chunk1); $seen = []; @@ -7354,11 +7358,11 @@ public function testChunkWithCountZero(): void $builder = $this->getMockQueryBuilder(); $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc']; - $builder->shouldReceive('getOffset')->never(); - $builder->shouldReceive('getLimit')->never(); - $builder->shouldReceive('offset')->never(); - $builder->shouldReceive('limit')->never(); - $builder->shouldReceive('get')->never(); + $builder->expects('getOffset')->never(); + $builder->expects('getLimit')->never(); + $builder->expects('offset')->never(); + $builder->expects('limit')->never(); + $builder->expects('get')->never(); foreach ([0, -1] as $count) { try { @@ -7380,10 +7384,10 @@ public function testChunkByIdOnArrays(): void $chunk1 = collect([['someIdField' => 1], ['someIdField' => 2]]); $chunk2 = collect([['someIdField' => 10], ['someIdField' => 11]]); $chunk3 = collect([]); - $builder->expects('forPageAfterId')->with(2, 0, 'someIdField')->andReturnSelf(); - $builder->expects('forPageAfterId')->with(2, 2, 'someIdField')->andReturnSelf(); - $builder->expects('forPageAfterId')->with(2, 11, 'someIdField')->andReturnSelf(); - $builder->expects('get')->times(3)->andReturn($chunk1, $chunk2, $chunk3); + $builder->expects('forPageAfterId')->with(2, null, 'someIdField')->returns($builder); + $builder->expects('forPageAfterId')->with(2, 2, 'someIdField')->returns($builder); + $builder->expects('forPageAfterId')->with(2, 11, 'someIdField')->returns($builder); + $builder->expects('get')->times(3)->returns($chunk1, $chunk2, $chunk3); $seen = []; @@ -7402,10 +7406,10 @@ public function testChunkPaginatesUsingIdWithLastChunkComplete(): void $chunk1 = collect([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]); $chunk2 = collect([(object) ['someIdField' => 10], (object) ['someIdField' => 11]]); $chunk3 = collect([]); - $builder->expects('forPageAfterId')->with(2, 0, 'someIdField')->andReturnSelf(); - $builder->expects('forPageAfterId')->with(2, 2, 'someIdField')->andReturnSelf(); - $builder->expects('forPageAfterId')->with(2, 11, 'someIdField')->andReturnSelf(); - $builder->expects('get')->times(3)->andReturn($chunk1, $chunk2, $chunk3); + $builder->expects('forPageAfterId')->with(2, null, 'someIdField')->returns($builder); + $builder->expects('forPageAfterId')->with(2, 2, 'someIdField')->returns($builder); + $builder->expects('forPageAfterId')->with(2, 11, 'someIdField')->returns($builder); + $builder->expects('get')->times(3)->returns($chunk1, $chunk2, $chunk3); $seen = []; @@ -7423,9 +7427,9 @@ public function testChunkPaginatesUsingIdWithLastChunkPartial(): void $chunk1 = collect([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]); $chunk2 = collect([(object) ['someIdField' => 10]]); - $builder->expects('forPageAfterId')->with(2, 0, 'someIdField')->andReturnSelf(); - $builder->expects('forPageAfterId')->with(2, 2, 'someIdField')->andReturnSelf(); - $builder->expects('get')->times(2)->andReturn($chunk1, $chunk2); + $builder->expects('forPageAfterId')->with(2, null, 'someIdField')->returns($builder); + $builder->expects('forPageAfterId')->with(2, 2, 'someIdField')->returns($builder); + $builder->expects('get')->times(2)->returns($chunk1, $chunk2); $seen = []; @@ -7441,10 +7445,10 @@ public function testChunkPaginatesUsingIdWithCountZero(): void $builder = $this->getMockQueryBuilder(); $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc']; - $builder->shouldReceive('getOffset')->never(); - $builder->shouldReceive('getLimit')->never(); - $builder->shouldReceive('forPageAfterId')->never(); - $builder->shouldReceive('get')->never(); + $builder->expects('getOffset')->never(); + $builder->expects('getLimit')->never(); + $builder->expects('forPageAfterId')->never(); + $builder->expects('get')->never(); foreach ([0, -1] as $count) { try { @@ -7465,9 +7469,9 @@ public function testChunkPaginatesUsingIdWithAlias(): void $chunk1 = collect([(object) ['table_id' => 1], (object) ['table_id' => 10]]); $chunk2 = collect([]); - $builder->expects('forPageAfterId')->with(2, 0, 'table.id')->andReturnSelf(); - $builder->expects('forPageAfterId')->with(2, 10, 'table.id')->andReturnSelf(); - $builder->expects('get')->times(2)->andReturn($chunk1, $chunk2); + $builder->expects('forPageAfterId')->with(2, null, 'table.id')->returns($builder); + $builder->expects('forPageAfterId')->with(2, 10, 'table.id')->returns($builder); + $builder->expects('get')->times(2)->returns($chunk1, $chunk2); $seen = []; @@ -7484,16 +7488,17 @@ public function testOrderedChunkByIdAcceptsAscendingSortDirection(): void $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc']; $chunk = collect([(object) ['someIdField' => 1]]); - $builder->expects('forPageAfterId')->with(2, 0, 'someIdField')->andReturnSelf(); - $builder->shouldReceive('forPageBeforeId')->never(); - $builder->expects('get')->andReturn($chunk); + $builder->expects('forPageAfterId')->with(2, null, 'someIdField')->returns($builder); + $builder->expects('forPageBeforeId')->never(); + $builder->expects('get')->returns($chunk); - $callbackAssertor = m::mock(stdClass::class); - $callbackAssertor->expects('doSomething')->with($chunk); + $seen = []; - $builder->orderedChunkById(2, function ($results) use ($callbackAssertor) { - $callbackAssertor->doSomething($results); + $builder->orderedChunkById(2, function (Collection $results) use (&$seen): void { + $seen[] = $results; }, 'someIdField', descending: SortDirection::Ascending); + + $this->assertSame([$chunk], $seen); } public function testChunkPaginatesUsingIdDesc(): void @@ -7503,9 +7508,9 @@ public function testChunkPaginatesUsingIdDesc(): void $chunk1 = collect([(object) ['someIdField' => 10], (object) ['someIdField' => 1]]); $chunk2 = collect([]); - $builder->expects('forPageBeforeId')->with(2, 0, 'someIdField')->andReturnSelf(); - $builder->expects('forPageBeforeId')->with(2, 1, 'someIdField')->andReturnSelf(); - $builder->expects('get')->times(2)->andReturn($chunk1, $chunk2); + $builder->expects('forPageBeforeId')->with(2, null, 'someIdField')->returns($builder); + $builder->expects('forPageBeforeId')->with(2, 1, 'someIdField')->returns($builder); + $builder->expects('get')->times(2)->returns($chunk1, $chunk2); $seen = []; @@ -7522,9 +7527,9 @@ public function testOrderedLazyByIdAcceptsAscendingSortDirection(): void $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc']; $chunk = collect([(object) ['someIdField' => 1]]); - $builder->expects('forPageAfterId')->with(2, null, 'someIdField')->andReturnSelf(); - $builder->shouldReceive('forPageBeforeId')->never(); - $builder->expects('get')->andReturn($chunk); + $builder->expects('forPageAfterId')->with(2, null, 'someIdField')->returns($builder); + $builder->expects('forPageBeforeId')->never(); + $builder->expects('get')->returns($chunk); $method = new ReflectionMethod($builder, 'orderedLazyById'); @@ -7545,9 +7550,9 @@ public function testPaginate(): void $results = collect([['test' => 'foo'], ['test' => 'bar']]); - $builder->expects('getCountForPagination')->andReturn(2); - $builder->expects('forPage')->with($page, $perPage)->andReturnSelf(); - $builder->expects('get')->andReturn($results); + $builder->expects('getCountForPagination')->returns(2); + $builder->expects('forPage')->with($page, $perPage)->returns($builder); + $builder->expects('get')->returns($results); Paginator::currentPathResolver(function () use ($path) { return $path; @@ -7571,9 +7576,9 @@ public function testPaginateWithDefaultArguments(): void $results = collect([['test' => 'foo'], ['test' => 'bar']]); - $builder->expects('getCountForPagination')->andReturn(2); - $builder->expects('forPage')->with($page, $perPage)->andReturnSelf(); - $builder->expects('get')->andReturn($results); + $builder->expects('getCountForPagination')->returns(2); + $builder->expects('forPage')->with($page, $perPage)->returns($builder); + $builder->expects('get')->returns($results); Paginator::currentPageResolver(function () { return 1; @@ -7598,9 +7603,9 @@ public function testPaginateWithExplicitZeroPageDoesNotConsultResolver(): void Paginator::currentPageResolver(fn () => 9); - $builder->expects('getCountForPagination')->andReturn(1); - $builder->expects('forPage')->with(0, 15)->andReturnSelf(); - $builder->expects('get')->andReturn($results); + $builder->expects('getCountForPagination')->returns(1); + $builder->expects('forPage')->with(0, 15)->returns($builder); + $builder->expects('get')->returns($results); $this->assertSame(1, $builder->paginate(page: 0)->currentPage()); } @@ -7611,7 +7616,7 @@ public function testSimplePaginateWithExplicitZeroPageDoesNotConsultResolver(): Paginator::currentPageResolver(fn () => 9); - $builder->expects('get')->andReturn(collect([['test' => 'foo']])); + $builder->expects('get')->returns(collect([['test' => 'foo']])); $this->assertSame(1, $builder->simplePaginate(page: 0)->currentPage()); $this->assertSame(0, $builder->offset); @@ -7627,9 +7632,9 @@ public function testPaginateWhenNoResults(): void $results = []; - $builder->expects('getCountForPagination')->andReturn(0); - $builder->shouldNotReceive('forPage'); - $builder->shouldNotReceive('get'); + $builder->expects('getCountForPagination')->returns(0); + $builder->expects('forPage')->never(); + $builder->expects('get')->never(); Paginator::currentPageResolver(function () { return 1; @@ -7658,9 +7663,9 @@ public function testPaginateWithSpecificColumns(): void $results = collect([['id' => 3, 'name' => 'Taylor'], ['id' => 5, 'name' => 'Mohamed']]); - $builder->expects('getCountForPagination')->andReturn(2); - $builder->expects('forPage')->with($page, $perPage)->andReturnSelf(); - $builder->expects('get')->andReturn($results); + $builder->expects('getCountForPagination')->returns(2); + $builder->expects('forPage')->with($page, $perPage)->returns($builder); + $builder->expects('get')->returns($results); Paginator::currentPathResolver(function () use ($path) { return $path; @@ -7685,9 +7690,9 @@ public function testPaginateWithTotalOverride(): void $results = collect([['id' => 3, 'name' => 'Taylor'], ['id' => 5, 'name' => 'Mohamed']]); - $builder->shouldReceive('getCountForPagination')->never(); - $builder->expects('forPage')->with($page, $perPage)->andReturnSelf(); - $builder->expects('get')->andReturn($results); + $builder->expects('getCountForPagination')->never(); + $builder->expects('forPage')->with($page, $perPage)->returns($builder); + $builder->expects('get')->returns($results); Paginator::currentPathResolver(function () use ($path) { return $path; @@ -7712,14 +7717,14 @@ public function testCursorPaginate(): void $columns = ['test']; $cursorName = 'cursor-name'; $cursor = new Cursor(['test' => 'bar']); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->from('foobar')->orderBy('test'); $path = 'http://foo.bar?cursor=' . $cursor->encode(); $results = collect([['test' => 'foo'], ['test' => 'bar']]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results) { + $builder->onGet(function () use ($builder, $results) { $this->assertSame( 'select * from "foobar" where ("test" > ?) order by "test" asc limit 17', $builder->toSql() @@ -7740,6 +7745,8 @@ public function testCursorPaginate(): void 'cursorName' => $cursorName, 'parameters' => ['test'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateMultipleOrderColumns(): void @@ -7748,14 +7755,14 @@ public function testCursorPaginateMultipleOrderColumns(): void $columns = ['test', 'another']; $cursorName = 'cursor-name'; $cursor = new Cursor(['test' => 'bar', 'another' => 'foo']); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->from('foobar')->orderBy('test')->orderBy('another'); $path = 'http://foo.bar?cursor=' . $cursor->encode(); $results = collect([['test' => 'foo', 'another' => 1], ['test' => 'bar', 'another' => 2]]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results) { + $builder->onGet(function () use ($builder, $results) { $this->assertSame( 'select * from "foobar" where ("test" > ? or ("test" = ? and ("another" > ?))) order by "test" asc, "another" asc limit 17', $builder->toSql() @@ -7776,6 +7783,8 @@ public function testCursorPaginateMultipleOrderColumns(): void 'cursorName' => $cursorName, 'parameters' => ['test', 'another'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWrapsOrderColumnsContainingParentheses(): void @@ -7785,14 +7794,14 @@ public function testCursorPaginateWrapsOrderColumnsContainingParentheses(): void $cursorName = 'cursor-name'; $column = 'id) or 1=1 or (id'; $cursor = new Cursor([$column => 'bar', 'id' => 'foo']); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->from('foobar')->orderBy($column)->orderBy('id'); $path = 'http://foo.bar?cursor=' . $cursor->encode(); $results = collect([['id' => 1], ['id' => 2]]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results): Collection { + $builder->onGet(function () use ($builder, $results): Collection { $this->assertSame( 'select * from "foobar" where ("id) or 1=1 or (id" > ? or ("id) or 1=1 or (id" = ? and ("id" > ?))) order by "id) or 1=1 or (id" asc, "id" asc limit 17', $builder->toSql() @@ -7807,6 +7816,8 @@ public function testCursorPaginateWrapsOrderColumnsContainingParentheses(): void }); $builder->cursorPaginate($perPage, $columns, $cursorName, $cursor); + + $this->assertSame(1, $builder->getCalls); } public function testKeysetIsolationDiscardsUnneededInnerOrdering(): void @@ -7842,14 +7853,14 @@ public function testCursorPaginateWithDefaultArguments(): void $perPage = 15; $cursorName = 'cursor'; $cursor = new Cursor(['test' => 'bar']); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->from('foobar')->orderBy('test'); $path = 'http://foo.bar?cursor=' . $cursor->encode(); $results = collect([['test' => 'foo'], ['test' => 'bar']]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results) { + $builder->onGet(function () use ($builder, $results) { $this->assertSame( 'select * from "foobar" where ("test" > ?) order by "test" asc limit 16', $builder->toSql() @@ -7874,6 +7885,8 @@ public function testCursorPaginateWithDefaultArguments(): void 'cursorName' => $cursorName, 'parameters' => ['test'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWhenNoResults(): void @@ -7885,7 +7898,7 @@ public function testCursorPaginateWhenNoResults(): void $results = []; - $builder->expects('get')->andReturn(new Collection($results)); + $builder->expects('get')->returns(new Collection($results)); CursorPaginator::currentCursorResolver(function () { return null; @@ -7910,14 +7923,14 @@ public function testCursorPaginateWithSpecificColumns(): void $columns = ['id', 'name']; $cursorName = 'cursor-name'; $cursor = new Cursor(['id' => 2]); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->from('foobar')->orderBy('id'); $path = 'http://foo.bar?cursor=3'; $results = collect([['id' => 3, 'name' => 'Taylor'], ['id' => 5, 'name' => 'Mohamed']]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results) { + $builder->onGet(function () use ($builder, $results) { $this->assertSame( 'select * from "foobar" where ("id" > ?) order by "id" asc limit 17', $builder->toSql() @@ -7938,6 +7951,8 @@ public function testCursorPaginateWithSpecificColumns(): void 'cursorName' => $cursorName, 'parameters' => ['id'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithMixedOrders(): void @@ -7946,14 +7961,14 @@ public function testCursorPaginateWithMixedOrders(): void $columns = ['foo', 'bar', 'baz']; $cursorName = 'cursor-name'; $cursor = new Cursor(['foo' => 1, 'bar' => 2, 'baz' => 3]); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->from('foobar')->orderBy('foo')->orderByDesc('bar')->orderBy('baz'); $path = 'http://foo.bar?cursor=' . $cursor->encode(); $results = collect([['foo' => 1, 'bar' => 2, 'baz' => 4], ['foo' => 1, 'bar' => 1, 'baz' => 1]]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results) { + $builder->onGet(function () use ($builder, $results) { $this->assertSame( 'select * from "foobar" where ("foo" > ? or ("foo" = ? and ("bar" < ? or ("bar" = ? and ("baz" > ?))))) order by "foo" asc, "bar" desc, "baz" asc limit 17', $builder->toSql() @@ -7974,6 +7989,8 @@ public function testCursorPaginateWithMixedOrders(): void 'cursorName' => $cursorName, 'parameters' => ['foo', 'bar', 'baz'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithDynamicColumnInSelectRaw(): void @@ -7981,14 +7998,14 @@ public function testCursorPaginateWithDynamicColumnInSelectRaw(): void $perPage = 15; $cursorName = 'cursor'; $cursor = new Cursor(['test' => 'bar']); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->from('foobar')->select('*')->selectRaw('(CONCAT(firstname, \' \', lastname)) as test')->orderBy('test'); $path = 'http://foo.bar?cursor=' . $cursor->encode(); $results = collect([['test' => 'foo'], ['test' => 'bar']]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results) { + $builder->onGet(function () use ($builder, $results) { $this->assertSame( 'select *, (CONCAT(firstname, \' \', lastname)) as test from "foobar" where ((CONCAT(firstname, \' \', lastname)) > ?) order by "test" asc limit 16', $builder->toSql() @@ -8013,6 +8030,8 @@ public function testCursorPaginateWithDynamicColumnInSelectRaw(): void 'cursorName' => $cursorName, 'parameters' => ['test'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithDynamicColumnWithCastInSelectRaw(): void @@ -8020,14 +8039,14 @@ public function testCursorPaginateWithDynamicColumnWithCastInSelectRaw(): void $perPage = 15; $cursorName = 'cursor'; $cursor = new Cursor(['test' => 'bar']); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->from('foobar')->select('*')->selectRaw('(CAST(CONCAT(firstname, \' \', lastname) as VARCHAR)) as test')->orderBy('test'); $path = 'http://foo.bar?cursor=' . $cursor->encode(); $results = collect([['test' => 'foo'], ['test' => 'bar']]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results) { + $builder->onGet(function () use ($builder, $results) { $this->assertSame( 'select *, (CAST(CONCAT(firstname, \' \', lastname) as VARCHAR)) as test from "foobar" where ((CAST(CONCAT(firstname, \' \', lastname) as VARCHAR)) > ?) order by "test" asc limit 16', $builder->toSql() @@ -8052,6 +8071,8 @@ public function testCursorPaginateWithDynamicColumnWithCastInSelectRaw(): void 'cursorName' => $cursorName, 'parameters' => ['test'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithDynamicColumnInSelectSub(): void @@ -8059,14 +8080,14 @@ public function testCursorPaginateWithDynamicColumnInSelectSub(): void $perPage = 15; $cursorName = 'cursor'; $cursor = new Cursor(['test' => 'bar']); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->from('foobar')->select('*')->selectSub('CONCAT(firstname, \' \', lastname)', 'test')->orderBy('test'); $path = 'http://foo.bar?cursor=' . $cursor->encode(); $results = collect([['test' => 'foo'], ['test' => 'bar']]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results) { + $builder->onGet(function () use ($builder, $results) { $this->assertSame( 'select *, (CONCAT(firstname, \' \', lastname)) as "test" from "foobar" where ((CONCAT(firstname, \' \', lastname)) > ?) order by "test" asc limit 16', $builder->toSql() @@ -8091,6 +8112,8 @@ public function testCursorPaginateWithDynamicColumnInSelectSub(): void 'cursorName' => $cursorName, 'parameters' => ['test'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithUnionWheres(): void @@ -8101,7 +8124,7 @@ public function testCursorPaginateWithUnionWheres(): void $columns = ['test']; $cursorName = 'cursor-name'; $cursor = new Cursor(['created_at' => $ts]); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->select('id', 'start_time as created_at')->selectRaw("'video' as type")->from('videos'); $builder->union($this->getBuilder()->select('id', 'created_at')->selectRaw("'news' as type")->from('news')); $builder->orderBy('created_at'); @@ -8113,7 +8136,7 @@ public function testCursorPaginateWithUnionWheres(): void ['id' => 2, 'created_at' => now(), 'type' => 'news'], ]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results, $ts) { + $builder->onGet(function () use ($builder, $results, $ts) { $this->assertSame( '(select "id", "start_time" as "created_at", \'video\' as type from "videos" where ("start_time" > ?)) union (select "id", "created_at", \'news\' as type from "news" where ("created_at" > ?)) order by "created_at" asc limit 17', $builder->toSql() @@ -8136,16 +8159,18 @@ public function testCursorPaginateWithUnionWheres(): void 'cursorName' => $cursorName, 'parameters' => ['created_at'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateFiltersNestedUnionsAndRebuildsTheirBindings(): void { - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->select('id')->from('videos')->where('active', 1) ->unionAll($this->getBuilder()->select('id')->from('news')->where('active', 2) ->unionAll($this->getBuilder()->select('id')->from('archives')->where('active', 3))) ->orderBy('id'); - $builder->expects('get')->andReturnUsing(function () use ($builder): Collection { + $builder->onGet(function () use ($builder): Collection { $this->assertSame( '(select "id" from "videos" where "active" = ? and ("id" > ?)) union all ((select "id" from "news" where "active" = ? and ("id" > ?)) union all (select "id" from "archives" where "active" = ? and ("id" > ?))) order by "id" asc limit 11', $builder->toSql() @@ -8155,6 +8180,8 @@ public function testCursorPaginateFiltersNestedUnionsAndRebuildsTheirBindings(): return new Collection; }); $builder->cursorPaginate(10, cursor: new Cursor(['id' => 2])); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithUnionSelectAndJoinBindings(): void @@ -8164,7 +8191,7 @@ public function testCursorPaginateWithUnionSelectAndJoinBindings(): void $columns = ['test']; $cursorName = 'cursor-name'; $cursor = new Cursor(['created_at' => $timestamp]); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->select('id', 'created_at')->selectRaw('? as type', ['video'])->from('videos'); $builder->union($this->getBuilder()->select('id', 'created_at')->selectRaw('? as type', ['news'])->from('news')->join('authors', function (JoinClause $join): void { $join->on('authors.id', '=', 'news.author_id')->where('authors.active', true); @@ -8175,7 +8202,7 @@ public function testCursorPaginateWithUnionSelectAndJoinBindings(): void ['id' => 1, 'created_at' => now(), 'type' => 'video'], ['id' => 2, 'created_at' => now(), 'type' => 'news'], ]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results, $timestamp): Collection { + $builder->onGet(function () use ($builder, $results, $timestamp): Collection { $this->assertSame( '(select "id", "created_at", ? as type from "videos" where ("created_at" > ?)) union (select "id", "created_at", ? as type from "news" inner join "authors" on "authors"."id" = "news"."author_id" and "authors"."active" = ? where ("created_at" > ?)) order by "created_at" asc limit 17', $builder->toSql() @@ -8193,6 +8220,8 @@ public function testCursorPaginateWithUnionSelectAndJoinBindings(): void 'cursorName' => $cursorName, 'parameters' => ['created_at'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithMultipleUnionsAndMultipleWheres(): void @@ -8203,7 +8232,7 @@ public function testCursorPaginateWithMultipleUnionsAndMultipleWheres(): void $columns = ['test']; $cursorName = 'cursor-name'; $cursor = new Cursor(['created_at' => $ts]); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->select('id', 'start_time as created_at')->selectRaw("'video' as type")->from('videos'); $builder->union($this->getBuilder()->select('id', 'created_at')->selectRaw("'news' as type")->from('news')->where('extra', 'first')); $builder->union($this->getBuilder()->select('id', 'created_at')->selectRaw("'podcast' as type")->from('podcasts')->where('extra', 'second')); @@ -8217,7 +8246,7 @@ public function testCursorPaginateWithMultipleUnionsAndMultipleWheres(): void ['id' => 3, 'created_at' => now(), 'type' => 'podcasts'], ]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results, $ts) { + $builder->onGet(function () use ($builder, $results, $ts) { $this->assertSame( '(select "id", "start_time" as "created_at", \'video\' as type from "videos" where ("start_time" > ?)) union (select "id", "created_at", \'news\' as type from "news" where "extra" = ? and ("created_at" > ?)) union (select "id", "created_at", \'podcast\' as type from "podcasts" where "extra" = ? and ("created_at" > ?)) order by "created_at" asc limit 17', $builder->toSql() @@ -8239,6 +8268,8 @@ public function testCursorPaginateWithMultipleUnionsAndMultipleWheres(): void 'cursorName' => $cursorName, 'parameters' => ['created_at'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithUnionMultipleWheresMultipleOrders(): void @@ -8249,7 +8280,7 @@ public function testCursorPaginateWithUnionMultipleWheresMultipleOrders(): void $columns = ['id', 'created_at', 'type']; $cursorName = 'cursor-name'; $cursor = new Cursor(['id' => 1, 'created_at' => $ts, 'type' => 'news']); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->select('id', 'start_time as created_at', 'type')->from('videos')->where('extra', 'first'); $builder->union($this->getBuilder()->select('id', 'created_at', 'type')->from('news')->where('extra', 'second')); $builder->union($this->getBuilder()->select('id', 'created_at', 'type')->from('podcasts')->where('extra', 'third')); @@ -8264,7 +8295,7 @@ public function testCursorPaginateWithUnionMultipleWheresMultipleOrders(): void ['id' => 2, 'created_at' => now(), 'type' => 'podcast'], ]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results, $ts) { + $builder->onGet(function () use ($builder, $results, $ts) { $this->assertSame( '(select "id", "start_time" as "created_at", "type" from "videos" where "extra" = ? and ("id" > ? or ("id" = ? and ("start_time" < ? or ("start_time" = ? and ("type" > ?)))))) union (select "id", "created_at", "type" from "news" where "extra" = ? and ("id" > ? or ("id" = ? and ("created_at" < ? or ("created_at" = ? and ("type" > ?)))))) union (select "id", "created_at", "type" from "podcasts" where "extra" = ? and ("id" > ? or ("id" = ? and ("created_at" < ? or ("created_at" = ? and ("type" > ?)))))) order by "id" asc, "created_at" desc, "type" asc limit 17', $builder->toSql() @@ -8286,6 +8317,8 @@ public function testCursorPaginateWithUnionMultipleWheresMultipleOrders(): void 'cursorName' => $cursorName, 'parameters' => ['id', 'created_at', 'type'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithUnionWheresWithRawOrderExpression(): void @@ -8296,7 +8329,7 @@ public function testCursorPaginateWithUnionWheresWithRawOrderExpression(): void $columns = ['test']; $cursorName = 'cursor-name'; $cursor = new Cursor(['created_at' => $ts]); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->select('id', 'is_published', 'start_time as created_at')->selectRaw("'video' as type")->where('is_published', true)->from('videos'); $builder->union($this->getBuilder()->select('id', 'is_published', 'created_at')->selectRaw("'news' as type")->where('is_published', true)->from('news')); $builder->orderByRaw('case when (id = 3 and type="news" then 0 else 1 end)')->orderBy('created_at'); @@ -8308,7 +8341,7 @@ public function testCursorPaginateWithUnionWheresWithRawOrderExpression(): void ['id' => 2, 'created_at' => now(), 'type' => 'news', 'is_published' => true], ]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results, $ts) { + $builder->onGet(function () use ($builder, $results, $ts) { $this->assertSame( '(select "id", "is_published", "start_time" as "created_at", \'video\' as type from "videos" where "is_published" = ? and ("start_time" > ?)) union (select "id", "is_published", "created_at", \'news\' as type from "news" where "is_published" = ? and ("created_at" > ?)) order by case when (id = 3 and type="news" then 0 else 1 end), "created_at" asc limit 17', $builder->toSql() @@ -8330,6 +8363,8 @@ public function testCursorPaginateWithUnionWheresWithRawOrderExpression(): void 'cursorName' => $cursorName, 'parameters' => ['created_at'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithUnionWheresReverseOrder(): void @@ -8340,7 +8375,7 @@ public function testCursorPaginateWithUnionWheresReverseOrder(): void $columns = ['test']; $cursorName = 'cursor-name'; $cursor = new Cursor(['created_at' => $ts], false); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->select('id', 'start_time as created_at')->selectRaw("'video' as type")->from('videos'); $builder->union($this->getBuilder()->select('id', 'created_at')->selectRaw("'news' as type")->from('news')); $builder->orderBy('created_at'); @@ -8352,7 +8387,7 @@ public function testCursorPaginateWithUnionWheresReverseOrder(): void ['id' => 2, 'created_at' => now(), 'type' => 'news'], ]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results, $ts) { + $builder->onGet(function () use ($builder, $results, $ts) { $this->assertSame( '(select "id", "start_time" as "created_at", \'video\' as type from "videos" where ("start_time" < ?)) union (select "id", "created_at", \'news\' as type from "news" where ("created_at" < ?)) order by "created_at" desc limit 17', $builder->toSql() @@ -8374,6 +8409,8 @@ public function testCursorPaginateWithUnionWheresReverseOrder(): void 'cursorName' => $cursorName, 'parameters' => ['created_at'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithUnionWheresMultipleOrders(): void @@ -8384,7 +8421,7 @@ public function testCursorPaginateWithUnionWheresMultipleOrders(): void $columns = ['test']; $cursorName = 'cursor-name'; $cursor = new Cursor(['created_at' => $ts, 'id' => 1]); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->select('id', 'start_time as created_at')->selectRaw("'video' as type")->from('videos'); $builder->union($this->getBuilder()->select('id', 'created_at')->selectRaw("'news' as type")->from('news')); $builder->orderByDesc('created_at')->orderBy('id'); @@ -8396,7 +8433,7 @@ public function testCursorPaginateWithUnionWheresMultipleOrders(): void ['id' => 2, 'created_at' => now(), 'type' => 'news'], ]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results, $ts) { + $builder->onGet(function () use ($builder, $results, $ts) { $this->assertSame( '(select "id", "start_time" as "created_at", \'video\' as type from "videos" where ("start_time" < ? or ("start_time" = ? and ("id" > ?)))) union (select "id", "created_at", \'news\' as type from "news" where ("created_at" < ? or ("created_at" = ? and ("id" > ?)))) order by "created_at" desc, "id" asc limit 17', $builder->toSql() @@ -8418,6 +8455,8 @@ public function testCursorPaginateWithUnionWheresMultipleOrders(): void 'cursorName' => $cursorName, 'parameters' => ['created_at', 'id'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testCursorPaginateWithUnionWheresAndAliassedOrderColumns(): void @@ -8428,7 +8467,7 @@ public function testCursorPaginateWithUnionWheresAndAliassedOrderColumns(): void $columns = ['test']; $cursorName = 'cursor-name'; $cursor = new Cursor(['created_at' => $ts]); - $builder = $this->getMockQueryBuilder(['get']); + $builder = $this->getQueryBuilderWithCapturedGet(); $builder->select('id', 'start_time as created_at')->selectRaw("'video' as type")->from('videos'); $builder->union($this->getBuilder()->select('id', 'created_at')->selectRaw("'news' as type")->from('news')); $builder->union($this->getBuilder()->select('id', 'init_at as created_at')->selectRaw("'podcast' as type")->from('podcasts')); @@ -8442,7 +8481,7 @@ public function testCursorPaginateWithUnionWheresAndAliassedOrderColumns(): void ['id' => 3, 'created_at' => now(), 'type' => 'podcast'], ]); - $builder->expects('get')->andReturnUsing(function () use ($builder, $results, $ts) { + $builder->onGet(function () use ($builder, $results, $ts) { $this->assertSame( '(select "id", "start_time" as "created_at", \'video\' as type from "videos" where ("start_time" > ?)) union (select "id", "created_at", \'news\' as type from "news" where ("created_at" > ?)) union (select "id", "init_at" as "created_at", \'podcast\' as type from "podcasts" where ("init_at" > ?)) order by "created_at" asc limit 17', $builder->toSql() @@ -8464,6 +8503,8 @@ public function testCursorPaginateWithUnionWheresAndAliassedOrderColumns(): void 'cursorName' => $cursorName, 'parameters' => ['created_at'], ]), $result); + + $this->assertSame(1, $builder->getCalls); } public function testWhereExpression(): void @@ -8471,7 +8512,7 @@ public function testWhereExpression(): void $builder = $this->getBuilder(); $builder->select('*')->from('orders')->where( new class implements ConditionExpression { - public function getValue(\Hypervel\Database\Grammar $grammar): string|int|float + public function getValue(BaseGrammar $grammar): string|int|float { return '1 = 1'; } @@ -8948,27 +8989,27 @@ public function testIgnoreIndexMySql(): void public function testIndexHintsOnMySqlUpdates(): void { $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('update')->with('update `users` use index (test_index) set `email` = ? where `id` = ?', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update `users` use index (test_index) set `email` = ? where `id` = ?', ['foo', 1])->returns(1); $this->assertSame(1, $builder->from('users')->useIndex('test_index')->where('id', 1)->update(['email' => 'foo'])); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('update')->with('update `users` ignore index (test_index) set `email` = ? where `id` = ?', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update `users` ignore index (test_index) set `email` = ? where `id` = ?', ['foo', 1])->returns(1); $this->assertSame(1, $builder->from('users')->ignoreIndex('test_index')->where('id', 1)->update(['email' => 'foo'])); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('update')->with('update `users` force index (primary) set `email` = ? where `id` in (?, ?) order by `id` asc limit 2', ['foo', 1, 2])->andReturn(2); + $builder->getConnection()->expects('update')->with('update `users` force index (primary) set `email` = ? where `id` in (?, ?) order by `id` asc limit 2', ['foo', 1, 2])->returns(2); $this->assertSame(2, $builder->from('users')->forceIndex('primary')->whereIn('id', [1, 2])->orderBy('id')->limit(2)->update(['email' => 'foo'])); $builder = $this->getMySqlBuilder(prefix: 'prefix_'); - $builder->getConnection()->expects('update')->with('update `prefix_users` as `prefix_u` force index (primary) set `email` = ? where `prefix_u`.`id` = ?', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update `prefix_users` as `prefix_u` force index (primary) set `email` = ? where `prefix_u`.`id` = ?', ['foo', 1])->returns(1); $this->assertSame(1, $builder->from('users as u')->forceIndex('primary')->where('u.id', 1)->update(['email' => 'foo'])); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('update')->with('update `users` force index (primary) inner join `orders` on `users`.`id` = `orders`.`user_id` set `email` = ? where `users`.`id` = ?', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update `users` force index (primary) inner join `orders` on `users`.`id` = `orders`.`user_id` set `email` = ? where `users`.`id` = ?', ['foo', 1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('primary')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', 1)->update(['email' => 'foo'])); $builder = $this->getMariaDbBuilder(); - $builder->getConnection()->expects('update')->with('update `users` force index (primary) set `email` = ? where `id` = ?', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update `users` force index (primary) set `email` = ? where `id` = ?', ['foo', 1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('primary')->where('id', 1)->update(['email' => 'foo'])); } @@ -8976,30 +9017,30 @@ public function testIndexHintsOnMySqlDeletes(): void { foreach (['useIndex' => 'use', 'forceIndex' => 'force', 'ignoreIndex' => 'ignore'] as $method => $hint) { $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('delete')->with("delete `users` from `users` {$hint} index (test_index) where `id` = ?", [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with("delete `users` from `users` {$hint} index (test_index) where `id` = ?", [1])->returns(1); $this->assertSame(1, $builder->from('users')->{$method}('test_index')->where('id', 1)->delete()); } $builder = $this->getMySqlBuilder(prefix: 'prefix_'); - $builder->getConnection()->expects('delete')->with('delete `prefix_u` from `prefix_users` as `prefix_u` force index (primary) where `prefix_u`.`id` = ?', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete `prefix_u` from `prefix_users` as `prefix_u` force index (primary) where `prefix_u`.`id` = ?', [1])->returns(1); $this->assertSame(1, $builder->from('users as u')->forceIndex('primary')->where('u.id', 1)->delete()); $builder = $this->getMySqlBuilder(prefix: 'prefix_'); - $builder->getConnection()->expects('delete')->with('delete `prefix_u` from `prefix_users` as `prefix_u` force index (primary) inner join `prefix_orders` on `prefix_u`.`id` = `prefix_orders`.`user_id` and `prefix_orders`.`status` = ? where `prefix_u`.`id` = ?', ['paid', 1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete `prefix_u` from `prefix_users` as `prefix_u` force index (primary) inner join `prefix_orders` on `prefix_u`.`id` = `prefix_orders`.`user_id` and `prefix_orders`.`status` = ? where `prefix_u`.`id` = ?', ['paid', 1])->returns(1); $this->assertSame(1, $builder->from('users as u')->forceIndex('primary')->join('orders', static function (JoinClause $join): void { $join->on('u.id', '=', 'orders.user_id')->where('orders.status', 'paid'); })->where('u.id', 1)->delete()); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('delete')->with('delete from `users` where `id` = ? order by `id` asc', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from `users` where `id` = ? order by `id` asc', [1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('primary')->where('id', 1)->orderBy('id')->delete()); $builder = $this->getMySqlBuilder(); - $builder->getConnection()->expects('delete')->with('delete from `users` where `id` = ? limit 1', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from `users` where `id` = ? limit 1', [1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('primary')->where('id', 1)->limit(1)->delete()); $builder = $this->getMariaDbBuilder(); - $builder->getConnection()->expects('delete')->with('delete `users` from `users` force index (primary) where `id` = ?', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete `users` from `users` force index (primary) where `id` = ?', [1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('primary')->where('id', 1)->delete()); } @@ -9050,22 +9091,22 @@ public function testIgnoreIndexSqlite(): void public function testIndexHintsOnSqliteUpdates(): void { $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('update')->with('update "users" indexed by test_index set "email" = ? where "id" = ?', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" indexed by test_index set "email" = ? where "id" = ?', ['foo', 1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('test_index')->where('id', 1)->update(['email' => 'foo'])); // SQLite has no other hints, so they leave an update as it is. $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ? where "id" = ?', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ? where "id" = ?', ['foo', 1])->returns(1); $this->assertSame(1, $builder->from('users')->useIndex('test_index')->where('id', 1)->update(['email' => 'foo'])); // A limited update selects its rows in a subquery, which takes the hint. $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ? where "rowid" in (select "users"."rowid" from "users" indexed by test_index where "id" > ? order by "id" asc limit 3)', ['foo', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ? where "rowid" in (select "users"."rowid" from "users" indexed by test_index where "id" > ? order by "id" asc limit 3)', ['foo', 1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('test_index')->where('id', '>', 1)->orderBy('id')->limit(3)->update(['email' => 'foo'])); // So does a joined update, whose join bindings come before its where bindings. $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('update')->with('update "users" set "email" = ? where "rowid" in (select "users"."rowid" from "users" indexed by test_index inner join "orders" on "users"."id" = "orders"."user_id" and "orders"."status" = ? where "users"."id" = ?)', ['foo', 'paid', 1])->andReturn(1); + $builder->getConnection()->expects('update')->with('update "users" set "email" = ? where "rowid" in (select "users"."rowid" from "users" indexed by test_index inner join "orders" on "users"."id" = "orders"."user_id" and "orders"."status" = ? where "users"."id" = ?)', ['foo', 'paid', 1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('test_index')->join('orders', static function (JoinClause $join): void { $join->on('users.id', '=', 'orders.user_id')->where('orders.status', '=', 'paid'); })->where('users.id', 1)->update(['email' => 'foo'])); @@ -9074,21 +9115,21 @@ public function testIndexHintsOnSqliteUpdates(): void public function testIndexHintsOnSqliteDeletes(): void { $builder = $this->getSQLiteBuilder(prefix: 'prefix_'); - $builder->getConnection()->expects('delete')->with('delete from "prefix_users" as "prefix_u" indexed by test_index where "prefix_u"."id" = ?', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "prefix_users" as "prefix_u" indexed by test_index where "prefix_u"."id" = ?', [1])->returns(1); $this->assertSame(1, $builder->from('users as u')->forceIndex('test_index')->where('u.id', 1)->delete()); foreach (['useIndex', 'ignoreIndex'] as $method) { $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where "id" = ?', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where "id" = ?', [1])->returns(1); $this->assertSame(1, $builder->from('users')->{$method}('test_index')->where('id', 1)->delete()); } $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" indexed by test_index where "id" > ? order by "id" asc limit 3)', [1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" indexed by test_index where "id" > ? order by "id" asc limit 3)', [1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('test_index')->where('id', '>', 1)->orderBy('id')->limit(3)->delete()); $builder = $this->getSQLiteBuilder(); - $builder->getConnection()->expects('delete')->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" indexed by test_index inner join "orders" on "users"."id" = "orders"."user_id" and "orders"."status" = ? where "users"."id" = ?)', ['paid', 1])->andReturn(1); + $builder->getConnection()->expects('delete')->with('delete from "users" where "rowid" in (select "users"."rowid" from "users" indexed by test_index inner join "orders" on "users"."id" = "orders"."user_id" and "orders"."status" = ? where "users"."id" = ?)', ['paid', 1])->returns(1); $this->assertSame(1, $builder->from('users')->forceIndex('test_index')->join('orders', static function (JoinClause $join): void { $join->on('users.id', '=', 'orders.user_id')->where('orders.status', 'paid'); })->where('users.id', 1)->delete()); @@ -9274,11 +9315,11 @@ public function testToRawSql(): void $connection = $this->getConnection(); $connection->expects('prepareBindings') ->with(['foo']) - ->andReturn(['foo']); - $grammar = m::mock(Grammar::class, [$connection])->makePartial(); + ->returns(['foo']); + $grammar = Double::for(new Grammar($connection))->passthru(); $grammar->expects('substituteBindingsIntoRawSql') ->with('select * from "users" where "email" = ?', ['foo']) - ->andReturn('select * from "users" where "email" = \'foo\''); + ->returns('select * from "users" where "email" = \'foo\''); $builder = new Builder($connection, $grammar, new Processor); $builder->select('*')->from('users')->where('email', 'foo'); @@ -9290,15 +9331,14 @@ public function testToRawSql(): void * * @param class-string $connectionClass */ - protected function getConnection(string $prefix = '', string $connectionClass = Connection::class): Connection&m\MockInterface + protected function getConnection(string $prefix = '', string $connectionClass = Connection::class): Connection&DoubleInterface { - $connection = m::mock($connectionClass); - $connection->shouldReceive('getDatabaseName')->andReturn('database'); - $connection->shouldReceive('getTablePrefix')->andReturn($prefix); + $connection = Double::for($connectionClass); + $connection->allows('getDatabaseName')->returns('database'); + $connection->allows('getTablePrefix')->returns($prefix); if ($connection instanceof MySqlConnection) { - $connection->shouldReceive('usesBackslashEscapes')->passthru(); - $connection->shouldReceive('getConfig')->with('modes')->andReturn(null); + $connection->allows('usesBackslashEscapes')->returns(true); } return $connection; @@ -9311,14 +9351,14 @@ protected function getConnection(string $prefix = '', string $connectionClass = */ protected function getRelationSubquery(string $database = 'database', string $grammarClass = Grammar::class): HasMany { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getDatabaseName')->andReturn($database); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getDatabaseName')->returns($database); + $connection->allows('getTablePrefix')->returns(''); $query = new EloquentBuilder(new Builder( $connection, new $grammarClass($connection), - m::mock(Processor::class), + Double::for(Processor::class), )); $query->setModel(new QueryableSubqueryRelatedModel); @@ -9404,7 +9444,7 @@ protected function getBuilder(string $prefix = ''): Builder { $connection = $this->getConnection(prefix: $prefix); $grammar = new Grammar($connection); - $processor = m::mock(Processor::class); + $processor = Double::for(Processor::class); return new Builder($connection, $grammar, $processor); } @@ -9416,7 +9456,7 @@ protected function getPostgresBuilder(string $prefix = ''): Builder { $connection = $this->getConnection(prefix: $prefix); $grammar = new PostgresGrammar($connection); - $processor = m::mock(Processor::class); + $processor = Double::for(Processor::class); return new Builder($connection, $grammar, $processor); } @@ -9428,7 +9468,7 @@ protected function getMySqlBuilder(string $prefix = ''): Builder { $connection = $this->getConnection(prefix: $prefix, connectionClass: MySqlConnection::class); $grammar = new MySqlGrammar($connection); - $processor = m::mock(Processor::class); + $processor = Double::for(Processor::class); return new Builder($connection, $grammar, $processor); } @@ -9440,7 +9480,7 @@ protected function getMariaDbBuilder(string $prefix = ''): Builder { $connection = $this->getConnection(prefix: $prefix, connectionClass: MariaDbConnection::class); $grammar = new MariaDbGrammar($connection); - $processor = m::mock(Processor::class); + $processor = Double::for(Processor::class); return new Builder($connection, $grammar, $processor); } @@ -9452,7 +9492,7 @@ protected function getSQLiteBuilder(string $prefix = ''): Builder { $connection = $this->getConnection(prefix: $prefix); $grammar = new SQLiteGrammar($connection); - $processor = m::mock(Processor::class); + $processor = Double::for(Processor::class); return new Builder($connection, $grammar, $processor); } @@ -9481,18 +9521,54 @@ protected function getPostgresBuilderWithProcessor(string $prefix = ''): Builder return new Builder($connection, $grammar, $processor); } + /** + * Create a real builder whose query execution can be inspected. + */ + protected function getQueryBuilderWithCapturedGet(): QueryBuilderTestGetStub + { + // Nested queries use new static, which must construct an initialized builder. + return new QueryBuilderTestGetStub( + $connection = $this->getConnection(), + new Grammar($connection), + new Processor, + ); + } + /** * Create a partially mocked query builder. - * - * @param list $methods */ - protected function getMockQueryBuilder(array $methods = []): Builder&m\MockInterface + protected function getMockQueryBuilder(): Builder&DoubleInterface { - return m::mock(Builder::class . ($methods ? '[' . implode(',', $methods) . ']' : ''), [ + return Double::for(new Builder( $connection = $this->getConnection(), new Grammar($connection), new Processor, - ])->makePartial(); + ))->passthru(); + } +} + +class QueryBuilderTestGetStub extends Builder +{ + protected Closure $getCallback; + + public int $getCalls = 0; + + /** + * Set the callback that inspects query execution. + */ + public function onGet(Closure $callback): void + { + $this->getCallback = $callback; + } + + /** + * Capture query execution without contacting the database. + */ + public function get(ExpressionContract|array|string $columns = ['*']): Collection + { + ++$this->getCalls; + + return ($this->getCallback)($columns); } } diff --git a/tests/Database/DatabaseQueryExceptionTest.php b/tests/Database/DatabaseQueryExceptionTest.php index 20abce68f..8b52024f5 100755 --- a/tests/Database/DatabaseQueryExceptionTest.php +++ b/tests/Database/DatabaseQueryExceptionTest.php @@ -5,15 +5,19 @@ namespace Hypervel\Tests\Database; use Hypervel\Database\Connection; +use Hypervel\Database\ConnectionResolverInterface; use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Database\QueryException; use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDOException; class DatabaseQueryExceptionTest extends TestCase { + use VerifiesDoubles; + public function testIfItEmbedsBindingsIntoSql(): void { $connection = $this->getMockConnection(); @@ -26,7 +30,7 @@ public function testIfItEmbedsBindingsIntoSql(): void $pdoException = new PDOException('Mock SQL error'); $exception = new QueryException($connection->getName(), $sql, $bindings, $pdoException); - DB::shouldReceive('connection')->andReturn($connection); + DB::swap($this->getConnectionResolver($connection)); $result = $exception->getRawSql(); $this->assertSame($expectedSql, $result); @@ -44,7 +48,7 @@ public function testIfItReturnsSameSqlWhenThereAreNoBindings(): void $pdoException = new PDOException('Mock SQL error'); $exception = new QueryException($connection->getName(), $sql, $bindings, $pdoException); - DB::shouldReceive('connection')->andReturn($connection); + DB::swap($this->getConnectionResolver($connection)); $result = $exception->getRawSql(); $this->assertSame($expectedSql, $result); @@ -181,15 +185,26 @@ public function testMaskingBindingsDoesNotAffectTheAccessors(): void */ protected function getMockConnection(): Connection { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new Grammar($connection); - $connection->shouldReceive('getName')->andReturn('default'); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); - $connection->shouldReceive('escape')->with(1, false)->andReturn(1); - $connection->shouldReceive('escape')->with('br', false)->andReturn("'br'"); + $connection->allows('getName')->returns('default'); + $connection->allows('getQueryGrammar')->returns($grammar); + $connection->allows('escape')->with(1, false)->returns('1'); + $connection->allows('escape')->with('br', false)->returns("'br'"); return $connection; } + + /** + * Resolve the connection used to render the failed query. + */ + protected function getConnectionResolver(Connection $connection): ConnectionResolverInterface + { + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->with('default')->returns($connection); + + return $resolver; + } } diff --git a/tests/Database/DatabaseSQLiteSchemaGrammarTest.php b/tests/Database/DatabaseSQLiteSchemaGrammarTest.php index fe3ec5088..1ff1bf11d 100755 --- a/tests/Database/DatabaseSQLiteSchemaGrammarTest.php +++ b/tests/Database/DatabaseSQLiteSchemaGrammarTest.php @@ -7,19 +7,21 @@ use Hypervel\Database\Capsule\Manager; use Hypervel\Database\Connection; use Hypervel\Database\Query\Expression; -use Hypervel\Database\Query\Processors\SQLiteProcessor; use Hypervel\Database\Schema\Blueprint; use Hypervel\Database\Schema\ForeignIdColumnDefinition; use Hypervel\Database\Schema\Grammars\SQLiteGrammar; use Hypervel\Database\Schema\SQLiteBuilder; use Hypervel\Tests\Database\Fixtures\Enums\Foo; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class DatabaseSQLiteSchemaGrammarTest extends TestCase { + use VerifiesDoubles; + public function testBasicCreateTable(): void { $blueprint = new Blueprint($this->getConnection(), 'users'); @@ -452,9 +454,7 @@ public function testAddingID(): void public function testAddingForeignID(): void { $connection = $this->getConnection(); - $connection->shouldReceive('getPostProcessor')->andReturn(new SQLiteProcessor); - $connection->shouldReceive('selectFromWriteConnection')->andReturn([]); - $connection->shouldReceive('scalar')->andReturn(''); + $connection->allows('scalar')->returns(''); $blueprint = new Blueprint($connection, 'users'); $foreignId = $blueprint->foreignId('foo'); @@ -494,9 +494,7 @@ public function testAddingForeignID(): void public function testAddingForeignIdSpecifyingIndexNameInConstraint(): void { $connection = $this->getConnection(); - $connection->shouldReceive('getPostProcessor')->andReturn(new SQLiteProcessor); - $connection->shouldReceive('selectFromWriteConnection')->andReturn([]); - $connection->shouldReceive('scalar')->andReturn(''); + $connection->expects('scalar')->returns(''); $blueprint = new Blueprint($connection, 'users'); $blueprint->foreignId('company_id')->constrained(indexName: 'my_index'); @@ -705,12 +703,10 @@ public function testAddingJson(): void public function testAddingNativeJson(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->expects('getConfig')->with('use_native_json')->andReturn(true); - $connection->shouldReceive('getSchemaGrammar')->andReturn($this->getGrammar($connection)); - $connection->shouldReceive('getSchemaBuilder')->andReturn($this->getBuilder()); - $connection->shouldReceive('getServerVersion')->andReturn('3.35'); + $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)); $blueprint = new Blueprint($connection, 'users'); $blueprint->json('foo'); @@ -732,12 +728,10 @@ public function testAddingJsonb(): void public function testAddingNativeJsonb(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->expects('getConfig')->with('use_native_jsonb')->andReturn(true); - $connection->shouldReceive('getSchemaGrammar')->andReturn($this->getGrammar($connection)); - $connection->shouldReceive('getSchemaBuilder')->andReturn($this->getBuilder()); - $connection->shouldReceive('getServerVersion')->andReturn('3.35'); + $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)); $blueprint = new Blueprint($connection, 'users'); $blueprint->jsonb('foo'); @@ -972,9 +966,7 @@ public function testAddingUuidDefaultsColumnName(): void public function testAddingForeignUuid(): void { $connection = $this->getConnection(); - $connection->shouldReceive('getPostProcessor')->andReturn(new SQLiteProcessor); - $connection->shouldReceive('selectFromWriteConnection')->andReturn([]); - $connection->shouldReceive('scalar')->andReturn(''); + $connection->allows('scalar')->returns(''); $blueprint = new Blueprint($connection, 'users'); $foreignUuid = $blueprint->foreignUuid('foo'); @@ -1204,19 +1196,19 @@ public function testDroppingColumnsWorks(): void public function testRenamingAndChangingColumnsWork(): void { - $builder = m::mock(SQLiteBuilder::class)->makePartial(); - $builder->expects('getColumnsForSchemaState')->andReturn([ + $builder = Double::for(SQLiteBuilder::class)->passthru(); + $builder->expects('getColumnsForSchemaState')->returns([ 'columns' => [ ['name' => 'name', 'type_name' => 'varchar', 'type' => 'varchar', 'collation' => null, 'nullable' => false, 'default' => null, 'auto_increment' => false, 'comment' => null, 'generation' => null], ['name' => 'age', 'type_name' => 'varchar', 'type' => 'varchar', 'collation' => null, 'nullable' => false, 'default' => null, 'auto_increment' => false, 'comment' => null, 'generation' => null], ], 'sql' => 'CREATE TABLE users (name varchar, age varchar)', ]); - $builder->expects('getIndexesForSchemaState')->andReturn([]); - $builder->expects('getForeignKeysForSchemaState')->andReturn([]); + $builder->expects('getIndexesForSchemaState')->returns([]); + $builder->expects('getForeignKeysForSchemaState')->returns([]); $connection = $this->getConnection(builder: $builder); - $connection->expects('scalar')->with('pragma foreign_keys', [], false)->andReturn(false); + $connection->expects('scalar')->with('pragma foreign_keys', [], false)->returns(false); $blueprint = new Blueprint($connection, 'users'); $blueprint->renameColumn('name', 'first_name'); @@ -1233,19 +1225,19 @@ public function testRenamingAndChangingColumnsWork(): void public function testRenamingAndChangingColumnsWorkWithSchema(): void { - $builder = m::mock(SQLiteBuilder::class)->makePartial(); - $builder->expects('getColumnsForSchemaState')->andReturn([ + $builder = Double::for(SQLiteBuilder::class)->passthru(); + $builder->expects('getColumnsForSchemaState')->returns([ 'columns' => [ ['name' => 'name', 'type_name' => 'varchar', 'type' => 'varchar', 'collation' => null, 'nullable' => false, 'default' => null, 'auto_increment' => false, 'comment' => null, 'generation' => null], ['name' => 'age', 'type_name' => 'varchar', 'type' => 'varchar', 'collation' => null, 'nullable' => false, 'default' => null, 'auto_increment' => false, 'comment' => null, 'generation' => null], ], 'sql' => 'CREATE TABLE users (name varchar, age varchar)', ]); - $builder->expects('getIndexesForSchemaState')->andReturn([]); - $builder->expects('getForeignKeysForSchemaState')->andReturn([]); + $builder->expects('getIndexesForSchemaState')->returns([]); + $builder->expects('getForeignKeysForSchemaState')->returns([]); $connection = $this->getConnection(builder: $builder); - $connection->expects('scalar')->with('pragma foreign_keys', [], false)->andReturn(false); + $connection->expects('scalar')->with('pragma foreign_keys', [], false)->returns(false); $blueprint = new Blueprint($connection, 'my_schema.users'); $blueprint->renameColumn('name', 'first_name'); @@ -1267,16 +1259,16 @@ protected function getConnection( ?SQLiteGrammar $grammar = null, ?SQLiteBuilder $builder = null, string $prefix = '' - ): Connection&MockInterface { - $connection = m::mock(Connection::class); + ): Connection&DoubleInterface { + $connection = Double::for(Connection::class); $grammar ??= $this->getGrammar($connection); $builder ??= $this->getBuilder(); - $connection->shouldReceive('getTablePrefix')->andReturn($prefix); - $connection->shouldReceive('getConfig')->andReturn(null); - $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); - $connection->shouldReceive('getSchemaBuilder')->andReturn($builder); - $connection->shouldReceive('getServerVersion')->andReturn('3.35'); + $connection->allows('getTablePrefix')->returns($prefix); + $connection->allows('getConfig')->returns(null); + $connection->allows('getSchemaGrammar')->returns($grammar); + $connection->allows('getSchemaBuilder')->returns($builder); + $connection->allows('getServerVersion')->returns('3.35'); return $connection; } @@ -1294,13 +1286,13 @@ public function getGrammar(?Connection $connection = null): SQLiteGrammar */ public function getBuilder(): SQLiteBuilder { - $builder = m::mock(SQLiteBuilder::class)->makePartial(); - $builder->shouldReceive('getColumnsForSchemaState')->andReturn([ + $builder = Double::for(SQLiteBuilder::class)->passthru(); + $builder->allows('getColumnsForSchemaState')->returns([ 'columns' => [], 'sql' => 'CREATE TABLE users ()', ]); - $builder->shouldReceive('getIndexesForSchemaState')->andReturn([]); - $builder->shouldReceive('getForeignKeysForSchemaState')->andReturn([]); + $builder->allows('getIndexesForSchemaState')->returns([]); + $builder->allows('getForeignKeysForSchemaState')->returns([]); return $builder; } diff --git a/tests/Database/DatabaseSchemaBlueprintTest.php b/tests/Database/DatabaseSchemaBlueprintTest.php index 434ac5299..3021221d4 100755 --- a/tests/Database/DatabaseSchemaBlueprintTest.php +++ b/tests/Database/DatabaseSchemaBlueprintTest.php @@ -24,21 +24,24 @@ use Hypervel\Tests\Database\Fixtures\Models\User; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; -use Mockery\MockInterface; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; class DatabaseSchemaBlueprintTest extends TestCase { + use VerifiesDoubles; + public function testToSqlRunsCommandsFromBlueprint(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->andReturn(new MySqlGrammar($connection)); - $connection->expects('statement')->with('foo')->andReturnTrue()->ordered(); - $connection->expects('statement')->with('bar')->andReturnTrue()->ordered(); - $connection->expects('getSchemaBuilder')->andReturn(new Builder($connection)); + $connection = Double::for(Connection::class); + $connection->allows('getSchemaGrammar')->returns(new MySqlGrammar($connection)); + $connection->expects('statement')->with('foo')->returns(true)->ordered(); + $connection->expects('statement')->with('bar')->returns(true)->ordered(); + $connection->expects('getSchemaBuilder')->returns(new Builder($connection)); $blueprint = $this->getMockBuilder(Blueprint::class)->onlyMethods(['toSql'])->setConstructorArgs([$connection, 'users'])->getMock(); $blueprint->expects($this->once())->method('toSql')->willReturn(['foo', 'bar']); @@ -286,8 +289,8 @@ public function testDefaultCurrentDate(): void $getSql = function (string $grammar, bool $mysql57 = false): array { if ($grammar === 'MySql') { $connection = $this->getConnection($grammar); - $mysql57 ? $connection->shouldReceive('getServerVersion')->andReturn('5.7') : $connection->shouldReceive('getServerVersion')->andReturn('8.0.13'); - $connection->shouldReceive('isMaria')->andReturn(false); + $mysql57 ? $connection->expects('getServerVersion')->returns('5.7') : $connection->expects('getServerVersion')->returns('8.0.13'); + $connection->expects('isMaria')->returns(false); return (new Blueprint($connection, 'users', function (Blueprint $table): void { $table->date('created')->useCurrent(); @@ -336,8 +339,8 @@ public function testDefaultCurrentYear(): void $getSql = function (string $grammar, bool $mysql57 = false): array { if ($grammar === 'MySql') { $connection = $this->getConnection($grammar); - $mysql57 ? $connection->shouldReceive('getServerVersion')->andReturn('5.7') : $connection->shouldReceive('getServerVersion')->andReturn('8.0.13'); - $connection->shouldReceive('isMaria')->andReturn(false); + $mysql57 ? $connection->expects('getServerVersion')->returns('5.7') : $connection->expects('getServerVersion')->returns('8.0.13'); + $connection->expects('isMaria')->returns(false); return (new Blueprint($connection, 'users', function (Blueprint $table): void { $table->year('birth_year')->useCurrent(); @@ -480,9 +483,9 @@ public function testSqliteAlterKeepsGeneratedIndexAtTheEndOfTheCallbackCommands( { $connection = $this->getConnection('SQLite'); $connection->getSchemaBuilder() - ->shouldReceive('parseSchemaAndTable') + ->allows('parseSchemaAndTable') ->with('nodes') - ->andReturn([null, 'nodes']); + ->returns([null, 'nodes']); $blueprint = new Blueprint($connection, 'nodes', function (Blueprint $table) { $table->integer('id')->unique(); @@ -498,8 +501,10 @@ public function testRenameColumn(): void { $getSql = function ($grammar) { $connection = $this->getConnection($grammar); - $connection->shouldReceive('getServerVersion')->andReturn('8.0.4'); - $connection->shouldReceive('isMaria')->andReturn(false); + if ($grammar === 'MySql') { + $connection->expects('getServerVersion')->returns('8.0.4'); + $connection->expects('isMaria')->returns(false); + } return (new Blueprint($connection, 'users', function ($table) { $table->renameColumn('foo', 'bar'); @@ -514,9 +519,9 @@ public function testRenameColumn(): void public function testNativeRenameColumnOnMysql57(): void { $connection = $this->getConnection('MySql'); - $connection->shouldReceive('isMaria')->andReturn(false); - $connection->shouldReceive('getServerVersion')->andReturn('5.7'); - $connection->getSchemaBuilder()->shouldReceive('getColumns')->andReturn([ + $connection->expects('isMaria')->times(3)->returns(false); + $connection->allows('getServerVersion')->returns('5.7'); + $connection->getSchemaBuilder()->allows('getColumns')->returns([ ['name' => 'name', 'type' => 'varchar(255)', 'type_name' => 'varchar', 'nullable' => true, 'collation' => 'utf8mb4_unicode_ci', 'default' => 'foo', 'comment' => null, 'auto_increment' => false, 'generation' => null], ['name' => 'id', 'type' => 'bigint unsigned', 'type_name' => 'bigint', 'nullable' => false, 'collation' => null, 'default' => null, 'comment' => 'lorem ipsum', 'auto_increment' => true, 'generation' => null], ['name' => 'generated', 'type' => 'int', 'type_name' => 'int', 'nullable' => false, 'collation' => null, 'default' => null, 'comment' => null, 'auto_increment' => false, 'generation' => ['type' => 'stored', 'expression' => 'expression']], @@ -541,9 +546,9 @@ public function testNativeRenameColumnOnMysql57(): void public function testNativeRenameColumnOnMariaDb(string $driver): void { $connection = $this->getConnection($driver); - $connection->shouldReceive('isMaria')->andReturn(true); - $connection->shouldNotReceive('getServerVersion'); - $connection->getSchemaBuilder()->shouldNotReceive('getColumns'); + $connection->allows('isMaria')->returns(true); + $connection->expects('getServerVersion')->never(); + $connection->getSchemaBuilder()->expects('getColumns')->never(); $blueprint = new Blueprint($connection, 'users', function ($table) { $table->renameColumn('name', 'title'); @@ -1010,34 +1015,29 @@ public function testColumnDefault(): void /** * Get a connection mock. */ - protected function getConnection(?string $grammar = null, string $prefix = ''): Connection&MockInterface + protected function getConnection(?string $grammar = null, string $prefix = ''): Connection&DoubleInterface { $grammar ??= 'MySql'; - $connection = m::mock(match ($grammar) { + $connection = Double::for(match ($grammar) { 'MySql' => MySqlConnection::class, 'MariaDb' => MariaDbConnection::class, default => Connection::class, }); - $connection->shouldReceive('getTablePrefix')->andReturn($prefix); - $connection->shouldReceive('getConfig')->with('prefix_indexes')->andReturn(true); + $connection->allows('getTablePrefix')->returns($prefix); + $connection->allows('getConfig')->with('prefix_indexes')->returns(true); $grammarClass = 'Hypervel\Database\Schema\Grammars\\' . $grammar . 'Grammar'; $builderClass = 'Hypervel\Database\Schema\\' . $grammar . 'Builder'; - $connection->shouldReceive('getSchemaGrammar')->andReturn(new $grammarClass($connection)); - $connection->shouldReceive('getSchemaBuilder')->andReturn(m::mock($builderClass)); + $connection->allows('getSchemaGrammar')->returns(new $grammarClass($connection)); + $connection->allows('getSchemaBuilder')->returns(Double::for($builderClass)); if ($grammar === 'SQLite') { - $connection->shouldReceive('getServerVersion')->andReturn('3.35'); - } - - if ($grammar === 'MySql') { - $connection->shouldReceive('isMaria')->andReturn(false)->byDefault(); + $connection->allows('getServerVersion')->returns('3.35'); } if ($connection instanceof MySqlConnection) { - $connection->shouldReceive('usesBackslashEscapes')->passthru(); - $connection->shouldReceive('getConfig')->with('modes')->andReturn(null); + $connection->allows('usesBackslashEscapes')->returns(true); } return $connection; diff --git a/tests/Database/DatabaseSchemaBuilderTest.php b/tests/Database/DatabaseSchemaBuilderTest.php index 688864102..dfd1c0e6f 100644 --- a/tests/Database/DatabaseSchemaBuilderTest.php +++ b/tests/Database/DatabaseSchemaBuilderTest.php @@ -13,7 +13,8 @@ use Hypervel\Database\Schema\Builder; use Hypervel\Database\Schema\Grammars\Grammar; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PDOException; use PHPUnit\Framework\Attributes\DataProvider; @@ -21,20 +22,22 @@ class DatabaseSchemaBuilderTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('metadataMethods')] public function testMetadataReadsUseTheOverridableWriterHook(string $method, array $arguments, string $compile, array $compileArguments, string $process): void { - $connection = m::mock(Connection::class); - $grammar = m::mock(Grammar::class); - $processor = m::mock(Processor::class); + $connection = Double::for(Connection::class); + $grammar = Double::for(Grammar::class); + $processor = Double::for(Processor::class); $rows = [(object) ['name' => 'id']]; $processed = [['name' => 'id']]; - $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); - $connection->shouldReceive('getPostProcessor')->andReturn($processor); - $connection->shouldReceive('getTablePrefix')->andReturn('prefix_'); - $grammar->shouldReceive($compile)->once()->with(...$compileArguments)->andReturn('metadata sql'); - $connection->shouldReceive('selectFromWriteConnection')->once()->with('metadata sql')->andReturn($rows); - $processor->shouldReceive($process)->once()->with($rows)->andReturn($processed); + $connection->allows('getSchemaGrammar')->returns($grammar); + $connection->allows('getPostProcessor')->returns($processor); + $connection->allows('getTablePrefix')->returns('prefix_'); + $grammar->expects($compile)->with(...$compileArguments)->returns('metadata sql'); + $connection->expects('selectFromWriteConnection')->with('metadata sql')->returns($rows); + $processor->expects($process)->with($rows)->returns($processed); $builder = new DatabaseSchemaMetadataBuilder($connection); $this->assertSame($method === 'hasColumn' ? true : $processed, $builder->{$method}(...$arguments)); @@ -59,12 +62,12 @@ public static function metadataMethods(): array #[DataProvider('tableExistenceResults')] public function testTableExistenceUsesTheMetadataHookAndPreservesScalarValidation(array $rows, ?bool $expected): void { - $connection = m::mock(Connection::class); - $grammar = m::mock(Grammar::class); - $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); - $connection->shouldReceive('getTablePrefix')->andReturn('prefix_'); - $grammar->shouldReceive('compileTableExists')->once()->with('public', 'prefix_users')->andReturn('exists sql'); - $connection->shouldReceive('selectFromWriteConnection')->once()->with('exists sql')->andReturn($rows); + $connection = Double::for(Connection::class); + $grammar = Double::for(Grammar::class); + $connection->allows('getSchemaGrammar')->returns($grammar); + $connection->allows('getTablePrefix')->returns('prefix_'); + $grammar->expects('compileTableExists')->with('public', 'prefix_users')->returns('exists sql'); + $connection->expects('selectFromWriteConnection')->with('exists sql')->returns($rows); $builder = new DatabaseSchemaMetadataBuilder($connection); if ($expected === null) { @@ -93,11 +96,11 @@ public static function tableExistenceResults(): array public function testCreateDatabase(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new class($connection) extends Grammar { }; - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('statement')->with($grammar->compileCreateDatabase('foo'))->andReturnTrue(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('statement')->with($grammar->compileCreateDatabase('foo'))->returns(true); $builder = new Builder($connection); $this->assertTrue($builder->createDatabase('foo')); @@ -105,11 +108,11 @@ public function testCreateDatabase(): void public function testDropDatabaseIfExists(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new class($connection) extends Grammar { }; - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('statement')->with($grammar->compileDropDatabaseIfExists('foo'))->andReturnTrue(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('statement')->with($grammar->compileDropDatabaseIfExists('foo'))->returns(true); $builder = new Builder($connection); $this->assertTrue($builder->dropDatabaseIfExists('foo')); @@ -117,19 +120,19 @@ public function testDropDatabaseIfExists(): void public function testTruncateTablesChecksWriteRowsAndSkipsEmptyTables(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(m::mock(Grammar::class)); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(Double::for(Grammar::class)); foreach (['public.populated' => true, 'public.empty' => false] as $name => $hasRows) { - $query = m::mock(QueryBuilder::class); - $connection->shouldReceive('table')->once()->with($name)->andReturn($query); - $query->shouldReceive('useWritePdo')->once()->andReturnSelf(); - $query->shouldReceive('exists')->once()->andReturn($hasRows); + $query = Double::for(QueryBuilder::class); + $connection->expects('table')->with($name)->returns($query); + $query->expects('useWritePdo')->returns($query); + $query->expects('exists')->returns($hasRows); if ($hasRows) { - $query->shouldReceive('truncate')->once(); + $query->expects('truncate'); } else { - $query->shouldNotReceive('truncate'); + $query->expects('truncate')->never(); } } @@ -139,15 +142,15 @@ public function testTruncateTablesChecksWriteRowsAndSkipsEmptyTables(): void #[DataProvider('partitionSelections')] public function testWithoutCoveredPartitionsKeepsOnlyPartitionsOfTablesOutsideTheSelection(array $tables, array $except, ?array $missingParents, array $links, array $expected): void { - $connection = m::mock(Connection::class); - $grammar = m::mock(Grammar::class); - $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); + $connection = Double::for(Connection::class); + $grammar = Double::for(Grammar::class); + $connection->allows('getSchemaGrammar')->returns($grammar); if ($missingParents === null) { - $grammar->shouldNotReceive('compilePartitionAncestors'); + $grammar->expects('compilePartitionAncestors')->never(); } else { - $grammar->expects('compilePartitionAncestors')->with($missingParents)->andReturn('ancestors sql'); - $connection->expects('selectFromWriteConnection')->with('ancestors sql')->andReturn($links); + $grammar->expects('compilePartitionAncestors')->with($missingParents)->returns('ancestors sql'); + $connection->expects('selectFromWriteConnection')->with('ancestors sql')->returns($links); } $tables = array_map(fn (array $table): array => ['schema_qualified_name' => $table[0], 'partition_of' => $table[1]], $tables); @@ -187,28 +190,28 @@ public static function partitionSelections(): array public function testExecuteBlueprintCompilesOnceAndExecutesStatementsInOrder(): void { - $connection = m::mock(Connection::class); - $grammar = m::mock(Grammar::class); - $blueprint = m::mock(Blueprint::class); + $connection = Double::for(Connection::class); + $grammar = Double::for(Grammar::class); + $blueprint = Double::for(Blueprint::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $blueprint->shouldReceive('toSql')->once()->andReturn(['first statement', 'second statement']); - $connection->shouldReceive('statement')->once()->with('first statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $blueprint->expects('toSql')->returns(['first statement', 'second statement']); + $connection->expects('statement')->with('first statement')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); (new Builder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintThrowsWhenAStatementReturnsFalse(): void { - $connection = m::mock(Connection::class); - $grammar = m::mock(Grammar::class); - $blueprint = m::mock(Blueprint::class); + $connection = Double::for(Connection::class); + $grammar = Double::for(Grammar::class); + $blueprint = Double::for(Blueprint::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $blueprint->shouldReceive('toSql')->once()->andReturn(['failed statement', 'unreached statement']); - $connection->shouldReceive('statement')->once()->with('failed statement')->andReturnFalse(); - $connection->shouldReceive('statement')->never()->with('unreached statement'); + $connection->expects('getSchemaGrammar')->returns($grammar); + $blueprint->expects('toSql')->returns(['failed statement', 'unreached statement']); + $connection->expects('statement')->with('failed statement')->returns(false); + $connection->expects('statement')->never()->with('unreached statement'); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Failed to execute schema statement [failed statement].'); @@ -218,15 +221,15 @@ public function testExecuteBlueprintThrowsWhenAStatementReturnsFalse(): void public function testWithoutForeignKeyConstraintsNestsAcrossBuilderInstances(): void { - $pdo = m::mock(PDO::class); + $pdo = Double::for(PDO::class); $connection = new PdoConnection($pdo, 'test'); - $grammar = m::mock(Grammar::class); + $grammar = Double::for(Grammar::class); $connection->setSchemaGrammar($grammar); - $grammar->shouldReceive('compileDisableForeignKeyConstraints')->once()->andReturn('disable constraints'); - $grammar->shouldReceive('compileEnableForeignKeyConstraints')->once()->andReturn('enable constraints'); - $pdo->shouldReceive('exec')->once()->with('disable constraints')->andReturn(0)->ordered(); - $pdo->shouldReceive('exec')->once()->with('enable constraints')->andReturn(0)->ordered(); + $grammar->expects('compileDisableForeignKeyConstraints')->returns('disable constraints'); + $grammar->expects('compileEnableForeignKeyConstraints')->returns('enable constraints'); + $pdo->expects('exec')->with('disable constraints')->returns(0)->ordered(); + $pdo->expects('exec')->with('enable constraints')->returns(0)->ordered(); $outer = new Builder($connection); $inner = new Builder($connection); @@ -249,11 +252,11 @@ static function () use (&$resolutions): PDO { }, 'test' ); - $grammar = m::mock(Grammar::class); + $grammar = Double::for(Grammar::class); $connection->setSchemaGrammar($grammar); - $grammar->shouldReceive('compileDisableForeignKeyConstraints')->once()->andReturn('disable constraints'); - $grammar->shouldReceive('compileEnableForeignKeyConstraints')->once()->andReturn('enable constraints'); + $grammar->expects('compileDisableForeignKeyConstraints')->returns('disable constraints'); + $grammar->expects('compileEnableForeignKeyConstraints')->returns('enable constraints'); $queries = $connection->pretend( fn () => (new Builder($connection))->withoutForeignKeyConstraints(fn () => null) @@ -268,16 +271,16 @@ static function () use (&$resolutions): PDO { public function testWithoutForeignKeyConstraintsMarksTheSessionUnknownWhenRestorationFails(): void { - $pdo = m::mock(PDO::class); + $pdo = Double::for(PDO::class); $connection = new PdoConnection($pdo, 'test'); - $grammar = m::mock(Grammar::class); + $grammar = Double::for(Grammar::class); $connection->setSchemaGrammar($grammar); $failure = new PDOException('Failed to restore foreign key constraints.'); - $grammar->shouldReceive('compileDisableForeignKeyConstraints')->once()->andReturn('disable constraints'); - $grammar->shouldReceive('compileEnableForeignKeyConstraints')->once()->andReturn('enable constraints'); - $pdo->shouldReceive('exec')->once()->with('disable constraints')->andReturn(0)->ordered(); - $pdo->shouldReceive('exec')->once()->with('enable constraints')->andThrow($failure)->ordered(); + $grammar->expects('compileDisableForeignKeyConstraints')->returns('disable constraints'); + $grammar->expects('compileEnableForeignKeyConstraints')->returns('enable constraints'); + $pdo->expects('exec')->with('disable constraints')->returns(0)->ordered(); + $pdo->expects('exec')->with('enable constraints')->throws($failure)->ordered(); try { (new Builder($connection))->withoutForeignKeyConstraints(fn () => null); @@ -294,17 +297,17 @@ public function testWithoutForeignKeyConstraintsMarksTheSessionUnknownWhenRestor public function testWithoutForeignKeyConstraintsPreservesNativeExceptionChainingWhenCallbackAndRestorationFail(): void { - $pdo = m::mock(PDO::class); + $pdo = Double::for(PDO::class); $connection = new PdoConnection($pdo, 'test'); - $grammar = m::mock(Grammar::class); + $grammar = Double::for(Grammar::class); $connection->setSchemaGrammar($grammar); $callbackFailure = new RuntimeException('callback failed'); $restorationFailure = new RuntimeException('restoration failed'); - $grammar->shouldReceive('compileDisableForeignKeyConstraints')->once()->andReturn('disable constraints'); - $grammar->shouldReceive('compileEnableForeignKeyConstraints')->once()->andReturn('enable constraints'); - $pdo->shouldReceive('exec')->once()->with('disable constraints')->andReturn(0)->ordered(); - $pdo->shouldReceive('exec')->once()->with('enable constraints')->andThrow($restorationFailure)->ordered(); + $grammar->expects('compileDisableForeignKeyConstraints')->returns('disable constraints'); + $grammar->expects('compileEnableForeignKeyConstraints')->returns('enable constraints'); + $pdo->expects('exec')->with('disable constraints')->returns(0)->ordered(); + $pdo->expects('exec')->with('enable constraints')->throws($restorationFailure)->ordered(); try { (new Builder($connection))->withoutForeignKeyConstraints( @@ -321,28 +324,28 @@ public function testWithoutForeignKeyConstraintsPreservesNativeExceptionChaining public function testHasTableCorrectlyCallsGrammar(): void { - $connection = m::mock(Connection::class); - $grammar = m::mock(Grammar::class); - $processor = m::mock(Processor::class); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('getPostProcessor')->andReturn($processor); + $connection = Double::for(Connection::class); + $grammar = Double::for(Grammar::class); + $processor = Double::for(Processor::class); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getPostProcessor')->returns($processor); $builder = new Builder($connection); $grammar->expects('compileTableExists'); - $grammar->expects('compileTables')->andReturn('sql'); - $processor->expects('processTables')->andReturn([['name' => 'prefix_table']]); - $connection->expects('getTablePrefix')->andReturn('prefix_'); - $connection->expects('selectFromWriteConnection')->with('sql')->andReturn([['name' => 'prefix_table']]); + $grammar->expects('compileTables')->returns('sql'); + $processor->expects('processTables')->returns([['name' => 'prefix_table']]); + $connection->expects('getTablePrefix')->returns('prefix_'); + $connection->expects('selectFromWriteConnection')->with('sql')->returns([['name' => 'prefix_table']]); $this->assertTrue($builder->hasTable('table')); } public function testTableHasColumns(): void { - $connection = m::mock(Connection::class); - $grammar = m::mock(Grammar::class); - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $builder = m::mock(Builder::class . '[getColumnListing]', [$connection]); - $builder->expects('getColumnListing')->with('users')->times(2)->andReturn(['id', 'firstname']); + $connection = Double::for(Connection::class); + $grammar = Double::for(Grammar::class); + $connection->expects('getSchemaGrammar')->returns($grammar); + $builder = Double::for(new Builder($connection))->passthru(); + $builder->expects('getColumnListing')->with('users')->times(2)->returns(['id', 'firstname']); $this->assertTrue($builder->hasColumns('users', ['id', 'firstname'])); $this->assertFalse($builder->hasColumns('users', ['id', 'address'])); @@ -351,10 +354,10 @@ public function testTableHasColumns(): void #[DataProvider('columnNames')] public function testColumnExistenceMatchesUnicodeWithoutCoercingNumericNames(string $column, bool $exists): void { - $connection = m::mock(Connection::class); - $connection->expects('getSchemaGrammar')->andReturn(m::mock(Grammar::class)); - $builder = m::mock(Builder::class . '[getColumnListing]', [$connection]); - $builder->expects('getColumnListing')->with('users')->twice()->andReturn(['Émail', '01']); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(Double::for(Grammar::class)); + $builder = Double::for(new Builder($connection))->passthru(); + $builder->expects('getColumnListing')->with('users')->times(2)->returns(['Émail', '01']); $this->assertSame($exists, $builder->hasColumn('users', $column)); $this->assertSame($exists, $builder->hasColumns('users', [$column])); @@ -380,10 +383,10 @@ public function testColumnLookupPrefersExactNamesBeforeCaseInsensitiveMatches(st ['name' => 'FOO', 'type_name' => 'varchar', 'type' => 'varchar(255)'], ['name' => 'Émail', 'type_name' => 'text', 'type' => 'text'], ]; - $connection = m::mock(Connection::class); - $connection->expects('getSchemaGrammar')->andReturn(m::mock(Grammar::class)); - $builder = m::mock(Builder::class . '[getColumns]', [$connection]); - $builder->expects('getColumns')->with('users')->times(3)->andReturn($columns); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(Double::for(Grammar::class)); + $builder = Double::for(new Builder($connection))->passthru(); + $builder->expects('getColumns')->with('users')->times(3)->returns($columns); $this->assertSame($columns[$index], $builder->getColumn('users', $column)); $this->assertSame($columns[$index]['type_name'], $builder->getColumnType('users', $column)); @@ -405,7 +408,7 @@ public static function columnLookups(): array public function testGetColumnTypeAddsPrefix(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new class($connection) extends Grammar { /** * Compile the query to determine the columns. @@ -416,11 +419,11 @@ public function compileColumns(?string $schema, string $table): string } }; $processor = new Processor; - $connection->expects('getSchemaGrammar')->andReturn($grammar); - $connection->expects('getPostProcessor')->andReturn($processor); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('getPostProcessor')->returns($processor); $builder = new Builder($connection); - $connection->expects('getTablePrefix')->andReturn('prefix_'); - $connection->expects('selectFromWriteConnection')->with('columns for prefix_users')->andReturn([['name' => 'id', 'type_name' => 'integer']]); + $connection->expects('getTablePrefix')->returns('prefix_'); + $connection->expects('selectFromWriteConnection')->with('columns for prefix_users')->returns([['name' => 'id', 'type_name' => 'integer']]); $this->assertSame('integer', $builder->getColumnType('users', 'id')); } diff --git a/tests/Database/DatabaseSeederTest.php b/tests/Database/DatabaseSeederTest.php index e3624b715..da37a2dc9 100755 --- a/tests/Database/DatabaseSeederTest.php +++ b/tests/Database/DatabaseSeederTest.php @@ -10,8 +10,9 @@ use Hypervel\Contracts\Container\Container; use Hypervel\Database\Seeder; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\Mock; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; class TestSeeder extends Seeder @@ -23,7 +24,7 @@ public function run(): void class TestDepsSeeder extends Seeder { - public function run(Mock $someDependency, string $someParam = ''): void + public function run(Container $someDependency, string $someParam = ''): void { } } @@ -137,6 +138,8 @@ public function run(): void class DatabaseSeederTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -148,17 +151,17 @@ protected function setUp(): void public function testCallResolveTheClassAndCallsRun(): void { $seeder = new TestSeeder; - $container = m::mock(Container::class); - $seeder->setContainer($container); - $output = m::mock(OutputStyle::class); + $container = Double::for(Container::class, override: true); + $seeder->setContainer($container->instance()); + $output = Double::for(OutputStyle::class); $output->expects('writeln')->times(3); - $command = m::mock(Command::class); - $command->expects('getOutput')->times(3)->andReturn($output); + $command = Double::for(Command::class); + $command->expects('getOutput')->times(3)->returns($output); $seeder->setCommand($command); - $child = m::mock(Seeder::class); - $container->expects('make')->with('ClassName')->andReturn($child); - $child->expects('setContainer')->with($container)->andReturn($child); - $child->expects('setCommand')->with($command)->andReturn($child); + $child = Double::for(Seeder::class); + $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); $child->expects('__invoke'); $seeder->call('ClassName'); @@ -180,28 +183,28 @@ public function testSetCommand(): void public function testInjectDependenciesOnRunMethod(): void { - $container = m::mock(Container::class); + $container = Double::for(Container::class, override: true); $container->expects('call'); $seeder = new TestDepsSeeder; - $seeder->setContainer($container); + $seeder->setContainer($container->instance()); $seeder->__invoke(); - $container->shouldHaveReceived('call')->once()->with([$seeder, 'run'], []); + $container->received('call')->times(1)->with([$seeder, 'run'], []); } public function testSendParamsOnCallMethodWithDeps(): void { - $container = m::mock(Container::class); + $container = Double::for(Container::class, override: true); $container->expects('call'); $seeder = new TestDepsSeeder; - $seeder->setContainer($container); + $seeder->setContainer($container->instance()); $seeder->__invoke(['test1', 'test2']); - $container->shouldHaveReceived('call')->once()->with([$seeder, 'run'], ['test1', 'test2']); + $container->received('call')->times(1)->with([$seeder, 'run'], ['test1', 'test2']); } public function testCallOnceResetsForEveryInvocationOfTheSameRoot(): void diff --git a/tests/Database/DatabaseSoftDeletingScopeTest.php b/tests/Database/DatabaseSoftDeletingScopeTest.php index 14b5a5749..4d943ab28 100644 --- a/tests/Database/DatabaseSoftDeletingScopeTest.php +++ b/tests/Database/DatabaseSoftDeletingScopeTest.php @@ -8,13 +8,8 @@ use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\SoftDeletes; use Hypervel\Database\Eloquent\SoftDeletingScope; -use Hypervel\Database\PdoConnection; -use Hypervel\Database\Query\Builder as BaseBuilder; -use Hypervel\Database\Query\Grammars\Grammar; -use Hypervel\Database\Query\Processors\Processor; use Hypervel\Database\SQLiteConnection; use Hypervel\Tests\TestCase; -use Mockery as m; use PDO; class DatabaseSoftDeletingScopeTest extends TestCase @@ -38,54 +33,6 @@ public function testRestoreExtension(): void $this->assertSame(0, $connection->table('users')->whereNotNull('deleted_at')->count()); } - public function testRestoreOrCreateExtension(): void - { - $connection = new PdoConnection(new PDO('sqlite::memory:')); - $builder = new EloquentBuilder(new BaseBuilder( - $connection, - new Grammar($connection), - new Processor - )); - - $scope = new SoftDeletingScope; - $scope->extend($builder); - $callback = $builder->getMacro('restoreOrCreate'); - $givenBuilder = m::mock(EloquentBuilder::class); - $givenBuilder->expects('withTrashed'); - $attributes = ['name' => 'foo']; - $values = ['email' => 'bar']; - $model = m::mock(Model::class); - $givenBuilder->expects('firstOrCreate')->with($attributes, $values)->andReturn($model); - $model->expects('restore')->andReturn(true); - $result = $callback($givenBuilder, $attributes, $values); - - $this->assertEquals($model, $result); - } - - public function testCreateOrRestoreExtension(): void - { - $connection = new PdoConnection(new PDO('sqlite::memory:')); - $builder = new EloquentBuilder(new BaseBuilder( - $connection, - new Grammar($connection), - new Processor - )); - - $scope = new SoftDeletingScope; - $scope->extend($builder); - $callback = $builder->getMacro('createOrRestore'); - $givenBuilder = m::mock(EloquentBuilder::class); - $givenBuilder->expects('withTrashed'); - $attributes = ['name' => 'foo']; - $values = ['email' => 'bar']; - $model = m::mock(Model::class); - $givenBuilder->expects('createOrFirst')->with($attributes, $values)->andReturn($model); - $model->expects('restore')->andReturn(true); - $result = $callback($givenBuilder, $attributes, $values); - - $this->assertEquals($model, $result); - } - public function testWithTrashedExtension(): void { $builder = $this->newBuilder(); diff --git a/tests/Database/DatabaseSoftDeletingTraitTest.php b/tests/Database/DatabaseSoftDeletingTraitTest.php deleted file mode 100644 index 968ae7764..000000000 --- a/tests/Database/DatabaseSoftDeletingTraitTest.php +++ /dev/null @@ -1,145 +0,0 @@ -makePartial(); - $query = m::mock(Builder::class); - $model->expects('newModelQuery')->andReturn($query); - $query->expects('where')->with('id', '=', 1)->andReturn($query); - $query->expects('update')->with([ - 'deleted_at' => 'date-time', - 'updated_at' => 'date-time', - ]); - $model->expects('syncOriginalAttributes')->with([ - 'deleted_at', - 'updated_at', - ]); - $model->expects('usesTimestamps')->andReturn(true); - $model->delete(); - - $this->assertSame(CarbonImmutable::class, $model->deleted_at::class); - } - - public function testForceDeleteWrappersPreserveIntegerDeleteResult(): void - { - $model = new IntegerDeleteResultModelStub; - $model->exists = true; - - $this->assertSame(1, $model->forceDelete()); - $this->assertSame(1, $model->forceDeleteQuietly()); - } - - public function testRestore(): void - { - $model = m::mock(Stub::class)->makePartial(); - $model->expects('fireModelEvent')->with('restoring')->andReturn(true); - $model->expects('save'); - - $model->restore(); - - $this->assertNull($model->deleted_at); - } - - public function testRestoreCancel(): void - { - $model = m::mock(Stub::class)->makePartial(); - $model->expects('fireModelEvent')->with('restoring')->andReturn(false); - $model->shouldReceive('save')->never(); - - $this->assertFalse($model->restore()); - } -} - -class Stub -{ - use SoftDeletes; - - public $deleted_at; - - public $updated_at; - - public $timestamps = true; - - public $exists = false; - - public function newQuery() - { - } - - public function getKey() - { - return 1; - } - - public function getKeyName() - { - return 'id'; - } - - public function save(): bool - { - return true; - } - - public function delete() - { - return $this->performDeleteOnModel(); - } - - public function fireModelEvent() - { - } - - public function freshTimestamp(): CarbonImmutable - { - return CarbonImmutable::now(); - } - - public function fromDateTime() - { - return 'date-time'; - } - - public function getUpdatedAtColumn() - { - return defined('static::UPDATED_AT') ? static::UPDATED_AT : 'updated_at'; - } - - public function setKeysForSaveQuery($query) - { - $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery()); - - return $query; - } - - protected function getKeyForSaveQuery() - { - return 1; - } -} - -class IntegerDeleteResultModelStub extends Model -{ - use SoftDeletes; - - /** - * Return a simulated affected-row count. - */ - public function delete(): int - { - return 1; - } -} diff --git a/tests/Database/DatabaseSqliteSchemaStateTest.php b/tests/Database/DatabaseSqliteSchemaStateTest.php index dcc474ef8..77059c116 100644 --- a/tests/Database/DatabaseSqliteSchemaStateTest.php +++ b/tests/Database/DatabaseSqliteSchemaStateTest.php @@ -9,23 +9,26 @@ use Hypervel\Database\SQLiteConnection; use Hypervel\Filesystem\Filesystem; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Process\Process; class DatabaseSqliteSchemaStateTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('fileDatabaseProvider')] public function testLoadSchemaToDatabase(string $database): void { $config = ['driver' => 'sqlite', 'database' => $database, 'prefix' => '', 'foreign_key_constraints' => true, 'name' => 'sqlite']; - $connection = m::mock(SQLiteConnection::class); - $connection->expects('getConfig')->andReturn($config); - $connection->expects('getDatabaseName')->andReturn($config['database']); + $connection = Double::for(SQLiteConnection::class); + $connection->expects('getConfig')->returns($config); + $connection->expects('getDatabaseName')->returns($config['database']); - $process = m::spy(Process::class); + $process = Double::for(Process::class); $command = null; $processFactory = function (string $givenCommand) use ($process, &$command): Process { $command = $givenCommand; @@ -38,7 +41,7 @@ public function testLoadSchemaToDatabase(string $database): void $this->assertSame('sqlite3 "${:HYPERVEL_LOAD_DATABASE}" < "${:HYPERVEL_LOAD_PATH}"', $command); - $process->shouldHaveReceived('mustRun')->with(null, [ + $process->received('mustRun')->with(null, [ 'HYPERVEL_LOAD_DATABASE' => $database, 'HYPERVEL_LOAD_PATH' => 'database/schema/sqlite-schema.dump', ]); @@ -61,18 +64,19 @@ public static function fileDatabaseProvider(): array public function testLoadSchemaToInMemory(string $database): void { $config = ['driver' => 'sqlite', 'database' => $database, 'prefix' => '', 'foreign_key_constraints' => true, 'name' => 'sqlite']; - $connection = m::mock(SQLiteConnection::class); - $connection->expects('getDatabaseName')->andReturn($config['database']); - $pdo = m::spy(PDO::class); - $connection->expects('getPdo')->andReturn($pdo); + $connection = Double::for(SQLiteConnection::class); + $connection->expects('getDatabaseName')->returns($config['database']); + $pdo = Double::for(PDO::class); + $pdo->expects('exec')->returns(0); + $connection->expects('getPdo')->returns($pdo); - $files = m::mock(Filesystem::class); - $files->expects('get')->andReturn('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); + $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);'); $schemaState = new SqliteSchemaState($connection, $files); $schemaState->load('database/schema/sqlite-schema.dump'); - $pdo->shouldHaveReceived('exec')->with('CREATE TABLE IF NOT EXISTS "migrations" ("id" integer not null primary key autoincrement, "migration" varchar not null, "batch" integer not null);'); + $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);'); } /** @@ -91,10 +95,10 @@ public static function inMemoryDatabaseProvider(): array public function testLoadSchemaToInMemoryRequiresPdoConnection(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getDatabaseName')->once()->andReturn(':memory:'); + $connection = Double::for(Connection::class); + $connection->expects('getDatabaseName')->returns(':memory:'); - $schemaState = new SqliteSchemaState($connection, m::mock(Filesystem::class)); + $schemaState = new SqliteSchemaState($connection, Double::for(Filesystem::class)); $this->expectException(LogicException::class); $this->expectExceptionMessageIs('In-memory SQLite schema loading requires a PDO-backed connection.'); @@ -102,7 +106,7 @@ public function testLoadSchemaToInMemoryRequiresPdoConnection(): void $schemaState->load('database/schema/sqlite-schema.dump'); } - public function testDumpWritesStoredStatementsWithoutInternalOrShadowTables(): void + public function testDumpRemovesShadowTables(): void { $connection = new SQLiteConnection(new PDO('sqlite::memory:'), config: ['database' => ':memory:']); $connection->statement('create virtual table posts using fts5(body)'); @@ -116,14 +120,14 @@ public function testDumpWritesStoredStatementsWithoutInternalOrShadowTables(): v $connection->statement('create index examples_body_index on examples (body)'); $connection->statement('create virtual table temp.logs using fts5(message)'); - $files = m::spy(Filesystem::class); + $files = Double::for(Filesystem::class); (new SqliteSchemaState($connection, $files)) ->withMigrationTable(null) ->dump($connection, 'schema.sql'); // Literals that look like removed statements are kept, and a quoted table name gets IF NOT EXISTS, as in .schema. - $files->shouldHaveReceived('put')->with('schema.sql', <<<'SQL' + $files->received('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); diff --git a/tests/Database/DatabaseTransactionsTest.php b/tests/Database/DatabaseTransactionsTest.php index 68839626d..b73bf433c 100644 --- a/tests/Database/DatabaseTransactionsTest.php +++ b/tests/Database/DatabaseTransactionsTest.php @@ -6,17 +6,23 @@ use Exception; use Hypervel\Database\Capsule\Manager as DB; +use Hypervel\Database\Connection; use Hypervel\Database\DatabaseManager; use Hypervel\Database\DatabaseTransactionsManager; +use Hypervel\Database\Schema\Builder; use Hypervel\Foundation\Testing\DatabaseTransactionsManager as TestingTransactionsManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PDOException; use RuntimeException; use Throwable; class DatabaseTransactionsTest extends TestCase { + use VerifiesDoubles; + /** * Setup the database schema. */ @@ -67,7 +73,7 @@ protected function tearDown(): void public function testTransactionIsRecordedAndCommitted(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $transactionManager->expects('begin')->with('default', 1); $transactionManager->expects('commit')->with('default', 1, 0); @@ -86,7 +92,7 @@ public function testTransactionIsRecordedAndCommitted(): void public function testTransactionIsRecordedAndCommittedUsingTheSeparateMethods(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $transactionManager->expects('begin')->with('default', 1); $transactionManager->expects('commit')->with('default', 1, 0); @@ -105,7 +111,7 @@ public function testTransactionIsRecordedAndCommittedUsingTheSeparateMethods(): public function testNestedTransactionIsRecordedAndCommitted(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $transactionManager->expects('begin')->with('default', 1); $transactionManager->expects('begin')->with('default', 2); $transactionManager->expects('commit')->with('default', 2, 1); @@ -132,7 +138,7 @@ public function testNestedTransactionIsRecordedAndCommitted(): void public function testNestedTransactionIsRecordeForDifferentConnectionsdAndCommitted(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $transactionManager->expects('begin')->with('default', 1); $transactionManager->expects('begin')->with('second_connection', 1); $transactionManager->expects('begin')->with('second_connection', 2); @@ -168,10 +174,10 @@ public function testNestedTransactionIsRecordeForDifferentConnectionsdAndCommitt public function testTransactionIsRolledBack(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $transactionManager->expects('begin')->with('default', 1); $transactionManager->expects('rollback')->with('default', 0); - $transactionManager->shouldNotReceive('commit'); + $transactionManager->expects('commit')->never(); $this->connection()->setTransactionManager($transactionManager); @@ -225,10 +231,10 @@ public function testFailedCommitRollsBackTheTransactionsManager(): void public function testTransactionIsRolledBackUsingSeparateMethods(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $transactionManager->expects('begin')->with('default', 1); $transactionManager->expects('rollback')->with('default', 0); - $transactionManager->shouldNotReceive('commit'); + $transactionManager->expects('commit')->never(); $this->connection()->setTransactionManager($transactionManager); @@ -247,12 +253,12 @@ public function testTransactionIsRolledBackUsingSeparateMethods(): void public function testNestedTransactionsAreRolledBack(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $transactionManager->expects('begin')->with('default', 1); $transactionManager->expects('begin')->with('default', 2); $transactionManager->expects('rollback')->with('default', 1); $transactionManager->expects('rollback')->with('default', 0); - $transactionManager->shouldNotReceive('commit'); + $transactionManager->expects('commit')->never(); $this->connection()->setTransactionManager($transactionManager); @@ -280,13 +286,12 @@ public function testNestedTransactionsAreRolledBack(): void public function testAfterCommitRegistersTheCurrentConnectionName(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $callback = static function (): void { }; - $transactionManager->shouldReceive('addCallback') - ->once() - ->with($callback, 'second_connection'); + $transactionManager->expects('addCallback') + ->with(Argument::same($callback), 'second_connection'); $this->connection('second_connection')->setTransactionManager($transactionManager); $this->connection('second_connection')->afterCommit($callback); @@ -321,9 +326,9 @@ public function testApplicableTransactionsExcludeTestWrappersButIncludeApplicati $manager = new TestingTransactionsManager(['default', 'second_connection']); $first = $this->connection(); $second = $this->connection('second_connection'); - $database = m::mock(DatabaseManager::class); - $database->shouldReceive('connection')->once()->with('default')->andReturn($first); - $database->shouldReceive('connection')->once()->with('second_connection')->andReturn($second); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with('default')->returns($first); + $database->expects('connection')->with('second_connection')->returns($second); $manager->beginTransactions($database); try { @@ -376,13 +381,12 @@ public function testAfterCommitOrNowRunsImmediatelyWithoutAManagerOrTransaction( public function testAfterCommitOrNowDelegatesToTheTransactionManager(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $callback = static function (): void { }; - $transactionManager->shouldReceive('addCallback') - ->once() - ->with($callback, 'second_connection'); + $transactionManager->expects('addCallback') + ->with(Argument::same($callback), 'second_connection'); $this->connection('second_connection')->setTransactionManager($transactionManager); $this->connection('second_connection')->afterCommitOrNow($callback); @@ -406,13 +410,12 @@ public function testAfterCommitOrNowRequiresAManagerDuringATransaction(): void public function testAfterRollbackRegistersTheCurrentConnectionName(): void { - $transactionManager = m::mock(new DatabaseTransactionsManager); + $transactionManager = Double::for(new DatabaseTransactionsManager); $callback = static function (): void { }; - $transactionManager->shouldReceive('addCallbackForRollback') - ->once() - ->with($callback, 'second_connection'); + $transactionManager->expects('addCallbackForRollback') + ->with(Argument::same($callback), 'second_connection'); $this->connection('second_connection')->setTransactionManager($transactionManager); $this->connection('second_connection')->afterRollBack($callback); @@ -439,12 +442,12 @@ public function testAfterRollbackRequiresATransactionManager(): void /** * Get a schema builder instance. */ - protected function schema(string $connection = 'default'): \Hypervel\Database\Schema\Builder + protected function schema(string $connection = 'default'): Builder { return $this->connection($connection)->getSchemaBuilder(); } - public function connection(string $name = 'default'): \Hypervel\Database\Connection + public function connection(string $name = 'default'): Connection { return DB::connection($name); } diff --git a/tests/Database/DatabaseWipeCommandTest.php b/tests/Database/DatabaseWipeCommandTest.php index cb2c9eed1..ef5ab9a91 100644 --- a/tests/Database/DatabaseWipeCommandTest.php +++ b/tests/Database/DatabaseWipeCommandTest.php @@ -5,7 +5,6 @@ namespace Hypervel\Tests\Database; use Hypervel\Config\Repository; -use Hypervel\Console\CommandMutex; use Hypervel\Context\CoroutineContext; use Hypervel\Database\ConnectionResolver; use Hypervel\Database\Console\WipeCommand; @@ -185,10 +184,6 @@ class ApplicationDatabaseWipeStub extends Application { public function __construct(array $data = []) { - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); - $mutex->shouldReceive('release')->andReturn(true); - $this->instance(CommandMutex::class, $mutex); $this->instance('env', 'development'); foreach ($data as $abstract => $instance) { diff --git a/tests/Database/MigratorTest.php b/tests/Database/MigratorTest.php index 1943e25c2..67f333a17 100644 --- a/tests/Database/MigratorTest.php +++ b/tests/Database/MigratorTest.php @@ -10,14 +10,15 @@ use Hypervel\Database\Schema\Blueprint; use Hypervel\Support\Facades\DB; use Hypervel\Support\Facades\Schema; -use Hypervel\Support\Stringable; use Hypervel\Testbench\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Output\BufferedOutput; class MigratorTest extends TestCase { - private OutputStyle&MockInterface $output; + private BufferedOutput $output; + + private array $expectedLines = []; public Migrator $subject; @@ -39,10 +40,9 @@ protected function defineEnvironment(Application $app): void */ protected function setUpInCoroutine(): void { - $this->output = m::mock(OutputStyle::class); - $this->output->shouldReceive('newLinesWritten')->andReturn(0); + $this->output = new BufferedOutput; $this->subject = $this->app->make('migrator'); - $this->subject->setOutput($this->output); + $this->subject->setOutput(new OutputStyle(new ArrayInput([]), $this->output)); $this->subject->getRepository()->createRepository(); } @@ -55,9 +55,8 @@ public function testMigrate(): void $this->expectTask('2016_10_04_000000_modify_people_table', 'DONE'); $this->expectTask('2017_10_04_000000_add_age_to_people', 'SKIPPED'); - $this->output->expects('writeln'); - $this->subject->run([__DIR__ . '/Fixtures/Migrator']); + $this->assertExpectedOutput(); $this->assertTrue(DB::getSchemaBuilder()->hasTable('people')); $this->assertTrue(DB::getSchemaBuilder()->hasColumn('people', 'first_name')); @@ -71,6 +70,7 @@ public function testMigrateWithoutOutput(): void $this->subject = $this->app->make('migrator'); $this->subject->run([__DIR__ . '/Fixtures/Migrator']); + $this->assertExpectedOutput(); $this->assertTrue(DB::getSchemaBuilder()->hasTable('people')); $this->assertTrue(DB::getSchemaBuilder()->hasColumn('people', 'first_name')); @@ -86,12 +86,14 @@ public function testWithSkippedMigrations(): void Migrator::withoutMigrations(['2015_10_04_000000_modify_people_table.php', '2016_10_04_000000_modify_people_table']); $this->subject->run([__DIR__ . '/Fixtures/Migrator']); + $this->assertExpectedOutput(); $this->assertTrue(DB::getSchemaBuilder()->hasTable('people')); $this->assertFalse(DB::getSchemaBuilder()->hasColumn('people', 'first_name')); $this->assertFalse(DB::getSchemaBuilder()->hasColumn('people', 'last_name')); Migrator::withoutMigrations([]); $this->subject->run([__DIR__ . '/Fixtures/Migrator']); + $this->assertExpectedOutput(); $this->assertTrue(DB::getSchemaBuilder()->hasColumn('people', 'first_name')); $this->assertTrue(DB::getSchemaBuilder()->hasColumn('people', 'last_name')); } @@ -115,9 +117,8 @@ public function testRollback(): void $this->expectTask('2015_10_04_000000_modify_people_table', 'DONE'); $this->expectTask('2014_10_12_000000_create_people_table', 'DONE'); - $this->output->expects('writeln'); - $this->subject->rollback([__DIR__ . '/Fixtures/Migrator']); + $this->assertExpectedOutput(); $this->assertFalse(DB::getSchemaBuilder()->hasTable('people')); } @@ -138,9 +139,8 @@ public function testPretendMigrate(): void $this->expectTwoColumnDetail('2016_10_04_000000_modify_people_table'); $this->expectBulletList(['alter table "people" add column "last_name" varchar']); - $this->output->expects('writeln')->times(3); - $this->subject->run([__DIR__ . '/Fixtures/Migrator'], ['pretend' => true]); + $this->assertExpectedOutput(); $this->assertFalse(DB::getSchemaBuilder()->hasTable('people')); } @@ -218,9 +218,8 @@ public function testIgnorePretendModeForCallbackOutputDynamicContentIsShown(): v $this->expectInfo('Running migrations.'); $this->expectTask('2014_10_12_000000_create_people_is_dynamic_table', 'DONE'); - $this->output->expects('writeln'); - $this->subject->run([__DIR__ . '/Fixtures/Migrator/pretending/2014_10_12_000000_create_people_is_dynamic_table.php'], ['pretend' => false]); + $this->assertExpectedOutput(); $this->assertTrue(DB::getSchemaBuilder()->hasTable('people')); @@ -236,9 +235,8 @@ public function testIgnorePretendModeForCallbackOutputDynamicContentIsShown(): v 'insert into "blogs" ("id", "name") values (2, \'John Doe Blog\')', ]); - $this->output->expects('writeln'); - $this->subject->run([__DIR__ . '/Fixtures/Migrator/pretending/2023_10_17_000000_dynamic_content_is_shown.php'], ['pretend' => true]); + $this->assertExpectedOutput(); $this->assertFalse(DB::getSchemaBuilder()->hasTable('blogs')); @@ -251,9 +249,8 @@ public function testIgnorePretendModeForCallbackOutputDynamicContentNotShown(): $this->expectInfo('Running migrations.'); $this->expectTask('2014_10_12_000000_create_people_non_dynamic_table', 'DONE'); - $this->output->expects('writeln'); - $this->subject->run([__DIR__ . '/Fixtures/Migrator/pretending/2014_10_12_000000_create_people_non_dynamic_table.php'], ['pretend' => false]); + $this->assertExpectedOutput(); $this->assertTrue(DB::getSchemaBuilder()->hasTable('people')); @@ -267,9 +264,8 @@ public function testIgnorePretendModeForCallbackOutputDynamicContentNotShown(): 'select * from "people"', ]); - $this->output->expects('writeln'); - $this->subject->run([__DIR__ . '/Fixtures/Migrator/pretending/2023_10_17_000000_dynamic_content_not_shown.php'], ['pretend' => true]); + $this->assertExpectedOutput(); $this->assertFalse(DB::getSchemaBuilder()->hasTable('blogs')); @@ -281,9 +277,7 @@ public function testIgnorePretendModeForCallbackOutputDynamicContentNotShown(): */ protected function expectInfo(string $message): void { - $this->output->expects('writeln')->with(m::on( - fn (string $argument): bool => (new Stringable($argument))->contains($message), - ), m::any()); + $this->expectedLines[] = $message; } /** @@ -291,15 +285,11 @@ protected function expectInfo(string $message): void */ protected function expectTwoColumnDetail(string $first, ?string $second = null): void { - $this->output->expects('writeln')->with(m::on(function (string $argument) use ($first, $second): bool { - $result = (new Stringable($argument))->contains($first); + $this->expectedLines[] = $first; - if ($result && $second) { - $result = (new Stringable($argument))->contains($second); - } - - return $result; - }), m::any()); + if ($second) { + $this->expectedLines[] = $second; + } } /** @@ -309,9 +299,9 @@ protected function expectTwoColumnDetail(string $first, ?string $second = null): */ protected function expectBulletList(array $elements): void { - $this->output->expects('writeln')->with(m::on(function (string $argument) use ($elements): bool { - return array_all($elements, fn (string $element): bool => (new Stringable($argument))->contains("⇂ {$element}")); - }), m::any()); + foreach ($elements as $element) { + $this->expectedLines[] = "⇂ {$element}"; + } } /** @@ -319,22 +309,21 @@ protected function expectBulletList(array $elements): void */ protected function expectTask(string $description, string $result): void { - // Ignore dots... - $this->output->expects('write')->with(m::on( - fn (string $argument): bool => (new Stringable($argument))->contains(['', '.']), - ), m::any(), m::any()); - - // Ignore duration... - $this->output->expects('write')->with(m::on( - fn (string $argument): bool => str_starts_with($argument, ' ') && str_ends_with($argument, ''), - ), m::any(), m::any()); - - $this->output->expects('write')->with(m::on( - fn (string $argument): bool => (new Stringable($argument))->contains($description), - ), m::any(), m::any()); - - $this->output->expects('writeln')->with(m::on( - fn (string $argument): bool => (new Stringable($argument))->contains($result), - ), m::any()); + $this->expectedLines[] = $description; + $this->expectedLines[] = $result; + } + + /** + * Assert the buffered output contains every expected line. + */ + protected function assertExpectedOutput(): void + { + $output = $this->output->fetch(); + + foreach ($this->expectedLines as $expected) { + $this->assertStringContainsString($expected, $output); + } + + $this->expectedLines = []; } } diff --git a/tests/Database/PruneCommandTest.php b/tests/Database/PruneCommandTest.php index 8f59dc776..bbdf13d1d 100644 --- a/tests/Database/PruneCommandTest.php +++ b/tests/Database/PruneCommandTest.php @@ -5,7 +5,6 @@ namespace Hypervel\Tests\Database; use Closure; -use Hypervel\Console\CommandMutex; use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; use Hypervel\Database\Capsule\Manager as DB; use Hypervel\Database\Console\PruneCommand; @@ -22,7 +21,6 @@ use Hypervel\Tests\Database\Fixtures\Pruning\Models\PrunableTestSoftDeletedModelWithPrunableRecords; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; @@ -48,10 +46,6 @@ protected function setUp(): void $container->alias(DispatcherContract::class, 'events'); - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); - $mutex->shouldReceive('release')->andReturn(true); - $container->instance(CommandMutex::class, $mutex); $container->instance('env', 'development'); } @@ -76,6 +70,7 @@ public function testPrunableModelWithPrunableRecords(): void $output, ); + // Hypervel reports the final total without installing temporary event listeners. $this->assertStringContainsString( '20 records', $output, @@ -279,14 +274,18 @@ public function testTheCommandDispatchesEvents(): void $startingEvents = []; $prunedEvents = []; $finishedEvents = []; - $events->listen(ModelPruningStarting::class, static function (ModelPruningStarting $event) use (&$startingEvents): void { + $eventOrder = []; + $events->listen(ModelPruningStarting::class, static function (ModelPruningStarting $event) use (&$startingEvents, &$eventOrder): void { $startingEvents[] = $event; + $eventOrder[] = $event::class; }); - $events->listen(ModelsPruned::class, static function (ModelsPruned $event) use (&$prunedEvents): void { + $events->listen(ModelsPruned::class, static function (ModelsPruned $event) use (&$prunedEvents, &$eventOrder): void { $prunedEvents[] = $event; + $eventOrder[] = $event::class; }); - $events->listen(ModelPruningFinished::class, static function (ModelPruningFinished $event) use (&$finishedEvents): void { + $events->listen(ModelPruningFinished::class, static function (ModelPruningFinished $event) use (&$finishedEvents, &$eventOrder): void { $finishedEvents[] = $event; + $eventOrder[] = $event::class; }); $this->artisan(['--model' => PrunableTestModelWithPrunableRecords::class]); @@ -297,6 +296,10 @@ public function testTheCommandDispatchesEvents(): void $this->assertCount(2, $startingEvents); $this->assertCount(4, $prunedEvents); $this->assertCount(2, $finishedEvents); + $this->assertSame([ + ModelPruningStarting::class, ModelsPruned::class, ModelsPruned::class, ModelPruningFinished::class, + ModelPruningStarting::class, ModelsPruned::class, ModelsPruned::class, ModelPruningFinished::class, + ], $eventOrder); $this->assertSame([10, 20, 10, 20], array_column($prunedEvents, 'count')); $this->assertSame( [PrunableTestModelWithPrunableRecords::class], diff --git a/tests/Database/SeedCommandTest.php b/tests/Database/SeedCommandTest.php index cd14affdb..a2c28aad6 100644 --- a/tests/Database/SeedCommandTest.php +++ b/tests/Database/SeedCommandTest.php @@ -4,8 +4,8 @@ namespace Hypervel\Tests\Database; +use Hypervel\Config\Repository; use Hypervel\Console\Command; -use Hypervel\Console\CommandMutex; use Hypervel\Context\CoroutineContext; use Hypervel\Database\ConnectionResolver; use Hypervel\Database\ConnectionResolverInterface; @@ -18,7 +18,8 @@ use Hypervel\Foundation\Application; use Hypervel\Testing\Assert; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\Console\Input\ArrayInput; @@ -27,6 +28,8 @@ class SeedCommandTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -34,19 +37,12 @@ protected function setUp(): void RecordsRootSeeder::$instances = []; } - protected function tearDown(): void - { - CoroutineContext::forget(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY); - - parent::tearDown(); - } - public function testHandle(): void { - $seeder = m::mock(Seeder::class); - $seeder->expects('setContainer')->andReturnSelf(); - $seeder->expects('setCommand')->andReturnSelf(); - $seeder->expects('__invoke')->andReturnUsing(function (): void { + $seeder = Double::for(Seeder::class); + $seeder->expects('setContainer')->returns($seeder); + $seeder->expects('setCommand')->returns($seeder); + $seeder->expects('__invoke')->resolves(function (): void { Assert::assertSame( 'sqlite', CoroutineContext::get(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY), @@ -54,7 +50,7 @@ public function testHandle(): void ); }); - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, @@ -79,7 +75,7 @@ public function testHandle(): void public function testReportsProgressForExplicitSeedersOnly(array $arguments, bool $reportsProgress): void { $seeder = new RecordsRootSeeder; - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, 'DatabaseSeeder' => $seeder, @@ -125,7 +121,7 @@ public static function seederProgressProvider(): array public function testRootSeederConstructorCanMassAssignModels(): void { - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $app = new ApplicationDatabaseSeedStub; $command = new SeedCommand($resolver); $command->setHypervel($app); @@ -142,7 +138,7 @@ public function testRootSeederConstructorCanMassAssignModels(): void public function testFailedSeederResolutionDoesNotReportProgress(): void { $exception = new RuntimeException('Seeder resolution failed'); - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $app = new ApplicationDatabaseSeedStub; $app->bind(RecordsRootSeeder::class, fn () => throw $exception); $command = new SeedCommand($resolver); @@ -173,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 = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, @@ -214,11 +210,11 @@ public function testWithoutModelEvents(): void { $instance = new UserWithoutModelEventsSeeder; - $seeder = m::mock($instance); - $seeder->expects('setContainer')->andReturnSelf(); - $seeder->expects('setCommand')->andReturnSelf(); + $seeder = Double::for($instance)->passthru(); + $seeder->expects('setContainer')->returns($seeder); + $seeder->expects('setCommand')->returns($seeder); - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, @@ -245,7 +241,7 @@ public function testWithoutModelEvents(): void public function testProhibitable(): void { - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, @@ -268,10 +264,10 @@ 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 = m::mock(Seeder::class); - $seeder->shouldReceive('setContainer')->once()->andReturnSelf(); - $seeder->shouldReceive('setCommand')->once()->andReturnSelf(); - $seeder->shouldReceive('__invoke')->once()->andReturnUsing(function (): void { + $seeder = Double::for(Seeder::class); + $seeder->expects('setContainer')->returns($seeder); + $seeder->expects('setCommand')->returns($seeder); + $seeder->expects('__invoke')->resolves(function (): void { Assert::assertSame( 'tenant_reporting', CoroutineContext::get(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY), @@ -279,8 +275,8 @@ public function testHandleWithoutDatabaseOptionUsesResolverDefault(): void ); }); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('getDefaultConnection')->once()->andReturn('tenant_reporting'); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('getDefaultConnection')->returns('tenant_reporting'); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, @@ -295,17 +291,17 @@ public function testHandleWithoutDatabaseOptionUsesResolverDefault(): void public function testHandlePreservesZeroDatabaseOption(): void { - $seeder = m::mock(Seeder::class); - $seeder->shouldReceive('setContainer')->once()->andReturnSelf(); - $seeder->shouldReceive('setCommand')->once()->andReturnSelf(); - $seeder->shouldReceive('__invoke')->once()->andReturnUsing(function (): void { + $seeder = Double::for(Seeder::class); + $seeder->expects('setContainer')->returns($seeder); + $seeder->expects('setCommand')->returns($seeder); + $seeder->expects('__invoke')->resolves(function (): void { Assert::assertSame( '0', CoroutineContext::get(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY), ); }); - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, @@ -323,18 +319,18 @@ public function testHandlePreservesZeroDatabaseOption(): void public function testHandleWithEmptyDatabaseOptionUsesResolverDefault(): void { - $seeder = m::mock(Seeder::class); - $seeder->shouldReceive('setContainer')->once()->andReturnSelf(); - $seeder->shouldReceive('setCommand')->once()->andReturnSelf(); - $seeder->shouldReceive('__invoke')->once()->andReturnUsing(function (): void { + $seeder = Double::for(Seeder::class); + $seeder->expects('setContainer')->returns($seeder); + $seeder->expects('setCommand')->returns($seeder); + $seeder->expects('__invoke')->resolves(function (): void { Assert::assertSame( 'tenant_reporting', CoroutineContext::get(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY), ); }); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('getDefaultConnection')->once()->andReturn('tenant_reporting'); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('getDefaultConnection')->returns('tenant_reporting'); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, @@ -354,14 +350,14 @@ public function testHandleDoesNotMutateConfigDatabaseDefault(): void { // Regression: db:seed must use Context, not config mutation. config // ('database.default') should be untouched after a seed run. - $seeder = m::mock(Seeder::class); - $seeder->shouldReceive('setContainer')->once()->andReturnSelf(); - $seeder->shouldReceive('setCommand')->once()->andReturnSelf(); - $seeder->shouldReceive('__invoke')->once(); + $seeder = Double::for(Seeder::class); + $seeder->expects('setContainer')->returns($seeder); + $seeder->expects('setCommand')->returns($seeder); + $seeder->expects('__invoke'); - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); - $config = new \Hypervel\Config\Repository(['database' => ['default' => 'pgsql']]); + $config = new Repository(['database' => ['default' => 'pgsql']]); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, @@ -386,7 +382,7 @@ public function testHandleDoesNotMutateConfigDatabaseDefault(): void public function testHandleResolvesAFreshUnboundRootSeederForEachRun(): void { - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $app = new ApplicationDatabaseSeedStub([ ConnectionResolverInterface::class => $resolver, @@ -416,10 +412,6 @@ class ApplicationDatabaseSeedStub extends Application { public function __construct(array $data = []) { - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->andReturn(true); - $mutex->shouldReceive('release')->andReturn(true); - $this->instance(CommandMutex::class, $mutex); $this->instance('env', 'development'); foreach ($data as $abstract => $instance) { @@ -442,6 +434,7 @@ class UserWithoutModelEventsSeeder extends Seeder public function run(): void { Assert::assertInstanceOf(NullDispatcher::class, Model::getEventDispatcher()); + Assert::assertSame('sqlite', CoroutineContext::get(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY)); } } diff --git a/tests/Events/BroadcastedEventsTest.php b/tests/Events/BroadcastedEventsTest.php index b56061de7..4541958c9 100644 --- a/tests/Events/BroadcastedEventsTest.php +++ b/tests/Events/BroadcastedEventsTest.php @@ -12,10 +12,15 @@ use Hypervel\Foundation\Events\Dispatchable; use Hypervel\Tests\Events\Fixtures\ExampleEvent; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use stdClass; class BroadcastedEventsTest extends TestCase { + use VerifiesDoubles; + /** * Create a dispatcher that exposes the protected broadcast check. */ @@ -48,11 +53,11 @@ public function testShouldBroadcastSuccess(): void public function testShouldBroadcastAsQueuedAndCallNormalListeners(): void { unset($_SERVER['__event.test']); - $container = m::mock(Container::class); - $d = new Dispatcher($container); - $broadcast = m::mock(BroadcastFactory::class); + $container = Double::for(Container::class, override: true); + $d = new Dispatcher($container->instance()); + $broadcast = Double::for(BroadcastFactory::class); $broadcast->expects('queue'); - $container->expects('make')->with(BroadcastFactory::class)->andReturn($broadcast); + $container->expects('make')->with(BroadcastFactory::class)->returns($broadcast); $d->listen(AlwaysBroadcastEvent::class, function (AlwaysBroadcastEvent $payload): void { $_SERVER['__event.test'] = $payload; @@ -85,11 +90,11 @@ public function testShouldBroadcastFail(): void public function testBroadcastWithMultipleChannels(): void { - $container = m::mock(Container::class); - $d = new Dispatcher($container); - $broadcast = m::mock(BroadcastFactory::class); + $container = Double::for(Container::class, override: true); + $d = new Dispatcher($container->instance()); + $broadcast = Double::for(BroadcastFactory::class); $broadcast->expects('queue'); - $container->expects('make')->with(BroadcastFactory::class)->andReturn($broadcast); + $container->expects('make')->with(BroadcastFactory::class)->returns($broadcast); $event = new class implements ShouldBroadcast { public function broadcastOn(): array @@ -103,11 +108,11 @@ public function broadcastOn(): array public function testBroadcastWithCustomConnectionName(): void { - $container = m::mock(Container::class); - $d = new Dispatcher($container); - $broadcast = m::mock(BroadcastFactory::class); + $container = Double::for(Container::class, override: true); + $d = new Dispatcher($container->instance()); + $broadcast = Double::for(BroadcastFactory::class); $broadcast->expects('queue'); - $container->expects('make')->with(BroadcastFactory::class)->andReturn($broadcast); + $container->expects('make')->with(BroadcastFactory::class)->returns($broadcast); $event = new class implements ShouldBroadcast { public string $connection = 'custom-connection'; @@ -123,11 +128,11 @@ public function broadcastOn(): array public function testBroadcastWithCustomEventName(): void { - $container = m::mock(Container::class); - $d = new Dispatcher($container); - $broadcast = m::mock(BroadcastFactory::class); + $container = Double::for(Container::class, override: true); + $d = new Dispatcher($container->instance()); + $broadcast = Double::for(BroadcastFactory::class); $broadcast->expects('queue'); - $container->expects('make')->with(BroadcastFactory::class)->andReturn($broadcast); + $container->expects('make')->with(BroadcastFactory::class)->returns($broadcast); $event = new class implements ShouldBroadcast { public function broadcastOn(): array @@ -146,11 +151,11 @@ public function broadcastAs(): string public function testBroadcastWithCustomPayload(): void { - $container = m::mock(Container::class); - $d = new Dispatcher($container); - $broadcast = m::mock(BroadcastFactory::class); + $container = Double::for(Container::class, override: true); + $d = new Dispatcher($container->instance()); + $broadcast = Double::for(BroadcastFactory::class); $broadcast->expects('queue'); - $container->expects('make')->with(BroadcastFactory::class)->andReturn($broadcast); + $container->expects('make')->with(BroadcastFactory::class)->returns($broadcast); $event = new class implements ShouldBroadcast { public string $customData = 'test-data'; @@ -172,24 +177,24 @@ public function broadcastWith(): array public function testEventBroadcastsUsingNamedArguments(): void { $container = new Container; - $broadcast = m::mock(BroadcastFactory::class); + $broadcast = Double::for(BroadcastFactory::class); $container->instance(BroadcastFactory::class, $broadcast); $originalContainer = Container::getInstance(); Container::setInstance($container); try { - $pendingBroadcast = m::mock(PendingBroadcast::class); + $pendingBroadcast = new PendingBroadcastWithoutDestructor(new Dispatcher, new stdClass); $broadcast->expects('event') - ->with(m::on(function (mixed $event): bool { + ->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; })) - ->andReturn($pendingBroadcast); + ->returns($pendingBroadcast); $this->assertSame( $pendingBroadcast, @@ -201,6 +206,16 @@ public function testEventBroadcastsUsingNamedArguments(): void } } +class PendingBroadcastWithoutDestructor extends PendingBroadcast +{ + /** + * Prevent the fixture event from being dispatched. + */ + public function __destruct() + { + } +} + class BroadcastEvent implements ShouldBroadcast { public function broadcastOn(): array diff --git a/tests/Events/EventsSubscriberTest.php b/tests/Events/EventsSubscriberTest.php index 7824ac1da..d9c0e4258 100644 --- a/tests/Events/EventsSubscriberTest.php +++ b/tests/Events/EventsSubscriberTest.php @@ -6,15 +6,19 @@ use Hypervel\Events\Dispatcher; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class EventsSubscriberTest extends TestCase { + use VerifiesDoubles; + public function testEventSubscribeCanAcceptObject(): void { $d = new Dispatcher; - $subs = m::mock(ExampleSubscriber::class); - $subs->expects('subscribe')->with($d); + $subs = Double::for(ExampleSubscriber::class); + $subs->expects('subscribe')->with(Argument::same($d)); $d->subscribe($subs); } diff --git a/tests/Events/QueuedEventsTest.php b/tests/Events/QueuedEventsTest.php index d5c22e398..aa62fcb67 100644 --- a/tests/Events/QueuedEventsTest.php +++ b/tests/Events/QueuedEventsTest.php @@ -9,6 +9,7 @@ use Hypervel\Bus\DebounceLock; use Hypervel\Bus\Dispatcher as BusDispatcher; use Hypervel\Bus\DispatchLockContext; +use Hypervel\Bus\UniqueLock; use Hypervel\Cache\ArrayStore; use Hypervel\Cache\Repository; use Hypervel\Container\Container; @@ -35,12 +36,16 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Laravel\SerializableClosure\SerializableClosure; use LogicException; -use Mockery as m; class QueuedEventsTest extends TestCase { + use VerifiesDoubles; + public function testQueuedEventHandlersAreQueued(): void { $d = new Dispatcher; @@ -112,11 +117,11 @@ public function testQueueIsSetByGetQueue(): void public function testQueueIsSetByGetConnection(): void { $d = new Dispatcher; - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); - $factory->expects('connection')->with('some_other_connection')->andReturn($queue); - $queue->expects('pushOn')->with(null, m::type(CallQueuedListener::class)); + $factory->expects('connection')->with('some_other_connection')->returns($queue); + $queue->expects('pushOn')->with(null, Argument::type(CallQueuedListener::class)); $d->setQueueResolver(function () use ($factory) { return $factory; @@ -129,11 +134,11 @@ public function testQueueIsSetByGetConnection(): void public function testEnumQueueAndConnectionResultsAreNormalizedBeforeDispatch(): void { $dispatcher = new Dispatcher; - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); - $factory->shouldReceive('connection')->once()->with('0')->andReturn($queue); - $queue->shouldReceive('pushOn')->once()->with('1', m::type(CallQueuedListener::class)); + $factory->expects('connection')->with('0')->returns($queue); + $queue->expects('pushOn')->with('1', Argument::type(CallQueuedListener::class)); $dispatcher->setQueueResolver(fn () => $factory); $dispatcher->listen('some.event', TestDispatcherGetEnumQueueAndConnection::class . '@handle'); @@ -143,11 +148,11 @@ public function testEnumQueueAndConnectionResultsAreNormalizedBeforeDispatch(): public function testDelayIsSetByWithDelay(): void { $d = new Dispatcher; - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); - $factory->expects('connection')->with(null)->andReturn($queue); - $queue->expects('laterOn')->with(null, 20, m::type(CallQueuedListener::class)); + $factory->expects('connection')->with(null)->returns($queue); + $queue->expects('laterOn')->with(null, 20, Argument::type(CallQueuedListener::class)); $d->setQueueResolver(function () use ($factory) { return $factory; @@ -160,11 +165,11 @@ public function testDelayIsSetByWithDelay(): void public function testDelayIsSetByAttribute(): void { $d = new Dispatcher; - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); - $factory->shouldReceive('connection')->once()->with(null)->andReturn($queue); - $queue->shouldReceive('laterOn')->once()->with(null, 30, m::type(CallQueuedListener::class)); + $factory->expects('connection')->with(null)->returns($queue); + $queue->expects('laterOn')->with(null, 30, Argument::type(CallQueuedListener::class)); $d->setQueueResolver(function () use ($factory) { return $factory; @@ -177,11 +182,11 @@ public function testDelayIsSetByAttribute(): void public function testWithDelayOverridesDelayAttribute(): void { $d = new Dispatcher; - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); - $factory->shouldReceive('connection')->once()->with(null)->andReturn($queue); - $queue->shouldReceive('laterOn')->once()->with(null, 20, m::type(CallQueuedListener::class)); + $factory->expects('connection')->with(null)->returns($queue); + $queue->expects('laterOn')->with(null, 20, Argument::type(CallQueuedListener::class)); $d->setQueueResolver(function () use ($factory) { return $factory; @@ -242,11 +247,10 @@ public function testQueueIsSetUsingQueueRoutes(): void $queueRoutes->set(TestDispatcherQueueRoutes::class, 'event-queue', 'event-connection'); $container->instance('queue.routes', $queueRoutes); - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = new QueueFake($container); - $factory->shouldReceive('connection')->once()->with('event-connection')->andReturn($queue); - $queue->shouldReceive('pushOn')->once()->with('event-queue', m::type(CallQueuedListener::class)); + $factory->expects('connection')->with('event-connection')->returns($queue); Container::setInstance($container); @@ -256,6 +260,9 @@ public function testQueueIsSetUsingQueueRoutes(): void $d->listen('some.event', TestDispatcherQueueRoutes::class . '@handle'); $d->dispatch('some.event', ['foo', 'bar']); + + $queue->assertPushedOnce(CallQueuedListener::class); + $queue->assertPushedOn('event-queue', CallQueuedListener::class); } public function testConnectionIsSetUsingForwardedQueue(): void @@ -267,15 +274,17 @@ public function testConnectionIsSetUsingForwardedQueue(): void $queueRoutes->forward('reports', 'processing', 'cloud'); $container->instance('queue.routes', $queueRoutes); - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); - $factory->shouldReceive('connection')->once()->with('cloud')->andReturn($queue); - $queue->shouldReceive('pushOn')->once()->with('reports', m::type(CallQueuedListener::class)); + $factory = Double::for(QueueFactory::class); + $queue = new QueueFake($container); + $factory->expects('connection')->with('cloud')->returns($queue); Container::setInstance($container); $d->setQueueResolver(fn (): QueueFactory => $factory); $d->listen('some.event', TestDispatcherForwardedQueue::class . '@handle'); $d->dispatch('some.event', ['foo', 'bar']); + + $queue->assertPushedOnce(CallQueuedListener::class); + $queue->assertPushedOn('reports', CallQueuedListener::class); } public function testForwardedConnectionUsesTheDynamicallySelectedQueue(): void @@ -286,10 +295,10 @@ public function testForwardedConnectionUsesTheDynamicallySelectedQueue(): void $routes->forward('my_queue', 'unused', 'wrong-connection'); $routes->forward('some_other_queue', 'processing', 'cloud'); $container->instance('queue.routes', $routes); - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); - $factory->shouldReceive('connection')->once()->with('cloud')->andReturn($queue); - $queue->shouldReceive('pushOn')->once()->with('some_other_queue', m::type(CallQueuedListener::class)); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); + $factory->expects('connection')->with('cloud')->returns($queue); + $queue->expects('pushOn')->with('some_other_queue', Argument::type(CallQueuedListener::class)); $dispatcher->setQueueResolver(fn (): QueueFactory => $factory); $dispatcher->listen('some.event', TestDispatcherGetQueue::class . '@handle'); @@ -299,11 +308,11 @@ public function testForwardedConnectionUsesTheDynamicallySelectedQueue(): void public function testDelayIsSetByWithDelayDynamically(): void { $d = new Dispatcher; - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); - $factory->expects('connection')->with(null)->andReturn($queue); - $queue->expects('laterOn')->with(null, 60, m::type(CallQueuedListener::class)); + $factory->expects('connection')->with(null)->returns($queue); + $queue->expects('laterOn')->with(null, 60, Argument::type(CallQueuedListener::class)); $d->setQueueResolver(function () use ($factory) { return $factory; @@ -517,15 +526,15 @@ public function testQueuePropagatesShouldBeUnique(): void $d = new Dispatcher($container); $fakeQueue = new QueueFake($container); - $cache = m::mock(Cache::class); - $lock = m::mock(Lock::class); + $cache = Double::for(Cache::class, LockProvider::class); + $lock = Double::for(Lock::class); $container->instance(Cache::class, $cache); - $cache->expects('getStore')->andReturn(m::mock(CacheStore::class, LockProvider::class)); - $cache->expects('lock')->andReturn($lock); - $lock->expects('get')->andReturn(true); - $lock->expects('owner')->andReturn('unique-lock-owner'); + $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)); + $cache->expects('lock')->returns($lock); + $lock->expects('get')->returns(true); + $lock->expects('owner')->returns('unique-lock-owner'); $d->setQueueResolver(function () use ($fakeQueue) { return $fakeQueue; @@ -548,14 +557,14 @@ public function testUniqueListenerNotQueuedWhenLockNotAcquired(): void $d = new Dispatcher($container); $fakeQueue = new QueueFake($container); - $cache = m::mock(Cache::class); - $lock = m::mock(Lock::class); + $cache = Double::for(Cache::class, LockProvider::class); + $lock = Double::for(Lock::class); $container->instance(Cache::class, $cache); - $cache->expects('getStore')->andReturn(m::mock(CacheStore::class, LockProvider::class)); - $cache->expects('lock')->andReturn($lock); - $lock->expects('get')->andReturn(false); + $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)); + $cache->expects('lock')->returns($lock); + $lock->expects('get')->returns(false); $d->setQueueResolver(function () use ($fakeQueue) { return $fakeQueue; @@ -573,15 +582,15 @@ public function testQueuePropagatesShouldBeUniqueUntilProcessing(): void $d = new Dispatcher($container); $fakeQueue = new QueueFake($container); - $cache = m::mock(Cache::class); - $lock = m::mock(Lock::class); + $cache = Double::for(Cache::class, LockProvider::class); + $lock = Double::for(Lock::class); $container->instance(Cache::class, $cache); - $cache->expects('getStore')->andReturn(m::mock(CacheStore::class, LockProvider::class)); - $cache->expects('lock')->andReturn($lock); - $lock->expects('get')->andReturn(true); - $lock->expects('owner')->andReturn('unique-lock-owner'); + $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)); + $cache->expects('lock')->returns($lock); + $lock->expects('get')->returns(true); + $lock->expects('owner')->returns('unique-lock-owner'); $d->setQueueResolver(function () use ($fakeQueue) { return $fakeQueue; @@ -602,15 +611,15 @@ public function testQueuePropagatesUniqueIdFromMethod(): void $d = new Dispatcher($container); $fakeQueue = new QueueFake($container); - $cache = m::mock(Cache::class); - $lock = m::mock(Lock::class); + $cache = Double::for(Cache::class, LockProvider::class); + $lock = Double::for(Lock::class); $container->instance(Cache::class, $cache); - $cache->expects('getStore')->andReturn(m::mock(CacheStore::class, LockProvider::class)); - $cache->expects('lock')->andReturn($lock); - $lock->expects('get')->andReturn(true); - $lock->expects('owner')->andReturn('unique-lock-owner'); + $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)); + $cache->expects('lock')->returns($lock); + $lock->expects('get')->returns(true); + $lock->expects('owner')->returns('unique-lock-owner'); $d->setQueueResolver(function () use ($fakeQueue) { return $fakeQueue; @@ -633,7 +642,7 @@ public function testUniqueLockKeyUsesListenerClassName(): void $this->assertSame(TestDispatcherShouldBeUnique::class, $listener->displayName()); $this->assertSame( 'laravel_unique_job:' . hash('xxh128', TestDispatcherShouldBeUnique::class) . ':test-id', - \Hypervel\Bus\UniqueLock::getKey($listener) + UniqueLock::getKey($listener) ); } @@ -643,8 +652,8 @@ public function testUniqueLockIsAcquiredWithListenerClassName(): void $d = new Dispatcher($container); $fakeQueue = new QueueFake($container); - $cache = m::mock(Cache::class); - $lock = m::mock(Lock::class); + $cache = Double::for(Cache::class, LockProvider::class); + $lock = Double::for(Lock::class); $container->instance(Cache::class, $cache); @@ -652,10 +661,10 @@ public function testUniqueLockIsAcquiredWithListenerClassName(): void $cache->expects('lock') ->with($expectedKey, 60) - ->andReturn($lock); - $cache->expects('getStore')->andReturn(m::mock(CacheStore::class, LockProvider::class)); - $lock->expects('get')->andReturn(true); - $lock->expects('owner')->andReturn('unique-lock-owner'); + ->returns($lock); + $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)); + $lock->expects('get')->returns(true); + $lock->expects('owner')->returns('unique-lock-owner'); $d->setQueueResolver(function () use ($fakeQueue) { return $fakeQueue; @@ -673,13 +682,13 @@ public function testUniqueViaUsesListenerCacheRepository(): void $d = new Dispatcher($container); $fakeQueue = new QueueFake($container); - $defaultCache = m::mock(Cache::class); - $uniqueCache = m::mock(Cache::class); - $lock = m::mock(Lock::class); + $defaultCache = Double::for(Cache::class, LockProvider::class); + $uniqueCache = Double::for(Cache::class, LockProvider::class); + $lock = Double::for(Lock::class); $container->instance(Cache::class, $defaultCache); - $defaultCache->shouldNotReceive('lock'); + $defaultCache->expects('lock')->never(); TestDispatcherShouldBeUniqueWithCustomCache::$cache = $uniqueCache; @@ -687,10 +696,10 @@ public function testUniqueViaUsesListenerCacheRepository(): void $uniqueCache->expects('lock') ->with($expectedKey, 60) - ->andReturn($lock); - $uniqueCache->expects('getStore')->andReturn(m::mock(CacheStore::class, LockProvider::class)); - $lock->expects('get')->andReturn(true); - $lock->expects('owner')->andReturn('unique-lock-owner'); + ->returns($lock); + $uniqueCache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)); + $lock->expects('get')->returns(true); + $lock->expects('owner')->returns('unique-lock-owner'); $d->setQueueResolver(function () use ($fakeQueue) { return $fakeQueue; @@ -705,8 +714,8 @@ public function testUniqueViaUsesListenerCacheRepository(): void public function testUniqueLockIsReleasedOnProcessingWithListenerClassName(): void { $container = new Container; - $cache = m::mock(Cache::class); - $lock = m::mock(Lock::class); + $cache = Double::for(Cache::class, LockProvider::class); + $lock = Double::for(Lock::class); $container->instance(Cache::class, $cache); $container->instance(BusDispatcher::class, new BusDispatcher($container)); @@ -720,7 +729,7 @@ public function testUniqueLockIsReleasedOnProcessingWithListenerClassName(): voi $cache->expects('lock') ->with($expectedKey) - ->andReturn($lock); + ->returns($lock); $lock->expects('forceRelease'); $job = new FakeJob; @@ -791,14 +800,14 @@ public function testExplicitListenerDelayTakesPrecedenceOverDebounceDelay(): voi { $container = new Container; $dispatcher = new Dispatcher($container); - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); $cache = new Repository(new ArrayStore); $container->instance(Cache::class, $cache); - $factory->expects('connection')->with(null)->andReturn($queue); - $queue->expects('laterOn')->with(null, 20, m::on(function (CallQueuedListener $job) use ($cache): bool { + $factory->expects('connection')->with(null)->returns($queue); + $queue->expects('laterOn')->with(null, 20, Argument::satisfies(function (CallQueuedListener $job) use ($cache): bool { $expectedKey = 'laravel_debounced_job:' . hash('xxh128', TestDispatcherDebouncedHandlerWithDelay::class) . ':event-123'; return $job->debounceOwner !== '' @@ -816,19 +825,19 @@ public function testDebouncedListenerMaxWaitForcesImmediateExecution(): void $container = new Container; $dispatcher = new Dispatcher($container); - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); $cache = new Repository(new ArrayStore); $container->instance(Cache::class, $cache); - $factory->expects('connection')->twice()->with(null)->andReturn($queue); - $queue->expects('laterOn')->with(null, 30, m::on(function (CallQueuedListener $job): bool { + $factory->expects('connection')->times(2)->with(null)->returns($queue); + $queue->expects('laterOn')->with(null, 30, Argument::satisfies(function (CallQueuedListener $job): bool { DispatchLockContext::accept($job); return true; }))->ordered(); - $queue->expects('laterOn')->with(null, 0, m::on(function (CallQueuedListener $job): bool { + $queue->expects('laterOn')->with(null, 0, Argument::satisfies(function (CallQueuedListener $job): bool { DispatchLockContext::accept($job); return true; @@ -874,10 +883,10 @@ public function testDebouncedListenerCannotAlsoBeUnique(): void $container = new Container; $dispatcher = new Dispatcher($container); $queue = new QueueFake($container); - $cache = m::mock(Cache::class); + $cache = Double::for(Cache::class, LockProvider::class); - $cache->shouldNotReceive('put'); - $cache->shouldNotReceive('lock'); + $cache->expects('put')->never(); + $cache->expects('lock')->never(); $container->instance(Cache::class, $cache); $dispatcher->setQueueResolver(fn () => $queue); @@ -893,13 +902,13 @@ public function testUniqueListenerLockIsReleasedWhenQueueResolutionFails(): void { $container = new Container; $dispatcher = new Dispatcher($container); - $factory = m::mock(QueueFactory::class); + $factory = Double::for(QueueFactory::class); $cache = new Repository(new ArrayStore); $failure = new Exception('Queue unavailable.'); $lockKey = 'laravel_unique_job:' . hash('xxh128', TestDispatcherShouldBeUnique::class) . ':unique-listener-id'; $container->instance(Cache::class, $cache); - $factory->shouldReceive('connection')->once()->andThrow($failure); + $factory->expects('connection')->throws($failure); $dispatcher->setQueueResolver(fn () => $factory); $dispatcher->listen('some.event', TestDispatcherShouldBeUnique::class . '@handle'); @@ -920,15 +929,15 @@ public function testDebouncedListenerPublicationFailureReleasesItsOwnership(): v { $container = new Container; $dispatcher = new Dispatcher($container); - $factory = m::mock(QueueFactory::class); - $queue = m::mock(Queue::class); + $factory = Double::for(QueueFactory::class); + $queue = Double::for(Queue::class); $cache = new Repository(new ArrayStore); $failure = new Exception('Queue unavailable.'); $lockKey = 'laravel_debounced_job:' . hash('xxh128', TestDispatcherDebouncedHandlerWithMaxWait::class) . ':event-123'; $container->instance(Cache::class, $cache); - $factory->shouldReceive('connection')->once()->with(null)->andReturn($queue); - $queue->shouldReceive('laterOn')->once()->andThrow($failure); + $factory->expects('connection')->with(null)->returns($queue); + $queue->expects('laterOn')->throws($failure); $dispatcher->setQueueResolver(fn () => $factory); $dispatcher->listen('some.event', TestDispatcherDebouncedHandlerWithMaxWait::class . '@handle'); diff --git a/tests/Filesystem/FilesystemAdapterTest.php b/tests/Filesystem/FilesystemAdapterTest.php index 11da6cbeb..c06b1b7a5 100644 --- a/tests/Filesystem/FilesystemAdapterTest.php +++ b/tests/Filesystem/FilesystemAdapterTest.php @@ -7,6 +7,7 @@ use DateTimeInterface; use GuzzleHttp\Handler\InflateBodyStream; use GuzzleHttp\Psr7\CachingStream; +use GuzzleHttp\Psr7\FnStream; use GuzzleHttp\Psr7\PumpStream; use GuzzleHttp\Psr7\Stream; use Hypervel\Container\Container; @@ -33,6 +34,9 @@ use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use JsonException; use League\Flysystem\Filesystem; use League\Flysystem\FilesystemAdapter as FlysystemAdapter; @@ -50,12 +54,10 @@ use League\Flysystem\UnableToRetrieveMetadata; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\UnableToWriteFile; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresFunction; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\ExpectationFailedException; -use Psr\Http\Message\StreamInterface; use RuntimeException; use stdClass; use Swoole\Coroutine\CanceledException; @@ -64,6 +66,8 @@ class FilesystemAdapterTest extends TestCase { + use VerifiesDoubles; + private $tempDir; private $filesystem; @@ -118,8 +122,8 @@ public function testMimeTypeIsNotCalledAlreadyProvidedToResponse(): void $this->filesystem->write('file.txt', 'Hello World'); - $files = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $files->shouldReceive('mimeType')->never(); + $files = Double::for(new FilesystemAdapter($this->filesystem, $this->adapter))->passthru(); + $files->expects('mimeType')->never(); $files->response('file.txt', null, [ 'Content-Type' => 'text/x-custom', @@ -132,8 +136,8 @@ public function testSizeIsNotCalledAlreadyProvidedToResponse(): void $this->filesystem->write('file.txt', 'Hello World'); - $files = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $files->shouldReceive('size')->never(); + $files = Double::for(new FilesystemAdapter($this->filesystem, $this->adapter))->passthru(); + $files->expects('size')->never(); $files->response('file.txt', null, [ 'Content-Length' => 11, @@ -481,10 +485,11 @@ public function testPrepend(): void public function testPrependDoesNotOverwriteAnUnreadableExistingFile(): void { - $filesystemAdapter = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $filesystemAdapter->shouldReceive('fileExists')->once()->with('file.txt')->andReturnTrue(); - $filesystemAdapter->shouldReceive('get')->once()->with('file.txt')->andReturnNull(); - $filesystemAdapter->shouldReceive('put')->never(); + $driver = Double::for(FilesystemOperator::class); + $driver->expects('fileExists')->with('file.txt')->returns(true); + $driver->expects('read')->with('file.txt')->throws(UnableToReadFile::fromLocation('file.txt')); + $driver->expects('write')->never(); + $filesystemAdapter = new FilesystemAdapter($driver, $this->adapter); $this->assertFalse($filesystemAdapter->prepend('file.txt', 'Hello ')); } @@ -499,10 +504,11 @@ public function testAppend(): void public function testAppendDoesNotOverwriteAnUnreadableExistingFile(): void { - $filesystemAdapter = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $filesystemAdapter->shouldReceive('fileExists')->once()->with('file.txt')->andReturnTrue(); - $filesystemAdapter->shouldReceive('get')->once()->with('file.txt')->andReturnNull(); - $filesystemAdapter->shouldReceive('put')->never(); + $driver = Double::for(FilesystemOperator::class); + $driver->expects('fileExists')->with('file.txt')->returns(true); + $driver->expects('read')->with('file.txt')->throws(UnableToReadFile::fromLocation('file.txt')); + $driver->expects('write')->never(); + $filesystemAdapter = new FilesystemAdapter($driver, $this->adapter); $this->assertFalse($filesystemAdapter->append('file.txt', 'Moon')); } @@ -558,9 +564,10 @@ public function testCopyToDisk(): void $backupFilesystem = new Filesystem($backupAdapter = new LocalFilesystemAdapter($this->tempDir . '/backup')); - Container::getInstance()->instance(FilesystemFactory::class, m::mock(FilesystemFactory::class, [ - 'disk' => new FilesystemAdapter($backupFilesystem, $backupAdapter), - ])); + $filesystemFactory = Double::for(FilesystemFactory::class); + $filesystemFactory->expects('disk')->returns(new FilesystemAdapter($backupFilesystem, $backupAdapter)); + + Container::getInstance()->instance(FilesystemFactory::class, $filesystemFactory); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $filesystemAdapter->copyToDisk('backup', 'file.txt'); @@ -575,9 +582,10 @@ public function testMoveToDisk(): void $backupFilesystem = new Filesystem($backupAdapter = new LocalFilesystemAdapter($this->tempDir . '/backup')); - Container::getInstance()->instance(FilesystemFactory::class, m::mock(FilesystemFactory::class, [ - 'disk' => new FilesystemAdapter($backupFilesystem, $backupAdapter), - ])); + $filesystemFactory = Double::for(FilesystemFactory::class); + $filesystemFactory->expects('disk')->returns(new FilesystemAdapter($backupFilesystem, $backupAdapter)); + + Container::getInstance()->instance(FilesystemFactory::class, $filesystemFactory); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $filesystemAdapter->moveToDisk('backup', 'file.txt', 'copy.txt'); @@ -592,9 +600,10 @@ public function testCopyToDiskRejectsSameDiskAndPath(): void $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); - Container::getInstance()->instance(FilesystemFactory::class, m::mock(FilesystemFactory::class, [ - 'disk' => $filesystemAdapter, - ])); + $filesystemFactory = Double::for(FilesystemFactory::class); + $filesystemFactory->expects('disk')->returns($filesystemAdapter); + + Container::getInstance()->instance(FilesystemFactory::class, $filesystemFactory); $this->expectException(InvalidArgumentException::class); @@ -748,8 +757,8 @@ public function testReadStreamRangeWithoutBoundsDelegatesToTheFullStream(): void { $stream = tmpfile(); $this->assertIsResource($stream); - $filesystemAdapter = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $filesystemAdapter->shouldReceive('readStream')->once()->with('file.txt')->andReturn($stream); + $filesystemAdapter = Double::for(new FilesystemAdapter($this->filesystem, $this->adapter))->passthru(); + $filesystemAdapter->expects('readStream')->with('file.txt')->returns($stream); $this->assertSame($stream, $filesystemAdapter->readStreamRange('file.txt', null, null)); @@ -766,9 +775,9 @@ public function testReadStreamRangeRejectsInvalidArgumentsBeforeFileIo(): void ]; foreach ($invalidRanges as [$start, $end]) { - $filesystemAdapter = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $filesystemAdapter->shouldNotReceive('readStream'); - $filesystemAdapter->shouldNotReceive('size'); + $filesystemAdapter = Double::for(new FilesystemAdapter($this->filesystem, $this->adapter))->passthru(); + $filesystemAdapter->expects('readStream')->never(); + $filesystemAdapter->expects('size')->never(); try { $filesystemAdapter->readStreamRange('file.txt', $start, $end); @@ -788,8 +797,8 @@ public function testReadStreamRangeDiscardsBytesFromANonSeekableStream(): void fclose($writer); $metadata = stream_get_meta_data($reader); $this->assertFalse($metadata['seekable']); - $filesystemAdapter = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $filesystemAdapter->shouldReceive('readStream')->once()->with('file.txt')->andReturn($reader); + $filesystemAdapter = Double::for(new FilesystemAdapter($this->filesystem, $this->adapter))->passthru(); + $filesystemAdapter->expects('readStream')->with('file.txt')->returns($reader); $stream = $filesystemAdapter->readStreamRange('file.txt', 3, 5); @@ -806,8 +815,8 @@ public function testReadStreamRangeClosesTheSourceWithABoundedWrapper(): void $this->assertIsResource($source); fwrite($source, '0123456789'); rewind($source); - $filesystemAdapter = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $filesystemAdapter->shouldReceive('readStream')->once()->with('file.txt')->andReturn($source); + $filesystemAdapter = Double::for(new FilesystemAdapter($this->filesystem, $this->adapter))->passthru(); + $filesystemAdapter->expects('readStream')->with('file.txt')->returns($source); $stream = $filesystemAdapter->readStreamRange('file.txt', 3, 5); @@ -819,8 +828,8 @@ public function testReadStreamRangeClosesTheSourceWithABoundedWrapper(): void public function testReadStreamRangeReturnsNullAndClosesAStalledStreamByDefault(): void { [$reader, $writer] = $this->openStalledNonSeekableStream(); - $filesystemAdapter = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $filesystemAdapter->shouldReceive('readStream')->once()->with('file.txt')->andReturn($reader); + $filesystemAdapter = Double::for(new FilesystemAdapter($this->filesystem, $this->adapter))->passthru(); + $filesystemAdapter->expects('readStream')->with('file.txt')->returns($reader); $this->assertNull($filesystemAdapter->readStreamRange('file.txt', 3, 5)); @@ -831,11 +840,12 @@ public function testReadStreamRangeReturnsNullAndClosesAStalledStreamByDefault() public function testReadStreamRangeThrowsAndClosesAStalledStreamWhenConfigured(): void { [$reader, $writer] = $this->openStalledNonSeekableStream(); - $filesystemAdapter = m::mock( - FilesystemAdapter::class, - [$this->filesystem, $this->adapter, ['throw' => true]], - )->makePartial(); - $filesystemAdapter->shouldReceive('readStream')->once()->with('file.txt')->andReturn($reader); + $filesystemAdapter = Double::for(new FilesystemAdapter( + $this->filesystem, + $this->adapter, + ['throw' => true], + ))->passthru(); + $filesystemAdapter->expects('readStream')->with('file.txt')->returns($reader); $failure = null; try { @@ -858,20 +868,20 @@ public function testReadStreamRangeThrowsAndClosesAStalledStreamWhenConfigured() public function testReadStreamRangeReportsAndClosesAStalledStreamWhenConfigured(): void { [$reader, $writer] = $this->openStalledNonSeekableStream(); - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldReceive('report') - ->once() - ->withArgs(static function (UnableToReadFile $exception): bool { + $exceptionHandler = Double::for(ExceptionHandler::class); + $exceptionHandler->expects('report') + ->with(Argument::satisfies(static function (UnableToReadFile $exception): bool { self::assertInstanceOf(RuntimeException::class, $exception->getPrevious()); return true; - }); + })); Container::getInstance()->bind(ExceptionHandler::class, static fn () => $exceptionHandler); - $filesystemAdapter = m::mock( - FilesystemAdapter::class, - [$this->filesystem, $this->adapter, ['report' => true]], - )->makePartial(); - $filesystemAdapter->shouldReceive('readStream')->once()->with('file.txt')->andReturn($reader); + $filesystemAdapter = Double::for(new FilesystemAdapter( + $this->filesystem, + $this->adapter, + ['report' => true], + ))->passthru(); + $filesystemAdapter->expects('readStream')->with('file.txt')->returns($reader); $this->assertNull($filesystemAdapter->readStreamRange('file.txt', 3, 5)); @@ -881,8 +891,8 @@ public function testReadStreamRangeReportsAndClosesAStalledStreamWhenConfigured( public function testReadStreamRangePreservesCancellationAndClosesTheSourceWithoutReporting(): void { - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldNotReceive('report'); + $exceptionHandler = Double::for(ExceptionHandler::class); + $exceptionHandler->expects('report')->never(); Container::getInstance()->bind(ExceptionHandler::class, static fn () => $exceptionHandler); $originalHookFlags = Runtime::getHookFlags(); Runtime::enableCoroutine(SWOOLE_HOOK_ALL); @@ -890,11 +900,12 @@ public function testReadStreamRangePreservesCancellationAndClosesTheSourceWithou $this->assertIsArray($sockets); [$reader, $writer] = $sockets; $this->assertFalse(stream_get_meta_data($reader)['seekable']); - $filesystemAdapter = m::mock( - FilesystemAdapter::class, - [$this->filesystem, $this->adapter, ['report' => true, 'throw' => false]], - )->makePartial(); - $filesystemAdapter->shouldReceive('readStream')->once()->with('file.txt')->andReturn($reader); + $filesystemAdapter = Double::for(new FilesystemAdapter( + $this->filesystem, + $this->adapter, + ['report' => true, 'throw' => false], + ))->passthru(); + $filesystemAdapter->expects('readStream')->with('file.txt')->returns($reader); $failure = null; try { @@ -964,8 +975,8 @@ public function testPutWithDecodedStreamPreservesProducerCancellationAndClosesTh public function testPutWithStreamAllowsTheWriterToCloseItsInput(): void { $body = new CachingStream(new Stream(fopen('php://temp', 'w+b'))); - $driver = m::mock(FilesystemOperator::class); - $driver->shouldReceive('writeStream')->once()->andReturnUsing( + $driver = Double::for(FilesystemOperator::class); + $driver->expects('writeStream')->resolves( static function (string $path, mixed $stream): void { fclose($stream); }, @@ -1046,8 +1057,8 @@ public function testPutFileAsClosesTheSourceWhenWritingThrows(bool $writerCloses file_put_contents($filePath = $this->tempDir . '/foo.txt', 'normal file content'); $stream = null; - $filesystemAdapter = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $filesystemAdapter->shouldReceive('put')->once()->andReturnUsing( + $filesystemAdapter = Double::for(new FilesystemAdapter($this->filesystem, $this->adapter))->passthru(); + $filesystemAdapter->expects('put')->resolves( function (string $path, mixed $contents, mixed $options) use (&$stream, $writerClosesStream): never { $stream = $contents; @@ -1070,8 +1081,8 @@ function (string $path, mixed $contents, mixed $options) use (&$stream, $writerC public function testPutFileAsAllowsTheDriverToCloseTheSource(): void { file_put_contents($filePath = $this->tempDir . '/foo.txt', 'normal file content'); - $filesystemAdapter = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); - $filesystemAdapter->shouldReceive('put')->once()->andReturnUsing( + $filesystemAdapter = Double::for(new FilesystemAdapter($this->filesystem, $this->adapter))->passthru(); + $filesystemAdapter->expects('put')->resolves( function (string $path, mixed $contents, mixed $options): bool { $this->assertSame('new.txt', $path); $this->assertSame('normal file content', stream_get_contents($contents)); @@ -1138,7 +1149,7 @@ public function testPutFileWithoutPath(): void #[RequiresFunction('ftp_connect')] public function testCreateFtpDriver(): void { - $filesystem = new FilesystemManager(m::mock(Container::class)); + $filesystem = new FilesystemManager(new Application); $driver = $filesystem->createFtpDriver([ 'host' => 'ftp.example.com', @@ -1313,11 +1324,11 @@ public function testCallbackMutatorsCanClearPreviouslyConfiguredCallbacks(): voi #[DataProvider('canceledFilesystemOperations')] public function testCancellationBypassesTheFilesystemFailurePolicy(string $method, array $arguments, string $driverMethod, Throwable $failure): void { - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->never(); $this->app->instance(ExceptionHandler::class, $handler); - $driver = m::mock(FilesystemOperator::class); - $driver->shouldReceive($driverMethod)->once()->andThrow($failure); + $driver = Double::for(Filesystem::class); + $driver->expects($driverMethod)->throws($failure); $adapter = new FilesystemAdapter($driver, $this->adapter, ['throw' => false, 'report' => true]); $stream = $method === 'writeStream' ? fopen('php://memory', 'w+b') : null; @@ -1369,13 +1380,19 @@ public function testRangeReadPreservesCancellationFromTheStreamProducerAndCloses { $failure = new RuntimeException('Read cleanup failed.', previous: new CanceledException); $closeFailure = new RuntimeException('Stream close failed.'); - $body = m::mock(StreamInterface::class, new CachingStream(new PumpStream(static fn () => throw $failure))); + $body = new CachingStream(new PumpStream(static fn () => throw $failure)); if ($closeThrows) { - $body->shouldReceive('close')->once()->andThrow($closeFailure); + $body = FnStream::decorate($body, [ + 'close' => static function () use ($body, $closeFailure): never { + $body->close(); + + throw $closeFailure; + }, + ]); } $stream = StreamWrapper::detach($body); - $driver = m::mock(FilesystemOperator::class); - $driver->shouldReceive('readStream')->once()->andReturn($stream); + $driver = Double::for(FilesystemOperator::class); + $driver->expects('readStream')->returns($stream); $adapter = new FilesystemAdapter($driver, $this->adapter); $caught = null; @@ -1605,10 +1622,10 @@ public function testProvidesTemporaryUrlsWithCustomCallback(): void public function testProvidesTemporaryUrlsForS3Adapter(): void { - $filesystem = new FilesystemManager(m::mock(Container::class)); + $filesystem = new FilesystemManager(new Application); $filesystemAdapter = $filesystem->createS3Driver([ 'region' => 'us-west-1', - 'bucket' => 'laravel', + 'bucket' => 'hypervel', ]); $this->assertTrue($filesystemAdapter->providesTemporaryUrls()); @@ -1616,10 +1633,10 @@ public function testProvidesTemporaryUrlsForS3Adapter(): void public function testUsesRightSeperatorForS3Adapter(): void { - $filesystem = new FilesystemManager(m::mock(Container::class)); + $filesystem = new FilesystemManager(new Application); $filesystemAdapter = $filesystem->createS3Driver([ 'region' => 'us-west-1', - 'bucket' => 'laravel', + 'bucket' => 'hypervel', 'root' => 'something', 'directory_separator' => '\\', ]); @@ -1717,10 +1734,10 @@ public function testGetChecksum(): void public function testUsesRightSeperatorForS3AdapterWithoutDoublePrefixing(): void { - $filesystem = new FilesystemManager(m::mock(Container::class)); + $filesystem = new FilesystemManager(new Application); $filesystemAdapter = $filesystem->createS3Driver([ 'region' => 'us-west-1', - 'bucket' => 'laravel', + 'bucket' => 'hypervel', 'root' => 'my-root', 'prefix' => 'someprefix', 'directory_separator' => '\\', diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php index 533a95b8e..2f1a24417 100755 --- a/tests/Filesystem/FilesystemTest.php +++ b/tests/Filesystem/FilesystemTest.php @@ -10,8 +10,9 @@ use Hypervel\Support\LazyCollection; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use PharData; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; use PHPUnit\Framework\Attributes\RequiresPhpExtension; @@ -23,6 +24,8 @@ class FilesystemTest extends TestCase { + use VerifiesDoubles; + private string $tempDir; protected function setUp(): void @@ -665,8 +668,8 @@ public function testMoveDirectoryReturnsFalseWhileOverwritingAndUnableToDeleteDe file_put_contents($this->tempDir . '/tmp6/foo.txt', ''); mkdir($this->tempDir . '/tmp7', 0777, true); - $files = m::mock(Filesystem::class)->makePartial(); - $files->expects('deleteDirectory')->andReturn(false); + $files = Double::for(Filesystem::class)->passthru(); + $files->expects('deleteDirectory')->returns(false); $this->assertFalse($files->moveDirectory($this->tempDir . '/tmp6', $this->tempDir . '/tmp7', true)); } diff --git a/tests/Foundation/Bootstrap/HandleExceptionsTest.php b/tests/Foundation/Bootstrap/HandleExceptionsTest.php index a898947dd..75f1b44b7 100644 --- a/tests/Foundation/Bootstrap/HandleExceptionsTest.php +++ b/tests/Foundation/Bootstrap/HandleExceptionsTest.php @@ -17,7 +17,9 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Monolog\Handler\NullHandler; use Monolog\Handler\TestHandler; use Monolog\Logger as Monolog; @@ -32,6 +34,8 @@ class HandleExceptionsTest extends TestCase { + use VerifiesDoubles; + protected $app; protected Config $config; @@ -227,11 +231,11 @@ public function testNullValueAsChannelUsesNullDriver(): void public function testMissingDeprecationOptionsUseTheNullChannelWithoutATrace(): void { - $logger = m::mock(LogManager::class); + $logger = Double::for(LogManager::class); $this->app->instance(LogManager::class, $logger); $this->config->set('logging.deprecations', []); - $logger->expects('channel')->with('deprecations')->andReturnSelf(); + $logger->expects('channel')->with('deprecations')->returns($logger); $logger->expects('warning')->with(sprintf( '%s in %s on line %s', 'Deprecated behavior', @@ -257,7 +261,7 @@ public function testMissingDeprecationOptionsUseTheNullChannelWithoutATrace(): v #[DataProvider('invalidDeprecationConfigurationProvider')] public function testInvalidDeprecationConfigurationFailsLoudly(mixed $configuration, string $key): void { - $this->app->instance(LogManager::class, m::mock(LogManager::class)); + $this->app->instance(LogManager::class, Double::for(LogManager::class)); $this->config->set('logging.deprecations', $configuration); $this->expectException(InvalidArgumentException::class); @@ -387,10 +391,10 @@ public function testDoNotOverrideExistingNullLogDriver(): void public function testDeprecationsDriverIsDerivedAgainFromTheRebuiltConfiguration(): void { - $logger = m::mock(LogManager::class); + $logger = Double::for(LogManager::class); $this->app->instance(LogManager::class, $logger); - $logger->expects('channel')->with('deprecations')->andReturnSelf(); + $logger->expects('channel')->with('deprecations')->returns($logger); $logger->expects('warning'); $this->config->set('logging.channels.single', ['driver' => 'single']); @@ -426,11 +430,11 @@ public function testNoDeprecationsDriverIfNoDeprecationsHereSend(): void public function testErrors(): void { - $logger = m::mock(LogManager::class); + $logger = Double::for(LogManager::class); $this->app->instance(LogManager::class, $logger); - $logger->shouldNotReceive('channel'); - $logger->shouldNotReceive('warning'); + $logger->expects('channel')->never(); + $logger->expects('warning')->never(); $this->expectExceptionObject(new ErrorException('Something went wrong')); @@ -462,16 +466,16 @@ public function testConsoleThrowableRendersToStandardError(): void { $exception = new RuntimeException('Test exception'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('renderForConsole')->once()->with( - m::on(function (mixed $output): bool { + $handler = Double::for(ExceptionHandler::class); + $handler->expects('renderForConsole')->with( + Argument::satisfies(function (mixed $output): bool { if (! $output instanceof StreamOutput) { return false; } return stream_get_meta_data($output->getStream())['uri'] === 'php://stderr'; }), - $exception, + Argument::same($exception), ); $this->app->instance(ExceptionHandler::class, $handler); @@ -482,13 +486,14 @@ public function testConsoleThrowableRendersToStandardError(): void public function testNonConsoleExceptionIsReportedWithoutRenderingAResponse(): void { $exception = new RuntimeException('uncaught coroutine failure'); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($exception); - $handler->shouldNotReceive('render'); - $handler->shouldNotReceive('renderForConsole'); - $this->app = m::mock($this->app); - $this->app->expects('make')->with(ExceptionHandler::class)->andReturn($handler); - $this->app->expects('runningInConsole')->andReturnFalse(); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with(Argument::same($exception)); + $handler->expects('render')->never(); + $handler->expects('renderForConsole')->never(); + $app = Double::for($this->app, override: true)->passthru(); + $this->app = $app->instance(); + $app->expects('make')->with(ExceptionHandler::class)->returns($handler); + $app->expects('runningInConsole')->returns(false); $this->handleExceptions()->handleException($exception); } @@ -501,13 +506,14 @@ public function testNonConsoleReporterFailureFallsBackToThePhpErrorLog(): void $errorLog = $directory . '/php-error.log'; $previousErrorLog = ini_set('error_log', $errorLog); $exception = new RuntimeException('uncaught coroutine failure'); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($exception)->andThrow(new Error('reporting failed')); - $handler->shouldNotReceive('render'); - $handler->shouldNotReceive('renderForConsole'); - $this->app = m::mock($this->app); - $this->app->expects('make')->with(ExceptionHandler::class)->andReturn($handler); - $this->app->expects('runningInConsole')->andReturnFalse(); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with(Argument::same($exception))->throws(new Error('reporting failed')); + $handler->expects('render')->never(); + $handler->expects('renderForConsole')->never(); + $app = Double::for($this->app, override: true)->passthru(); + $this->app = $app->instance(); + $app->expects('make')->with(ExceptionHandler::class)->returns($handler); + $app->expects('runningInConsole')->returns(false); try { $this->handleExceptions()->handleException($exception); @@ -527,11 +533,12 @@ public function testNonConsoleReporterFailureFallsBackToThePhpErrorLog(): void public function testIgnoresDeprecationsUntilConfigurationIsBound(): void { - $this->app = m::mock(Application::class); - $this->app->expects('hasBeenBootstrapped')->andReturnTrue(); - $this->app->expects('runningUnitTests')->andReturnFalse(); - $this->app->expects('bound')->with('config')->andReturnFalse(); - $this->app->shouldNotReceive('make'); + $app = Double::for(Application::class, override: true); + $this->app = $app->instance(); + $app->expects('hasBeenBootstrapped')->returns(true); + $app->expects('runningUnitTests')->returns(false); + $app->expects('bound')->with('config')->returns(false); + $app->expects('make')->never(); $this->handleExceptions()->handleDeprecationError( 'Deprecated behavior', @@ -560,10 +567,10 @@ 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 = m::mock(LogManager::class); + $logger = Double::for(LogManager::class); $this->app->instance(LogManager::class, $logger); - $logger->expects('channel')->with('deprecations')->andThrow(new Error('Class "Monolog\Logger" not found')); + $logger->expects('channel')->with('deprecations')->throws(new Error('Class "Monolog\Logger" not found')); $this->handleExceptions()->handleError( E_DEPRECATED, @@ -799,9 +806,10 @@ public function testReleaseLeavesHandlersAndSettingsChangedAfterTheApplication() */ protected function bootstrappableApplication(bool $testing = true): Application { - return tap(m::mock(Application::class), function (Application $app) use ($testing): void { - $app->allows('environment')->with('testing')->andReturn($testing); - }); + $app = Double::for(Application::class, override: true); + $app->allows('environment')->with('testing')->returns($testing); + + return $app->instance(); } /** diff --git a/tests/Foundation/Exceptions/Renderer/ListenerTest.php b/tests/Foundation/Exceptions/Renderer/ListenerTest.php index 46ff2cf78..aaa2a13cd 100644 --- a/tests/Foundation/Exceptions/Renderer/ListenerTest.php +++ b/tests/Foundation/Exceptions/Renderer/ListenerTest.php @@ -9,10 +9,13 @@ use Hypervel\Database\Events\QueryExecuted; use Hypervel\Foundation\Exceptions\Renderer\Listener; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ListenerTest extends TestCase { + use VerifiesDoubles; + /** * Create a real in-memory SQLite connection. */ @@ -56,9 +59,9 @@ public function testListenerCapsAt100Queries(): void { $listener = new Listener; - $connection = m::mock(Connection::class); - $connection->expects('getName')->times(150)->andReturn('testing'); - $connection->expects('prepareBindings')->times(100)->andReturnUsing(fn (array $bindings): array => $bindings); + $connection = Double::for(Connection::class); + $connection->expects('getName')->times(150)->returns('testing'); + $connection->expects('prepareBindings')->times(100)->resolves(fn (array $bindings): array => $bindings); for ($index = 0; $index < 150; ++$index) { $listener->onQueryExecuted( @@ -173,11 +176,11 @@ public function testNormalQuerySkipsTruncation(): void public function testLongQueriesAndBindingsAreBounded(): void { - $connection = m::mock(Connection::class); - $connection->expects('getName')->andReturn('testing'); + $connection = Double::for(Connection::class); + $connection->expects('getName')->returns('testing'); $connection->expects('prepareBindings') ->with(['first', 'second', 'third']) - ->andReturn(['first', 'second', 'third']); + ->returns(['first', 'second', 'third']); $listener = new Listener; $listener->onQueryExecuted(new QueryExecuted( diff --git a/tests/Foundation/FoundationAuthenticationTest.php b/tests/Foundation/FoundationAuthenticationTest.php index 16ce22a53..2fe9f6557 100644 --- a/tests/Foundation/FoundationAuthenticationTest.php +++ b/tests/Foundation/FoundationAuthenticationTest.php @@ -6,6 +6,7 @@ use Hypervel\Auth\AuthManager; use Hypervel\Auth\GenericUser; +use Hypervel\Auth\SessionGuard; use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Contracts\Auth\Authenticatable; use Hypervel\Contracts\Auth\Guard; @@ -13,11 +14,14 @@ use Hypervel\Foundation\Application; use Hypervel\Foundation\Testing\Concerns\InteractsWithAuthentication; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class FoundationAuthenticationTest extends TestCase { use InteractsWithAuthentication; + use VerifiesDoubles; protected Application $app; @@ -31,16 +35,17 @@ class FoundationAuthenticationTest extends TestCase */ protected function mockGuard(): Guard { - $guard = m::mock(Guard::class); + $guard = Double::for(SessionGuard::class); - $auth = m::mock(AuthManager::class); + $auth = Double::for(AuthManager::class); $auth->expects('guard') - ->andReturn($guard); + ->returns($guard); - $this->app = m::mock(Application::class); - $this->app->expects('make') - ->withArgs(['auth']) - ->andReturn($auth); + $app = Double::for(Application::class, override: true); + $app->expects('make') + ->with('auth') + ->returns($auth); + $this->app = $app->instance(); return $guard; } @@ -162,19 +167,19 @@ protected function setupProvider(array $credentials): void { $user = new GenericUser([]); - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $provider->expects('retrieveByCredentials') ->with($credentials) - ->andReturn($user); + ->returns($user); $provider->expects('validateCredentials') - ->with($user, $credentials) - ->andReturn($this->credentials === $credentials); + ->with(Argument::same($user), $credentials) + ->returns($this->credentials === $credentials); $this->mockGuard() ->expects('getProvider') - ->andReturn($provider); + ->returns($provider); } public function testAssertCredentials(): void diff --git a/tests/Foundation/FoundationCacheBasedMaintenanceModeTest.php b/tests/Foundation/FoundationCacheBasedMaintenanceModeTest.php index 79b12367f..2c0084c4d 100644 --- a/tests/Foundation/FoundationCacheBasedMaintenanceModeTest.php +++ b/tests/Foundation/FoundationCacheBasedMaintenanceModeTest.php @@ -8,52 +8,54 @@ use Hypervel\Contracts\Cache\Repository; use Hypervel\Foundation\CacheBasedMaintenanceMode; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class FoundationCacheBasedMaintenanceModeTest extends TestCase { + use VerifiesDoubles; + public function testItDeterminesWhetherMaintenanceModeIsActive(): void { - $cache = m::mock(Factory::class, Repository::class); - $cache->expects('store')->twice()->with('store-key')->andReturnSelf(); + $cache = Double::for(Factory::class, Repository::class); + $cache->expects('store')->times(2)->with('store-key')->returns($cache); $manager = new CacheBasedMaintenanceMode($cache, 'store-key', 'key'); - $cache->expects('has')->with('key')->andReturnFalse(); + $cache->expects('has')->with('key')->times(2)->returns(false, true); $this->assertFalse($manager->active()); - $cache->expects('has')->with('key')->andReturnTrue(); $this->assertTrue($manager->active()); } public function testItRetrievesPayloadFromCache(): void { - $cache = m::mock(Factory::class, Repository::class); - $cache->expects('store')->with('store-key')->andReturnSelf(); + $cache = Double::for(Factory::class, Repository::class); + $cache->expects('store')->with('store-key')->returns($cache); $manager = new CacheBasedMaintenanceMode($cache, 'store-key', 'key'); - $cache->expects('get')->with('key')->andReturn(['payload']); + $cache->expects('get')->with('key')->returns(['payload']); $this->assertSame(['payload'], $manager->data()); } public function testItReturnsEmptyPayloadWhenCacheKeyIsMissing(): void { - $cache = m::mock(Factory::class, Repository::class); - $cache->expects('store')->with('store-key')->andReturnSelf(); + $cache = Double::for(Factory::class, Repository::class); + $cache->expects('store')->with('store-key')->returns($cache); $manager = new CacheBasedMaintenanceMode($cache, 'store-key', 'key'); - $cache->expects('get')->with('key')->andReturnNull(); + $cache->expects('get')->with('key')->returns(null); $this->assertSame([], $manager->data()); } public function testItStoresPayloadInCache(): void { - $cache = m::mock(Factory::class, Repository::class); - $cache->expects('store')->with('store-key')->andReturnSelf(); - $cache->expects('put')->with('key', ['payload'])->andReturnTrue(); + $cache = Double::for(Factory::class, Repository::class); + $cache->expects('store')->with('store-key')->returns($cache); + $cache->expects('put')->with('key', ['payload'])->returns(true); $manager = new CacheBasedMaintenanceMode($cache, 'store-key', 'key'); $manager->activate(['payload']); @@ -61,9 +63,9 @@ public function testItStoresPayloadInCache(): void public function testItRemovesPayloadFromCache(): void { - $cache = m::mock(Factory::class, Repository::class); - $cache->expects('store')->with('store-key')->andReturnSelf(); - $cache->expects('forget')->with('key')->andReturnTrue(); + $cache = Double::for(Factory::class, Repository::class); + $cache->expects('store')->with('store-key')->returns($cache); + $cache->expects('forget')->with('key')->returns(true); $manager = new CacheBasedMaintenanceMode($cache, 'store-key', 'key'); $manager->deactivate(); @@ -71,9 +73,9 @@ public function testItRemovesPayloadFromCache(): void public function testItFailsWhenPayloadCannotBeStored(): void { - $cache = m::mock(Factory::class, Repository::class); - $cache->expects('store')->with('store-key')->andReturnSelf(); - $cache->expects('put')->with('key', ['payload'])->andReturnFalse(); + $cache = Double::for(Factory::class, Repository::class); + $cache->expects('store')->with('store-key')->returns($cache); + $cache->expects('put')->with('key', ['payload'])->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to activate maintenance mode using cache key [key].'); @@ -83,9 +85,9 @@ public function testItFailsWhenPayloadCannotBeStored(): void public function testItFailsWhenPayloadCannotBeRemoved(): void { - $cache = m::mock(Factory::class, Repository::class); - $cache->expects('store')->with('store-key')->andReturnSelf(); - $cache->expects('forget')->with('key')->andReturnFalse(); + $cache = Double::for(Factory::class, Repository::class); + $cache->expects('store')->with('store-key')->returns($cache); + $cache->expects('forget')->with('key')->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to deactivate maintenance mode using cache key [key].'); diff --git a/tests/Foundation/FoundationExceptionsHandlerTest.php b/tests/Foundation/FoundationExceptionsHandlerTest.php index ac3968980..152c9a8b1 100644 --- a/tests/Foundation/FoundationExceptionsHandlerTest.php +++ b/tests/Foundation/FoundationExceptionsHandlerTest.php @@ -10,6 +10,7 @@ use Hypervel\Config\Repository; use Hypervel\Container\Container; use Hypervel\Context\CoroutineContext; +use Hypervel\Contracts\Auth\Guard; use Hypervel\Contracts\Foundation\ExceptionRenderer; use Hypervel\Contracts\Routing\ResponseFactory as ResponseFactoryContract; use Hypervel\Contracts\Session\Session as SessionContract; @@ -46,8 +47,11 @@ use Hypervel\Validation\ValidationException; use Hypervel\Validation\Validator; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use OutOfRangeException; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\Attributes\DataProvider; @@ -71,6 +75,7 @@ class FoundationExceptionsHandlerTest extends TestCase { use InteractsWithExceptionHandling; + use VerifiesDoubles; protected Repository $config; @@ -82,13 +87,16 @@ class FoundationExceptionsHandlerTest extends TestCase protected Request $request; + protected DoubleInterface $requestDouble; + protected function setUp(): void { parent::setUp(); $this->config = $this->getConfig(); - $this->viewFactory = m::mock(ViewFactory::class); - $this->request = m::mock(Request::class); + $this->viewFactory = Double::for(ViewFactory::class); + $this->requestDouble = Double::for(Request::class, override: true); + $this->request = $this->requestDouble->instance(); $this->container = new Application; $this->container->singleton('config', fn (): Repository => $this->config); $this->container->singleton('view', fn (): ViewFactory => $this->viewFactory); @@ -96,7 +104,7 @@ protected function setUp(): void $this->container->instance(ResponseFactoryContract::class, new ResponseFactory( $this->viewFactory, - m::mock(Redirector::class), + Double::for(Redirector::class), )); Container::setInstance($this->container); @@ -132,8 +140,9 @@ public function testHandlerReportsExceptionAsContext(bool $throwingCleanup): voi public function testHandlerNeverReportsCancellation(): void { $cancellation = new CanceledException('canceled'); - $logger = m::mock(LoggerInterface::class); - $logger->shouldNotReceive('log', 'error'); + $logger = Double::for(LoggerInterface::class); + $logger->expects('log')->never(); + $logger->expects('error')->never(); $this->container->instance(LoggerInterface::class, $logger); $this->assertFalse($this->handler->shouldReport($cancellation)); @@ -158,8 +167,8 @@ public function testHandlerPreservesCancellationFromLoggerResolution(Throwable $ #[DataProvider('cancellations')] public function testHandlerPreservesCancellationFromDefaultContext(Throwable $cancellation): void { - $auth = m::mock(); - $auth->expects('id')->andThrow($cancellation); + $auth = Double::for(Guard::class); + $auth->expects('id')->throws($cancellation); $this->container->instance('auth', $auth); $previousFacadeApplication = Facade::getFacadeApplication(); Facade::setFacadeApplication($this->container); @@ -199,8 +208,8 @@ public function testHandlerPreservesCancellationDuringRendering(Throwable $cance public function testHandlerPreservesCancellationFromCustomRenderer(Throwable $cancellation): void { $failure = new RuntimeException('failed'); - $renderer = m::mock(ExceptionRenderer::class); - $renderer->expects('render')->with($failure)->andThrow($cancellation); + $renderer = Double::for(ExceptionRenderer::class); + $renderer->expects('render')->with(Argument::same($failure))->throws($cancellation); $this->container->instance(ExceptionRenderer::class, $renderer); $this->config->set('app.debug', true); @@ -227,14 +236,14 @@ public function testHandlerPreservesCancellationDuringConsoleRendering(Throwable public function testReportingStateIsLocalToTheCurrentCoroutine(): void { - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); $exception = new RuntimeException('Exception message'); $parentReporting = false; $childReporting = true; $completed = new Channel(1); - $logger->expects('error')->andReturnUsing( + $logger->expects('error')->resolves( function () use ( $exception, &$parentReporting, @@ -277,9 +286,9 @@ public function testHandlerCallsContextMethodIfPresent(): void public function testHandlerMergesInlineContextIntoLogContext(): void { - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->expects('error')->withArgs(['Exception message', m::subset(['from' => 'user@example.com', 'subject' => 'Hello'])]); + $logger->expects('error')->with('Exception message', Argument::satisfies(fn (array $context): bool => ($context['from'] ?? null) === 'user@example.com' && ($context['subject'] ?? null) === 'Hello')); $this->handler->report(new RuntimeException('Exception message'), [ 'from' => 'user@example.com', @@ -289,9 +298,9 @@ public function testHandlerMergesInlineContextIntoLogContext(): void public function testHandlerInlineContextOverridesExceptionContext(): void { - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->expects('error')->withArgs(['Exception message', m::subset(['foo' => 'overridden'])]); + $logger->expects('error')->with('Exception message', Argument::satisfies(fn (array $context): bool => ($context['foo'] ?? null) === 'overridden')); $this->handler->report(new ContextProvidingException('Exception message'), [ 'foo' => 'overridden', @@ -322,9 +331,9 @@ public function testReportableCallbackReceivesInlineContext(): void public function testReportingMarkerIsRestoredAfterNestedReportsAndContextFailures(): void { - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->expects('error')->withArgs(['Inner exception', m::hasKey('exception')]); + $logger->expects('error')->with('Inner exception', Argument::satisfies(fn (array $context): bool => array_key_exists('exception', $context))); $outer = new RuntimeException('Outer exception'); $inner = new RuntimeException('Inner exception'); @@ -395,13 +404,13 @@ public function testHandlerReportsExceptionWithCustomLogLevel(): void public function testHandlerReportsExceptionWithInlineLogLevel(): void { - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->expects('warning')->withArgs([ + $logger->expects('warning')->with( 'Warning message', - m::subset(['from' => 'user@example.com']), - ]); + Argument::satisfies(fn (array $context): bool => ($context['from'] ?? null) === 'user@example.com'), + ); $this->handler->level(InvalidArgumentException::class, LogLevel::CRITICAL); @@ -414,9 +423,10 @@ public function testHandlerReportsExceptionWithInlineLogLevel(): void public function testHandlerIgnoresNotReportableExceptions(): void { - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->shouldNotReceive('log'); + $logger->expects('log')->never(); + $logger->expects('error')->never(); $this->handler->ignore(RuntimeException::class); @@ -528,25 +538,27 @@ public function testHandlerInvokesRetryCallbackWhenExceptionMatchesAllIntersecti public function testHandlerCallsReportMethodWithDependencies(): void { - $reporter = m::mock(ReportingService::class); + $reporter = Double::for(ReportingService::class); $this->container->instance(ReportingService::class, $reporter); - $reporter->expects('send')->withArgs(['Exception message']); + $reporter->expects('send')->with('Exception message'); - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->shouldNotReceive('log'); + $logger->expects('log')->never(); + $logger->expects('error')->never(); $this->handler->report(new ReportableException('Exception message')); } public function testHandlerReportsExceptionUsingCallableClass(): void { - $reporter = m::mock(ReportingService::class); - $reporter->expects('send')->withArgs(['Exception message']); + $reporter = Double::for(ReportingService::class); + $reporter->expects('send')->with('Exception message'); - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->shouldNotReceive('log'); + $logger->expects('log')->never(); + $logger->expects('error')->never(); $this->handler->reportable(new CustomReporter($reporter)); @@ -570,7 +582,7 @@ public function testShouldReturnJson(): void public function testShouldReturnJsonWhen(): void { - $this->request->shouldReceive('expectsJson')->never(); + $this->requestDouble->expects('expectsJson')->never(); $exception = new Exception('My custom error message'); $request = $this->request; @@ -600,7 +612,7 @@ public function testShouldReturnJsonWhen(): void public function testUnauthenticatedJsonRequestReturnsJsonResponse(): void { - $this->request->expects('expectsJson')->andReturn(true); + $this->requestDouble->expects('expectsJson')->returns(true); $response = $this->handler->render($this->request, new AuthenticationException); @@ -614,7 +626,7 @@ public function testUnauthenticatedJsonRequestReturnsJsonResponse(): void public function testUnauthenticatedRequestWithoutRedirectReturnsNoContent(): void { AuthenticationException::redirectUsing(static fn (): null => null); - $this->request->expects('expectsJson')->andReturn(false); + $this->requestDouble->expects('expectsJson')->returns(false); $response = $this->handler->render($this->request, new AuthenticationException); @@ -625,12 +637,12 @@ public function testUnauthenticatedRequestWithoutRedirectReturnsNoContent(): voi public function testUnauthenticatedRequestWithRedirectReturnsGuestRedirect(): void { AuthenticationException::redirectUsing(static fn (): string => '/login'); - $this->request->expects('expectsJson')->andReturn(false); + $this->requestDouble->expects('expectsJson')->returns(false); - $redirector = m::mock(Redirector::class); + $redirector = Double::for(Redirector::class); $redirector->expects('guest') ->with('/login') - ->andReturn(new RedirectResponse('/login')); + ->returns(new RedirectResponse('/login')); $this->container->instance('redirect', $redirector); $response = $this->handler->render($this->request, new AuthenticationException); @@ -782,26 +794,26 @@ public function testValidateFileMethod(): void $argumentExpected = ['input' => 'My input value']; $argumentActual = null; - $session = m::mock(Store::class); - $session->shouldReceive('get')->with('errors', m::type(ViewErrorBag::class))->andReturn(new MessageBag(['error' => 'My custom validation exception'])); - $session->expects('flash')->with('errors', m::type(ViewErrorBag::class)); - $session->expects('flashInput')->with(m::on( + $session = Double::for(Store::class); + $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; } - ))->andReturnNull(); + ))->returns(null); CoroutineContext::set(Store::CONTEXT_KEY, $session); $this->container->instance(SessionContract::class, $session); $this->container->singleton('redirect', function () use ($session): Redirector { - $redirector = m::mock(Redirector::class); + $redirector = Double::for(Redirector::class); $redirect = new RedirectResponse('http://localhost/'); $redirect->setSession($session); $redirector->expects('to') - ->andReturn($redirect); + ->returns($redirect); return $redirector; }); @@ -810,8 +822,8 @@ function (array $argument) use (&$argumentActual): bool { $request = Request::create('/', 'POST', $argumentExpected, [], ['photo' => $file]); - $validator = m::mock(Validator::class); - $validator->expects('errors')->twice()->andReturn(new MessageBag(['error' => 'My custom validation exception'])); + $validator = Double::for(Validator::class); + $validator->expects('errors')->times(2)->returns(new MessageBag(['error' => 'My custom validation exception'])); $validationException = new ValidationException($validator); $validationException->redirectTo = '/'; @@ -824,27 +836,27 @@ function (array $argument) use (&$argumentActual): bool { public function testInvalidUsesErrorBagWhenStringAndFallsBackWhenNotString(): void { $errorBagActual = null; - CoroutineContext::set(Store::CONTEXT_KEY, m::mock(Store::class)); + CoroutineContext::set(Store::CONTEXT_KEY, Double::for(Store::class)); $this->container->singleton('redirect', function () use (&$errorBagActual): Redirector { - $redirector = m::mock(Redirector::class); - $responder = m::mock(RedirectResponse::class . '[withInput,withErrors]', ['/']); - $redirector->expects('to')->twice()->andReturn($responder); - $responder->expects('withInput')->twice()->andReturn($responder); - $responder->expects('withErrors')->twice()->with( - m::any(), - m::on(function (string $errorBag) use (&$errorBagActual): bool { + $redirector = Double::for(Redirector::class); + $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; }) - )->andReturn($responder); + )->returns($responder); return $redirector; }); - $validator = m::mock(Validator::class); - $validator->expects('errors')->times(3)->andReturn(new MessageBag(['error' => 'My custom validation exception'])); + $validator = Double::for(Validator::class); + $validator->expects('errors')->times(3)->returns(new MessageBag(['error' => 'My custom validation exception'])); $validationException = new ValidationException($validator); $validationException->redirectTo = '/'; @@ -862,16 +874,17 @@ public function testInvalidUsesErrorBagWhenStringAndFallsBackWhenNotString(): vo public function testSuspiciousOperationReturns400WithoutReporting(): void { $this->config->set('app.debug', true); - $this->request->expects('expectsJson')->andReturn(true); + $this->requestDouble->expects('expectsJson')->returns(true); $response = $this->handler->render($this->request, new SuspiciousOperationException('Invalid method override "__CONSTRUCT"')); $this->assertEquals(400, $response->getStatusCode()); $this->assertStringContainsString('"message": "Bad request."', $response->getContent()); - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->shouldNotReceive('log'); + $logger->expects('log')->never(); + $logger->expects('error')->never(); $this->handler->report(new SuspiciousOperationException('Invalid method override "__CONSTRUCT"')); } @@ -879,16 +892,17 @@ public function testSuspiciousOperationReturns400WithoutReporting(): void public function testRecordsNotFoundReturns404WithoutReporting(): void { $this->config->set('app.debug', true); - $this->request->expects('expectsJson')->andReturn(true); + $this->requestDouble->expects('expectsJson')->returns(true); $response = $this->handler->render($this->request, new RecordsNotFoundException); $this->assertEquals(404, $response->getStatusCode()); $this->assertStringContainsString('"message": "Not found."', $response->getContent()); - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->shouldNotReceive('log'); + $logger->expects('log')->never(); + $logger->expects('error')->never(); $this->handler->report(new RecordsNotFoundException); } @@ -969,7 +983,7 @@ private function executeScenarioWhereErrorViewThrowsWhileRenderingAndDebugIs(boo $this->container->instance(ViewFactory::class, $viewFactory); $this->container->instance(ResponseFactoryContract::class, new ResponseFactory( $viewFactory, - m::mock(Redirector::class), + Double::for(Redirector::class), )); $this->config->set('app.debug', $debug); @@ -1019,8 +1033,8 @@ public function testItDoesNotCrashIfErrorViewThrowsWhileRenderingAndDebugTrue(): #[DataProvider('cancellations')] public function testErrorViewCancellationEscapesWithoutReportingOrFallback(Throwable $cancellation): void { - $this->viewFactory->expects('exists')->with('errors::404')->andReturnTrue(); - $this->viewFactory->expects('make')->andThrow($cancellation); + $this->viewFactory->expects('exists')->with('errors::404')->returns(true); + $this->viewFactory->expects('make')->throws($cancellation); $handler = new class($this->container) extends Handler { public bool $reported = false; @@ -1626,28 +1640,28 @@ public function attempt( public function testValidateFailed(): void { - $this->request->expects('expectsJson')->andReturn(false); - $this->request->shouldReceive('input')->withNoArgs()->andReturn(['foo' => 'bar']); - $this->request->shouldReceive('input')->with('_error_bag')->andReturn('default'); + $this->requestDouble->expects('expectsJson')->returns(false); + $this->requestDouble->allows('input')->with(Argument::none())->returns(['foo' => 'bar']); + $this->requestDouble->allows('input')->with('_error_bag')->returns('default'); - $session = m::mock(Store::class); - $session->shouldReceive('get')->with('errors', m::type(ViewErrorBag::class))->andReturn(new MessageBag(['error' => 'My custom validation exception'])); - $session->expects('flash')->with('errors', m::type(ViewErrorBag::class)); + $session = Double::for(Store::class); + $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']); CoroutineContext::set(Store::CONTEXT_KEY, $session); $this->container->instance(SessionContract::class, $session); $redirectTo = 'http://localhost/redirectTo'; - $redirector = m::mock(Redirector::class); + $redirector = Double::for(Redirector::class); $redirect = new RedirectResponse($redirectTo); $redirect->setSession($session); $redirector->expects('to') ->with('redirectTo', 302, [], null) - ->andReturn($redirect); + ->returns($redirect); $this->container->instance('redirect', $redirector); - $validator = m::mock(Validator::class); - $validator->shouldReceive('errors')->andReturn(new MessageBag(['error' => 'My custom validation exception'])); + $validator = Double::for(Validator::class); + $validator->allows('errors')->returns(new MessageBag(['error' => 'My custom validation exception'])); $validationException = new ValidationException($validator); $validationException->redirectTo = 'redirectTo'; @@ -1660,7 +1674,7 @@ public function testValidateFailed(): void public function testModelNotFoundReturns404WithoutReporting(): void { - $this->request->expects('expectsJson')->andReturn(true); + $this->requestDouble->expects('expectsJson')->returns(true); $this->config->set('app.debug', true); $response = $this->handler->render($this->request, $exception = (new ModelNotFoundException)->setModel('foo')); @@ -1668,9 +1682,10 @@ public function testModelNotFoundReturns404WithoutReporting(): void $this->assertEquals(404, $response->getStatusCode()); $this->assertStringContainsString('"message": "No query results for model [foo]."', $response->getContent()); - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $this->container->instance(LoggerInterface::class, $logger); - $logger->shouldNotReceive('log'); + $logger->expects('log')->never(); + $logger->expects('error')->never(); $this->handler->report($exception); } @@ -1680,7 +1695,7 @@ public function testAfterResponseCallbacks(): void $this->handler->afterResponse(function (SymfonyResponse $response): void { $response->headers->set('X-After-Error', 'true'); }); - $this->request->expects('expectsJson')->andReturn(true); + $this->requestDouble->expects('expectsJson')->returns(true); $response = $this->handler->render($this->request, new Exception('Test exception')); diff --git a/tests/Foundation/FoundationFormRequestTest.php b/tests/Foundation/FoundationFormRequestTest.php index d009ff729..9477694d1 100644 --- a/tests/Foundation/FoundationFormRequestTest.php +++ b/tests/Foundation/FoundationFormRequestTest.php @@ -30,12 +30,15 @@ use Hypervel\Validation\Factory as ValidationFactory; use Hypervel\Validation\Rules\Numeric; use Hypervel\Validation\ValidationException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionProperty; use Symfony\Component\HttpFoundation\InputBag; class FoundationFormRequestTest extends TestCase { + use VerifiesDoubles; + protected array $mocks = []; public function testValidatedMethodReturnsTheValidatedData(): void @@ -189,7 +192,7 @@ public function testChildRouteAttributeOverridesParentRedirectProperty(): void { $request = $this->createRequest([], FoundationTestFormRequestOverridingParentPropertiesWithRouteAttributeStub::class, 'POST'); - $this->mocks['generator']->shouldReceive('route')->with('grandchild.route')->andReturn('http://localhost/grandchild'); + $this->mocks['generator']->expects('route')->with('grandchild.route')->returns('http://localhost/grandchild'); $exception = $this->catchException(ValidationException::class, function () use ($request): void { $request->validateResolved(); @@ -866,10 +869,10 @@ protected function createRequest(array $payload = [], string $class = Foundation */ protected function createValidationFactory(Container $container): ValidationFactory { - $translator = m::mock(Translator::class); - $translator->shouldReceive('get')->zeroOrMoreTimes()->andReturn('error'); - $translator->shouldReceive('string')->zeroOrMoreTimes()->andReturn('error'); - $translator->shouldReceive('choice')->zeroOrMoreTimes()->andReturn('error'); + $translator = Double::for(Translator::class); + $translator->allows('get')->returns('error'); + $translator->allows('string')->returns('error'); + $translator->allows('choice')->returns('error'); return new ValidationFactory($translator, $container); } @@ -896,16 +899,16 @@ protected function getRealRedirector(array $routes = []): Redirector */ protected function createMockRedirector(FormRequest $request): Redirector { - $redirector = $this->mocks['redirector'] = m::mock(Redirector::class); + $redirector = $this->mocks['redirector'] = Double::for(Redirector::class); - $redirector->shouldReceive('getUrlGenerator')->zeroOrMoreTimes() - ->andReturn($generator = $this->createMockUrlGenerator()); + $redirector->allows('getUrlGenerator') + ->returns($generator = $this->createMockUrlGenerator()); - $redirector->shouldReceive('to')->zeroOrMoreTimes() - ->andReturn($this->createMockRedirectResponse()); + $redirector->allows('to') + ->returns($this->createMockRedirectResponse()); - $generator->shouldReceive('previous')->zeroOrMoreTimes() - ->andReturn('previous'); + $generator->allows('previous') + ->returns('previous'); return $redirector; } @@ -915,7 +918,7 @@ protected function createMockRedirector(FormRequest $request): Redirector */ protected function createMockUrlGenerator(): UrlGenerator { - return $this->mocks['generator'] = m::mock(UrlGenerator::class); + return $this->mocks['generator'] = Double::for(UrlGenerator::class); } /** @@ -923,7 +926,7 @@ protected function createMockUrlGenerator(): UrlGenerator */ protected function createMockRedirectResponse(): RedirectResponse { - return $this->mocks['redirect'] = m::mock(RedirectResponse::class); + return $this->mocks['redirect'] = Double::for(RedirectResponse::class); } public function testAttributeConfigurationIsCachedPerClass(): void diff --git a/tests/Foundation/FoundationInteractsWithDatabaseTest.php b/tests/Foundation/FoundationInteractsWithDatabaseTest.php index 0c1c7eddb..678db3077 100644 --- a/tests/Foundation/FoundationInteractsWithDatabaseTest.php +++ b/tests/Foundation/FoundationInteractsWithDatabaseTest.php @@ -16,13 +16,15 @@ use Hypervel\Support\Facades\DB; use Hypervel\Testbench\Concerns\CreatesApplication; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\ExpectationFailedException; class FoundationInteractsWithDatabaseTest extends TestCase { use InteractsWithDatabase; + use VerifiesDoubles; protected string $table = 'products'; @@ -37,7 +39,7 @@ protected function setUp(): void { parent::setUp(); - $this->connection = m::mock(Connection::class); + $this->connection = Double::for(Connection::class); } public function testSeeInDatabaseFindsResults(): void @@ -70,12 +72,12 @@ public function testAssertDatabaseHasConstrainsToModel(): void public function testAssertDatabaseSupportsArrays(): void { - $builder = m::mock(Builder::class); - $builder->expects('where')->with(['title' => 'Spark', 'name' => 'Hypervel'])->andReturnSelf(); - $builder->expects('where')->with(['title' => 'Forge', 'name' => 'Hypervel'])->andReturnSelf(); - $builder->expects('exists')->twice()->andReturn(true); + $builder = Double::for(Builder::class); + $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); - $this->connection->shouldReceive('table')->with($this->table)->andReturn($builder); + $this->connection->allows('table')->with($this->table)->returns($builder); $this->assertDatabaseHas($this->table, [ ['title' => 'Spark', 'name' => 'Hypervel'], @@ -116,12 +118,12 @@ public function testSeeInDatabaseFindsManyNotMatchingResults(): void public function testAssertDatabaseMissingSupportsArrays(): void { - $builder = m::mock(Builder::class); - $builder->expects('where')->with(['title' => 'Spark', 'name' => 'Hypervel'])->andReturnSelf(); - $builder->expects('where')->with(['title' => 'Forge', 'name' => 'Hypervel'])->andReturnSelf(); - $builder->expects('exists')->twice()->andReturn(false); + $builder = Double::for(Builder::class); + $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); - $this->connection->shouldReceive('table')->with($this->table)->andReturn($builder); + $this->connection->allows('table')->with($this->table)->returns($builder); $this->assertDatabaseMissing($this->table, [ ['title' => 'Spark', 'name' => 'Hypervel'], @@ -206,11 +208,11 @@ public function testAssertDatabaseEmpty(): void public function testAssertDatabaseEmptySupportsArrays(): void { - $builder = m::mock(Builder::class); - $builder->expects('count')->twice()->andReturn(0); + $builder = Double::for(Builder::class); + $builder->expects('count')->times(2)->returns(0); - $this->connection->shouldReceive('table')->with($this->table)->andReturn($builder); - $this->connection->shouldReceive('table')->with('orders')->andReturn($builder); + $this->connection->expects('table')->with($this->table)->returns($builder); + $this->connection->expects('table')->with('orders')->returns($builder); $this->assertDatabaseEmpty([ProductStub::class, OrderStub::class]); } @@ -225,13 +227,13 @@ public function testAssertTableEntriesCountWrong(): void public function testAssertSoftDeletedSupportsArrays(): void { - $builder = m::mock(Builder::class); - $builder->expects('where')->with(['title' => 'Spark', 'name' => 'Hypervel'])->andReturnSelf(); - $builder->expects('where')->with(['title' => 'Forge', 'name' => 'Hypervel'])->andReturnSelf(); - $builder->expects('whereNotNull')->with('deleted_at')->twice()->andReturnSelf(); - $builder->expects('exists')->twice()->andReturnTrue(); + $builder = Double::for(Builder::class); + $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); + $builder->expects('exists')->times(2)->returns(true); - $this->connection->shouldReceive('table')->with($this->table)->andReturn($builder); + $this->connection->allows('table')->with($this->table)->returns($builder); $this->assertSoftDeleted($this->table, [ ['title' => 'Spark', 'name' => 'Hypervel'], @@ -241,13 +243,13 @@ public function testAssertSoftDeletedSupportsArrays(): void public function testAssertSoftDeletedSupportsModelWithArrays(): void { - $builder = m::mock(Builder::class); - $builder->expects('where')->with(['title' => 'Spark', 'id' => 1])->andReturnSelf(); - $builder->expects('where')->with(['name' => 'Hypervel', 'id' => 1])->andReturnSelf(); - $builder->expects('whereNotNull')->with('trashed_at')->twice()->andReturnSelf(); - $builder->expects('exists')->twice()->andReturnTrue(); + $builder = Double::for(Builder::class); + $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); + $builder->expects('exists')->times(2)->returns(true); - $this->connection->shouldReceive('table')->with($this->table)->andReturn($builder); + $this->connection->allows('table')->with($this->table)->returns($builder); $this->assertSoftDeleted(new CustomProductStub(['id' => 1]), [ ['title' => 'Spark'], @@ -257,13 +259,13 @@ public function testAssertSoftDeletedSupportsModelWithArrays(): void public function testAssertNotSoftDeletedSupportsArrays(): void { - $builder = m::mock(Builder::class); - $builder->expects('where')->with(['title' => 'Spark', 'name' => 'Hypervel'])->andReturnSelf(); - $builder->expects('where')->with(['title' => 'Forge', 'name' => 'Hypervel'])->andReturnSelf(); - $builder->expects('whereNull')->with('deleted_at')->twice()->andReturnSelf(); - $builder->expects('exists')->twice()->andReturnTrue(); + $builder = Double::for(Builder::class); + $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); + $builder->expects('exists')->times(2)->returns(true); - $this->connection->shouldReceive('table')->with($this->table)->andReturn($builder); + $this->connection->allows('table')->with($this->table)->returns($builder); $this->assertNotSoftDeleted($this->table, [ ['title' => 'Spark', 'name' => 'Hypervel'], @@ -273,13 +275,13 @@ public function testAssertNotSoftDeletedSupportsArrays(): void public function testAssertNotSoftDeletedSupportsModelWithArrays(): void { - $builder = m::mock(Builder::class); - $builder->expects('where')->with(['title' => 'Spark', 'id' => 1])->andReturnSelf(); - $builder->expects('where')->with(['name' => 'Hypervel', 'id' => 1])->andReturnSelf(); - $builder->expects('whereNull')->with('trashed_at')->twice()->andReturnSelf(); - $builder->expects('exists')->twice()->andReturnTrue(); + $builder = Double::for(Builder::class); + $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); + $builder->expects('exists')->times(2)->returns(true); - $this->connection->shouldReceive('table')->with($this->table)->andReturn($builder); + $this->connection->allows('table')->with($this->table)->returns($builder); $this->assertNotSoftDeleted(new CustomProductStub(['id' => 1]), [ ['title' => 'Spark'], @@ -289,26 +291,26 @@ public function testAssertNotSoftDeletedSupportsModelWithArrays(): void public function testAssertSoftDeletedTableSupportsIterablesWithCustomDeletedAtColumn(): void { - $builder = m::mock(Builder::class); - $builder->expects('where')->with($this->data)->twice()->andReturnSelf(); - $builder->expects('whereNotNull')->with('removed_at')->twice()->andReturnSelf(); - $builder->expects('exists')->twice()->andReturnTrue(); + $builder = Double::for(Builder::class); + $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); - $this->connection->shouldReceive('table')->with($this->table)->andReturn($builder); - $this->connection->shouldReceive('table')->with('orders')->andReturn($builder); + $this->connection->expects('table')->with($this->table)->returns($builder); + $this->connection->expects('table')->with('orders')->returns($builder); $this->assertSoftDeleted(['products', 'orders'], $this->data, deletedAtColumn: 'removed_at'); } public function testAssertNotSoftDeletedTableSupportsIterablesWithCustomDeletedAtColumn(): void { - $builder = m::mock(Builder::class); - $builder->expects('where')->with($this->data)->twice()->andReturnSelf(); - $builder->expects('whereNull')->with('removed_at')->twice()->andReturnSelf(); - $builder->expects('exists')->twice()->andReturnTrue(); + $builder = Double::for(Builder::class); + $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); - $this->connection->shouldReceive('table')->with($this->table)->andReturn($builder); - $this->connection->shouldReceive('table')->with('orders')->andReturn($builder); + $this->connection->expects('table')->with($this->table)->returns($builder); + $this->connection->expects('table')->with('orders')->returns($builder); $this->assertNotSoftDeleted(['products', 'orders'], $this->data, deletedAtColumn: 'removed_at'); } @@ -591,9 +593,9 @@ public function testExpectsDatabaseQueryCount(): void * * @param null|int|list $countResult */ - protected function mockCountBuilder(bool $existsResult, string $deletedAtColumn = 'deleted_at', array|int|null $countResult = null): Builder&MockInterface + protected function mockCountBuilder(bool $existsResult, string $deletedAtColumn = 'deleted_at', array|int|null $countResult = null): Builder&DoubleInterface { - $builder = m::mock(Builder::class); + $builder = Double::for(Builder::class); $countResult = Arr::wrap($countResult); $countResult = ! empty($countResult) ? $countResult : [$existsResult ? 1 : 0]; @@ -601,25 +603,25 @@ protected function mockCountBuilder(bool $existsResult, string $deletedAtColumn $key = array_key_first($this->data); $value = $this->data[$key]; - $builder->shouldReceive('where')->with($key, $value)->andReturnSelf(); + $builder->allows('where')->with($key, $value)->returns($builder); - $builder->shouldReceive('select')->with(array_keys($this->data))->andReturnSelf(); + $builder->allows('select')->with(array_keys($this->data))->returns($builder); - $builder->shouldReceive('limit')->andReturnSelf(); + $builder->allows('limit')->returns($builder); - $builder->shouldReceive('where')->with($this->data)->andReturnSelf(); + $builder->allows('where')->with($this->data)->returns($builder); - $builder->shouldReceive('whereNotNull')->with($deletedAtColumn)->andReturnSelf(); + $builder->allows('whereNotNull')->with($deletedAtColumn)->returns($builder); - $builder->shouldReceive('whereNull')->with($deletedAtColumn)->andReturnSelf(); + $builder->allows('whereNull')->with($deletedAtColumn)->returns($builder); - $builder->shouldReceive('exists')->andReturn($existsResult)->byDefault(); + $builder->allows('exists')->returns($existsResult); - $builder->shouldReceive('count')->andReturn(...$countResult)->byDefault(); + $builder->allows('count')->returns(...$countResult); - $this->connection->shouldReceive('table') + $this->connection->allows('table') ->with($this->table) - ->andReturn($builder); + ->returns($builder); return $builder; } diff --git a/tests/Foundation/Testing/Concerns/InteractsWithDatabaseTest.php b/tests/Foundation/Testing/Concerns/InteractsWithDatabaseTest.php index 1882a042d..025fe7983 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithDatabaseTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithDatabaseTest.php @@ -13,12 +13,14 @@ use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Foundation\Fixtures\User; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionClass; class InteractsWithDatabaseTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; protected bool $migrateRefresh = true; @@ -72,14 +74,14 @@ public function testDatabaseAssertionsPreserveAnExplicitZeroNamedConnection(): v public function testCastAsJsonUsesSpecifiedConnection(): void { $database = DB::getFacadeRoot(); - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); - $connection->shouldReceive('getQueryGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('raw')->once()->andReturnUsing( + $connection->expects('getQueryGrammar')->returns($grammar); + $connection->expects('raw')->resolves( static fn (string $value): Expression => new Expression($value), ); - $connection->shouldReceive('escape')->once()->andReturnUsing( + $connection->expects('escape')->resolves( static fn (string $value): string => "'{$value}'", ); @@ -204,15 +206,15 @@ public function testCastToJsonMariaDb(): void protected function castAsJsonUsingGrammar(array|object|string $value, string $grammar): string { $database = DB::getFacadeRoot(); - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammarClass = 'Hypervel\Database\Query\Grammars\\' . $grammar . 'Grammar'; $grammar = new $grammarClass($connection); - $connection->shouldReceive('getQueryGrammar')->andReturn($grammar); - $connection->shouldReceive('raw')->andReturnUsing( + $connection->allows('getQueryGrammar')->returns($grammar); + $connection->allows('raw')->resolves( static fn (string $value): Expression => new Expression($value), ); - $connection->shouldReceive('escape')->andReturnUsing( + $connection->allows('escape')->resolves( static fn (string $value): string => "'{$value}'", ); diff --git a/tests/Foundation/Testing/DatabaseTruncationTest.php b/tests/Foundation/Testing/DatabaseTruncationTest.php index e131e234a..5623f7d85 100644 --- a/tests/Foundation/Testing/DatabaseTruncationTest.php +++ b/tests/Foundation/Testing/DatabaseTruncationTest.php @@ -22,8 +22,10 @@ use Hypervel\Foundation\Testing\RefreshDatabase; use Hypervel\Foundation\Testing\RefreshDatabaseState; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PDO; use RuntimeException; @@ -31,6 +33,7 @@ class DatabaseTruncationTest extends TestCase { use DatabaseTruncation; use InteractsWithConsole; + use VerifiesDoubles; private ?Container $app; @@ -270,17 +273,17 @@ public function testRestoreSkipsDatabaseResolutionWhenNoInMemoryConnectionIsCach public function testCachesAndRestoresConfiguredInMemoryConnections(): void { - $defaultPdo = m::mock(PDO::class); - $namedPdo = m::mock(PDO::class); - $sourceDefault = m::mock(PdoConnection::class); - $sourceNamed = m::mock(PdoConnection::class); - $sourceDefault->expects('getPdo')->andReturn($defaultPdo); - $sourceNamed->expects('getPdo')->andReturn($namedPdo); - - $sourceDatabase = m::mock(DatabaseManager::class); - $sourceDatabase->expects('connection')->with(null)->andReturn($sourceDefault); - $sourceDatabase->expects('connection')->with('named')->andReturn($sourceNamed); - $sourceDatabase->shouldNotReceive('connection')->with('file'); + $defaultPdo = Double::for(PDO::class); + $namedPdo = Double::for(PDO::class); + $sourceDefault = Double::for(PdoConnection::class); + $sourceNamed = Double::for(PdoConnection::class); + $sourceDefault->expects('getPdo')->returns($defaultPdo); + $sourceNamed->expects('getPdo')->returns($namedPdo); + + $sourceDatabase = Double::for(DatabaseManager::class); + $sourceDatabase->expects('connection')->with(null)->returns($sourceDefault); + $sourceDatabase->expects('connection')->with('named')->returns($sourceNamed); + $sourceDatabase->expects('connection')->never()->with('file'); $this->app->instance('config', new Repository([ 'database' => [ @@ -297,18 +300,18 @@ public function testCachesAndRestoresConfiguredInMemoryConnections(): void $this->cacheInMemoryDatabases(); - $dispatcher = m::mock(DispatcherContract::class); - $restoredDefault = m::mock(PdoConnection::class); - $restoredNamed = m::mock(PdoConnection::class); - $restoredDefault->expects('setPdo')->with($defaultPdo)->andReturnSelf(); - $restoredDefault->expects('setEventDispatcher')->with($dispatcher)->andReturnSelf(); - $restoredNamed->expects('setPdo')->with($namedPdo)->andReturnSelf(); - $restoredNamed->expects('setEventDispatcher')->with($dispatcher)->andReturnSelf(); + $dispatcher = Double::for(DispatcherContract::class); + $restoredDefault = Double::for(PdoConnection::class); + $restoredNamed = Double::for(PdoConnection::class); + $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 = m::mock(DatabaseManager::class); - $restoredDatabase->expects('connection')->with(null)->andReturn($restoredDefault); - $restoredDatabase->expects('connection')->with('named')->andReturn($restoredNamed); - $restoredDatabase->shouldNotReceive('connection')->with('file'); + $restoredDatabase = Double::for(DatabaseManager::class); + $restoredDatabase->expects('connection')->with(null)->returns($restoredDefault); + $restoredDatabase->expects('connection')->with('named')->returns($restoredNamed); + $restoredDatabase->expects('connection')->never()->with('file'); $this->app->instance('db', $restoredDatabase); $this->app->instance(DispatcherContract::class, $dispatcher); @@ -339,8 +342,8 @@ public function testCachingInMemoryConnectionRequiresPdoConnection(): void ], ])); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn(m::mock(Connection::class)); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns(Double::for(Connection::class)); $this->app->instance('db', $database); $this->expectException(LogicException::class); @@ -359,10 +362,10 @@ public function testRestoringInMemoryConnectionRequiresPdoConnection(): void ], ], ])); - RefreshDatabaseState::$inMemoryConnections = ['default' => m::mock(PDO::class)]; + RefreshDatabaseState::$inMemoryConnections = ['default' => Double::for(PDO::class)]; - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn(m::mock(Connection::class)); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns(Double::for(Connection::class)); $this->app->instance('db', $database); $this->expectException(LogicException::class); @@ -453,17 +456,17 @@ public function truncate(): void public function testMigratesWhenRetainedStateHasNoSelectedInMemoryPdo(): void { - $pdo = m::mock(PDO::class); - $connection = m::mock(PdoConnection::class); - $connection->expects('getPdo')->andReturn($pdo); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); - $kernel = m::mock(KernelContract::class); + $pdo = Double::for(PDO::class); + $connection = Double::for(PdoConnection::class); + $connection->expects('getPdo')->returns($pdo); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); + $kernel = Double::for(KernelContract::class); $kernel->expects('call')->with('migrate:fresh', [ '--drop-views' => false, '--drop-types' => false, '--seed' => false, - ])->andReturn(0); + ])->returns(0); $kernel->expects('setArtisan')->with(null); $this->app->instance(KernelContract::class, $kernel); $this->app->instance('db', $database); @@ -485,12 +488,12 @@ public function testMigratesWhenRetainedStateHasNoSelectedInMemoryPdo(): void public function testAdoptsAMissingInMemoryPdoBeforeTheTruncationHook(): void { - $pdo = m::mock(PDO::class); - $connection = m::mock(PdoConnection::class); - $connection->expects('getPdo')->andReturn($pdo); + $pdo = Double::for(PDO::class); + $connection = Double::for(PdoConnection::class); + $connection->expects('getPdo')->returns($pdo); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); $app = new Container; $app->instance('config', new Repository([ @@ -558,21 +561,21 @@ private function arrangeConnection( $actual = []; $allTables = array_map(fn (array $table): array => $table + ['partition_of' => null], $allTables); - $schema = m::mock($builder ?? Builder::class)->makePartial(); + $schema = Double::for($builder ?? Builder::class)->passthru(); if ($schemas === []) { - $schema->shouldNotReceive('getTables'); + $schema->expects('getTables')->never(); } else { - $schema->expects('getTables')->with($schemas)->andReturn( + $schema->expects('getTables')->with($schemas)->returns( $schemas === null ? $allTables : array_filter($allTables, fn (array $table): bool => in_array($table['schema'], $schemas, true)) ); } - $schema->expects('getCurrentSchemaListing')->andReturn($schemas); + $schema->expects('getCurrentSchemaListing')->returns($schemas); $withoutPrefix = false; - $schema->expects('truncateTables')->andReturnUsing( + $schema->expects('truncateTables')->resolves( function (array $tables) use (&$actual, &$withoutPrefix, $failure): void { $this->assertTrue($withoutPrefix); $actual = $tables; @@ -583,14 +586,14 @@ function (array $tables) use (&$actual, &$withoutPrefix, $failure): void { } ); - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn($prefix); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns($prefix); $dispatcher = new Dispatcher; - $connection->expects('getEventDispatcher')->andReturn($dispatcher); + $connection->expects('getEventDispatcher')->returns($dispatcher); $connection->expects('unsetEventDispatcher'); - $connection->expects('setEventDispatcher')->with($dispatcher); - $connection->shouldReceive('getSchemaBuilder')->andReturn($schema); - $connection->expects('withoutTablePrefix')->andReturnUsing( + $connection->expects('setEventDispatcher')->with(Argument::same($dispatcher)); + $connection->allows('getSchemaBuilder')->returns($schema); + $connection->expects('withoutTablePrefix')->resolves( function (callable $callback) use ($connection, &$withoutPrefix): void { $withoutPrefix = true; diff --git a/tests/Foundation/Testing/LazilyRefreshDatabaseTest.php b/tests/Foundation/Testing/LazilyRefreshDatabaseTest.php index 077354f52..b40076b0f 100644 --- a/tests/Foundation/Testing/LazilyRefreshDatabaseTest.php +++ b/tests/Foundation/Testing/LazilyRefreshDatabaseTest.php @@ -14,7 +14,8 @@ use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Foundation\Testing\Fixtures\ConsoleKernelSpy; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Output\OutputInterface; use Throwable; @@ -26,6 +27,7 @@ class LazilyRefreshDatabaseTest extends TestCase use LazilyRefreshDatabase { refreshTestDatabase as baseRefreshTestDatabase; } + use VerifiesDoubles; protected array $connectionsToTransact = ['testing', 'testing2']; @@ -68,9 +70,9 @@ public function testDatabaseIsRefreshedOnInteraction(): void public function testDatabaseIsNotRefreshedWithoutInteraction(): void { - $kernel = m::mock(KernelContract::class); + $kernel = Double::for(KernelContract::class); $this->app->instance(KernelContract::class, $kernel); - $kernel->shouldNotReceive('call'); + $kernel->expects('call')->never(); $this->app->make('db')->getPdo(); diff --git a/tests/Http/HttpRedirectResponseTest.php b/tests/Http/HttpRedirectResponseTest.php index 58bffd611..a03770bd1 100755 --- a/tests/Http/HttpRedirectResponseTest.php +++ b/tests/Http/HttpRedirectResponseTest.php @@ -13,11 +13,14 @@ use Hypervel\Support\MessageBag; use Hypervel\Support\ViewErrorBag; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Cookie; class HttpRedirectResponseTest extends TestCase { + use VerifiesDoubles; + public function testToResponseReturnsTheSameInstance(): void { $response = new RedirectResponse('foo.bar'); @@ -41,7 +44,7 @@ public function testWithOnRedirect(): void { $response = new RedirectResponse('foo.bar'); $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26])); - $session = m::mock(Store::class); + $session = Double::for(Store::class); $response->setSession($session); $session->expects('flash')->with('0', 'name'); $session->expects('flash')->with('1', 'age'); @@ -51,7 +54,7 @@ public function testWithOnRedirect(): void public function testWithAssociativeArrayOnRedirect(): void { $response = new RedirectResponse('foo.bar'); - $session = m::mock(Store::class); + $session = Double::for(Store::class); $session->expects('flash')->with('name', 'Taylor'); $response->setSession($session); $response->with(['name' => 'Taylor']); @@ -136,8 +139,8 @@ public function testFlashingErrorsOnRedirect(): void $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26])); $session = new Store('test', new NullSessionHandler); $response->setSession($session); - $provider = m::mock(MessageProvider::class); - $provider->expects('getMessageBag')->andReturn(new MessageBag(['name' => ['required']])); + $provider = Double::for(MessageProvider::class); + $provider->expects('getMessageBag')->returns(new MessageBag(['name' => ['required']])); $response->withErrors($provider); $this->assertContains('errors', $session->get('_flash.new', [])); diff --git a/tests/Http/HttpResponseTest.php b/tests/Http/HttpResponseTest.php index 4f76c3805..e85a6de83 100644 --- a/tests/Http/HttpResponseTest.php +++ b/tests/Http/HttpResponseTest.php @@ -20,8 +20,9 @@ use Hypervel\Support\MessageBag; use Hypervel\Support\ViewErrorBag; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonSerializable; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\HeaderBag; @@ -30,6 +31,8 @@ class HttpResponseTest extends TestCase { + use VerifiesDoubles; + public function testConstructorInitializesStatusHeadersContentAndOriginalContent(): void { $response = new Response(['name' => 'Taylor'], 201, ['X-Test' => 'yes']); @@ -296,8 +299,8 @@ public function testFlashingErrorsOnRedirect(): void $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26])); $session = new Store('test', new NullSessionHandler); $response->setSession($session); - $provider = m::mock(MessageProvider::class); - $provider->expects('getMessageBag')->andReturn(new MessageBag(['name' => ['required']])); + $provider = Double::for(MessageProvider::class); + $provider->expects('getMessageBag')->returns(new MessageBag(['name' => ['required']])); $response->withErrors($provider); $this->assertContains('errors', $session->get('_flash.new', [])); diff --git a/tests/Http/JsonResourceTest.php b/tests/Http/JsonResourceTest.php index 5761e12ff..14b4eeb12 100644 --- a/tests/Http/JsonResourceTest.php +++ b/tests/Http/JsonResourceTest.php @@ -10,7 +10,6 @@ use Hypervel\Http\Resources\Json\JsonResource; use Hypervel\Http\Resources\MissingValue; use Hypervel\Tests\TestCase; -use Mockery as m; class JsonResourceTest extends TestCase { @@ -49,10 +48,9 @@ public function testJsonResourceToJsonSucceedsWithPriorErrors(): void public function testJsonResourceToPrettyPrint(): void { - $resource = m::mock(JsonResource::class) - ->makePartial() - ->expects('jsonSerialize')->times(3)->andReturn(['foo' => 'bar', 'bar' => 'foo', 'number' => 123]) - ->getMock(); + Container::getInstance()->instance('request', Request::create('/')); + + $resource = new JsonResource(['foo' => 'bar', 'bar' => 'foo', 'number' => 123]); $results = $resource->toPrettyJson(); $expected = $resource->toJson(JSON_PRETTY_PRINT); diff --git a/tests/Http/Middleware/PreventRequestForgeryTest.php b/tests/Http/Middleware/PreventRequestForgeryTest.php index 124516932..406bfed7f 100644 --- a/tests/Http/Middleware/PreventRequestForgeryTest.php +++ b/tests/Http/Middleware/PreventRequestForgeryTest.php @@ -4,8 +4,8 @@ namespace Hypervel\Tests\Http\Middleware; -use Hypervel\Contracts\Foundation\Application; use Hypervel\Encryption\Encrypter; +use Hypervel\Foundation\Application; use Hypervel\Foundation\Http\Middleware\PreventRequestForgery; use Hypervel\Http\Exceptions\OriginMismatchException; use Hypervel\Http\Request; @@ -14,7 +14,6 @@ use Hypervel\Session\Store; use Hypervel\Session\TokenMismatchException; use Hypervel\Tests\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class PreventRequestForgeryTest extends TestCase @@ -238,7 +237,7 @@ protected function createSpoofedQueryRequest(string $bag, ?string $token = null) protected function createMiddleware(): PreventRequestForgeryTestStub { return new PreventRequestForgeryTestStub( - m::mock(Application::class), + new Application, new Encrypter(str_repeat('a', 16)) ); } diff --git a/tests/Image/ImageManagerTest.php b/tests/Image/ImageManagerTest.php index 6ecb55c95..a44a72943 100644 --- a/tests/Image/ImageManagerTest.php +++ b/tests/Image/ImageManagerTest.php @@ -12,6 +12,7 @@ use Hypervel\Contracts\Image\Driver; use Hypervel\Contracts\Image\Transformation; use Hypervel\Filesystem\Filesystem; +use Hypervel\Foundation\Application as FoundationApplication; use Hypervel\Http\Client\Factory as HttpFactory; use Hypervel\Http\Client\RequestException; use Hypervel\Http\UploadedFile; @@ -22,13 +23,17 @@ use Hypervel\Image\ImagePipeline; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use TypeError; use WeakReference; class ImageManagerTest extends TestCase { + use VerifiesDoubles; + public function testDefaultDriverReturnsConfiguredValue(): void { $app = $this->makeApp(['images.default' => 'imagick']); @@ -219,9 +224,7 @@ public function testFromPathReturnsImageFromFilePath(): void $path = $file->getRealPath(); $app = $this->makeApp([]); - $app->expects('make') - ->with(Filesystem::class) - ->andReturn(new Filesystem); + $app->instance(Filesystem::class, new Filesystem); $manager = new ImageManager($app); $image = $manager->fromPath($path); @@ -233,32 +236,33 @@ public function testFromPathReturnsImageFromFilePath(): void public function testFromPathIsLazy(): void { $app = $this->makeApp([]); - $app->shouldNotReceive('make')->with(Filesystem::class); + $filesystem = Double::for(Filesystem::class); + $filesystem->expects('get')->never(); + $app->bind(Filesystem::class, fn (): Filesystem => $filesystem); $manager = new ImageManager($app); $image = $manager->fromPath('/some/path.jpg'); $this->assertInstanceOf(Image::class, $image); + $this->assertFalse($app->resolved(Filesystem::class)); } public function testFromStorageReturnsImageFromStorageDiskPath(): void { $contents = $this->fakeImageContents(); - $disk = m::mock(FilesystemContract::class); + $disk = Double::for(FilesystemContract::class); $disk->expects('get') ->with('images/avatar.jpg') - ->andReturn($contents); + ->returns($contents); - $filesystem = m::mock(FilesystemFactory::class); + $filesystem = Double::for(FilesystemFactory::class); $filesystem->expects('disk') ->with('public') - ->andReturn($disk); + ->returns($disk); $app = $this->makeApp([]); - $app->expects('make') - ->with(FilesystemFactory::class) - ->andReturn($filesystem); + $app->instance(FilesystemFactory::class, $filesystem); $manager = new ImageManager($app); $image = $manager->fromStorage('images/avatar.jpg', 'public'); @@ -271,20 +275,18 @@ public function testFromStorageAcceptsBackedEnumDisk(): void { $contents = $this->fakeImageContents(); - $disk = m::mock(FilesystemContract::class); + $disk = Double::for(FilesystemContract::class); $disk->expects('get') ->with('images/avatar.jpg') - ->andReturn($contents); + ->returns($contents); - $filesystem = m::mock(FilesystemFactory::class); + $filesystem = Double::for(FilesystemFactory::class); $filesystem->expects('disk') ->with(ImageDiskStub::Public) - ->andReturn($disk); + ->returns($disk); $app = $this->makeApp([]); - $app->expects('make') - ->with(FilesystemFactory::class) - ->andReturn($filesystem); + $app->instance(FilesystemFactory::class, $filesystem); $manager = new ImageManager($app); $image = $manager->fromStorage('images/avatar.jpg', ImageDiskStub::Public); @@ -297,20 +299,18 @@ public function testFromStorageAcceptsUnitEnumDisk(): void { $contents = $this->fakeImageContents(); - $disk = m::mock(FilesystemContract::class); + $disk = Double::for(FilesystemContract::class); $disk->expects('get') ->with('images/avatar.jpg') - ->andReturn($contents); + ->returns($contents); - $filesystem = m::mock(FilesystemFactory::class); + $filesystem = Double::for(FilesystemFactory::class); $filesystem->expects('disk') ->with(ImageUnitDiskStub::public) - ->andReturn($disk); + ->returns($disk); $app = $this->makeApp([]); - $app->expects('make') - ->with(FilesystemFactory::class) - ->andReturn($filesystem); + $app->instance(FilesystemFactory::class, $filesystem); $manager = new ImageManager($app); $image = $manager->fromStorage('images/avatar.jpg', ImageUnitDiskStub::public); @@ -321,14 +321,14 @@ public function testFromStorageAcceptsUnitEnumDisk(): void public function testFromStorageReportsAMissingPath(): void { - $disk = m::mock(FilesystemContract::class); - $disk->expects('get')->with('images/missing.jpg')->andReturnNull(); + $disk = Double::for(FilesystemContract::class); + $disk->expects('get')->with('images/missing.jpg')->returns(null); - $filesystem = m::mock(FilesystemFactory::class); - $filesystem->expects('disk')->with('public')->andReturn($disk); + $filesystem = Double::for(FilesystemFactory::class); + $filesystem->expects('disk')->with('public')->returns($disk); $app = $this->makeApp([]); - $app->expects('make')->with(FilesystemFactory::class)->andReturn($filesystem); + $app->instance(FilesystemFactory::class, $filesystem); $manager = new ImageManager($app); $image = $manager->fromStorage('images/missing.jpg', 'public'); @@ -342,12 +342,15 @@ public function testFromStorageReportsAMissingPath(): void public function testFromStorageIsLazy(): void { $app = $this->makeApp([]); - $app->shouldNotReceive('make')->with(FilesystemFactory::class); + $filesystem = Double::for(FilesystemFactory::class); + $filesystem->expects('disk')->never(); + $app->bind(FilesystemFactory::class, fn (): FilesystemFactory => $filesystem); $manager = new ImageManager($app); $image = $manager->fromStorage('images/avatar.jpg', 'public'); $this->assertInstanceOf(Image::class, $image); + $this->assertFalse($app->resolved(FilesystemFactory::class)); } public function testFromStreamReturnsImage(): void @@ -473,9 +476,7 @@ public function testFromUrlIsOnlyFetchedOnce(): void ]); $app = $this->makeApp([]); - $app->expects('make') - ->with(HttpFactory::class) - ->andReturn($http); + $app->instance(HttpFactory::class, $http); $manager = new ImageManager($app); $image = $manager->fromUrl('https://example.com/photo.jpg'); @@ -549,9 +550,7 @@ public function testFromUrlReturnsImage(): void ]); $app = $this->makeApp([]); - $app->expects('make') - ->with(HttpFactory::class) - ->andReturn($http); + $app->instance(HttpFactory::class, $http); $manager = new ImageManager($app); $image = $manager->fromUrl('https://example.com/photo.jpg'); @@ -569,7 +568,7 @@ public function testFromUrlThrowsForUnsuccessfulResponse(int $status): void ]); $app = $this->makeApp([]); - $app->expects('make')->with(HttpFactory::class)->andReturn($http); + $app->instance(HttpFactory::class, $http); $manager = new ImageManager($app); $image = $manager->fromUrl('https://example.com/missing.jpg'); @@ -590,12 +589,16 @@ public static function httpErrorStatusProvider(): array public function testFromUrlIsLazy(): void { $app = $this->makeApp([]); - $app->shouldNotReceive('make')->with(HttpFactory::class); + $http = new HttpFactory; + $http->fake(); + $app->bind(HttpFactory::class, fn (): HttpFactory => $http); $manager = new ImageManager($app); $image = $manager->fromUrl('https://example.com/photo.jpg'); $this->assertInstanceOf(Image::class, $image); + $this->assertFalse($app->resolved(HttpFactory::class)); + $http->assertNothingSent(); } public function testFromBase64ReturnsImage(): void @@ -672,13 +675,13 @@ public function testCustomBackendProcessesWithoutInterventionInheritance(): void { $container = new Container; $container->instance('config', new Repository(['images.default' => 'custom'])); - $driver = m::mock(Driver::class); + $driver = Double::for(Driver::class); $driver->expects('process') ->with( 'source image', - m::on(static fn (ImagePipeline $pipeline): bool => $pipeline->output->format === 'png'), + Argument::satisfies(static fn (ImagePipeline $pipeline): bool => $pipeline->output->format === 'png'), ) - ->andReturn('custom image'); + ->returns('custom image'); $manager = new ImageManager($container); $manager->extend('custom', static fn (): Driver => $driver); @@ -781,11 +784,8 @@ protected function fakeImageContents(): string protected function makeApp(array $config): Application { - $app = m::mock(Application::class); - - $configRepo = new Repository($config); - - $app->shouldReceive('make')->with('config')->andReturn($configRepo)->byDefault(); + $app = new FoundationApplication; + $app->instance('config', new Repository($config)); return $app; } diff --git a/tests/Integration/Cache/Redis/RedisStoreTest.php b/tests/Integration/Cache/Redis/RedisStoreTest.php index b11a2eb42..34637b830 100644 --- a/tests/Integration/Cache/Redis/RedisStoreTest.php +++ b/tests/Integration/Cache/Redis/RedisStoreTest.php @@ -11,12 +11,15 @@ use Hypervel\Cache\RedisStore; use Hypervel\Cache\Repository; use Hypervel\Foundation\Testing\Concerns\InteractsWithRedis; +use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Facades\Cache; use Hypervel\Support\LazyCollection; use Hypervel\Support\Sleep; use Hypervel\Support\Str; +use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use Redis; use RuntimeException; @@ -24,6 +27,7 @@ class RedisStoreTest extends TestCase { use InteractsWithRedis; + use VerifiesDoubles; public function testCacheTtl(): void { @@ -325,6 +329,134 @@ public function testTagsCanBeFlushedWithLargeNumberOfKeys(): void $this->assertCount(0, $keyCount); } + public function testItStoresAndRetrievesValues(): void + { + $store = Cache::store('redis'); + $store->clear(); + + $this->assertNull($store->get('foo')); + + $this->assertTrue($store->put('foo', 'bar', 60)); + $this->assertTrue($store->put('number', 5, 60)); + $this->assertTrue($store->put('float', 1.5, 60)); + + $this->assertSame('bar', $store->get('foo')); + $this->assertEquals(5, $store->get('number')); + $this->assertEquals(1.5, $store->get('float')); + } + + public function testItStoresAndRetrievesManyValues(): void + { + $store = Cache::store('redis'); + $store->clear(); + + $this->assertTrue($store->putMany(['foo' => 'bar', 'fizz' => 'buzz', 'norf' => 'quz'], 60)); + + $this->assertSame( + ['foo' => 'bar', 'fizz' => 'buzz', 'norf' => 'quz', 'missing' => null], + $store->many(['foo', 'fizz', 'norf', 'missing']) + ); + } + + public function testItIncrementsAndDecrementsValues(): void + { + $store = Cache::store('redis'); + $store->clear(); + + $store->put('count', 1, 60); + + $this->assertSame(6, $store->increment('count', 5)); + $this->assertEquals(6, $store->get('count')); + $this->assertSame(4, $store->decrement('count', 2)); + $this->assertEquals(4, $store->get('count')); + } + + public function testItStoresValuesForeverAndCanTouchThem(): void + { + $store = Cache::store('redis'); + $store->clear(); + $connection = $store->connection(); + + $this->assertTrue($store->forever('forever', 'value')); + $this->assertSame('value', $store->get('forever')); + $this->assertSame(-1, $connection->ttl($store->getPrefix() . 'forever')); + + $store->put('touched', 'value', 10); + + $this->assertTrue($store->touch('touched', 100)); + $this->assertGreaterThan(10, $connection->ttl($store->getPrefix() . 'touched')); + $this->assertSame('value', $store->get('touched')); + } + + public function testFlushStaleTagsRemovesExpiredEntriesAndStopsScanning(): void + { + $store = Cache::store('redis'); + + $store->clear(); + + // An entry that expired five minutes ago, and one that is still fresh... + CarbonImmutable::setTestNow(CarbonImmutable::now()->subMinutes(5)); + + try { + $store->tags(['foo'])->put('expired', 'value', 60); + } finally { + CarbonImmutable::setTestNow(); + } + + $store->tags(['foo'])->put('fresh', 'value', 3600); + + $tagSet = $store->getPrefix() . '_all:tag:foo:entries'; + + $this->assertSame(2, $store->connection()->zcard($tagSet)); + + // The scan has to recognise it is back at its starting cursor, or this never returns... + $store->flushStaleTags(); + + $this->assertSame(1, $store->connection()->zcard($tagSet)); + $this->assertSame('value', $store->tags(['foo'])->get('fresh')); + } + + #[WithConfig('database.redis.options.prefix', 'app_')] + #[WithConfig('database.redis.options.scan', Redis::SCAN_PREFIX)] + public function testFlushStaleTagsDoesNotDoublePrefixTheMatchPatternWithScanPrefix(): void + { + $store = Cache::store('redis'); + $store->clear(); + + CarbonImmutable::setTestNow(CarbonImmutable::now()->subMinutes(5)); + + try { + $store->tags(['foo'])->put('expired', 'value', 60); + } finally { + CarbonImmutable::setTestNow(); + } + + $tagSet = $store->getPrefix() . '_all:tag:foo:entries'; + $connection = $store->connection(); + + $this->assertSame(1, $connection->zcard($tagSet)); + + $store->flushStaleTags(); + + $this->assertSame(0, $connection->zcard($tagSet)); + } + + public function testItForgetsAndFlushesValues(): void + { + $store = Cache::store('redis'); + $store->clear(); + + $store->put('foo', 'bar', 60); + $store->put('fizz', 'buzz', 60); + + $this->assertTrue($store->forget('foo')); + $this->assertNull($store->get('foo')); + $this->assertSame('buzz', $store->get('fizz')); + + $this->assertTrue($store->flush()); + $this->assertNull($store->get('fizz')); + } + public function testFlushingManyTagsOnlyPassesEachEntrysOwnTagToTheScript(): void { // Hypervel runs flush scripts on the raw connection, which dispatches no command events, @@ -368,10 +500,10 @@ public function testFlushingTagsWhileASharedKeyIsRewrittenLeavesNoLiveValueUnind $context = $store->getStore()->getContext(); $scanner = new GetEntries($context); $requests = 0; - $entries = m::mock(GetEntries::class); - $entries->shouldReceive('execute') - ->twice() - ->andReturnUsing(function (array $tagIds) use ($scanner, $store, &$requests): LazyCollection { + $entries = Double::for(GetEntries::class); + $entries->expects('execute') + ->times(2) + ->resolves(function (array $tagIds) use ($scanner, $store, &$requests): LazyCollection { if (++$requests === 2) { $store->tags(['people', 'artist'])->forever('person', 'John'); } diff --git a/tests/Integration/Database/DatabaseLockTest.php b/tests/Integration/Database/DatabaseLockTest.php index dc7eb1e48..952a79ad5 100644 --- a/tests/Integration/Database/DatabaseLockTest.php +++ b/tests/Integration/Database/DatabaseLockTest.php @@ -13,13 +13,17 @@ use Hypervel\Support\Facades\Cache; use Hypervel\Support\Facades\DB; use Hypervel\Testbench\Attributes\WithMigration; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PDOException; use PHPUnit\Framework\Attributes\TestWith; #[WithMigration('cache')] class DatabaseLockTest extends DatabaseTestCase { + use VerifiesDoubles; + public function testLockCanHaveASeparateConnection(): void { $config = $this->app->make('config'); @@ -273,15 +277,15 @@ public function testExpiredLockCannotBeRefreshedByPreviousOwner(): void #[TestWith(['Table does not exist', 1146, false])] public function testIgnoresConcurrencyException(string $message, int $code, bool $hasConcurrencyError): void { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $insertBuilder = m::mock(Builder::class); - $deleteBuilder = m::mock(Builder::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $insertBuilder = Double::for(Builder::class); + $deleteBuilder = Double::for(Builder::class); - $insertBuilder->expects('insert')->andReturn(true); + $insertBuilder->expects('insert')->returns(true); - $deleteBuilder->expects('where')->with('expiration', '<=', m::any())->andReturnSelf(); - $deleteBuilder->expects('delete')->andThrow( + $deleteBuilder->expects('where')->with('expiration', '<=', Argument::any())->returns($deleteBuilder); + $deleteBuilder->expects('delete')->throws( new QueryException( 'mysql', 'delete from cache_locks where expiration <= ?', @@ -290,10 +294,10 @@ public function testIgnoresConcurrencyException(string $message, int $code, bool ) ); - $connection->shouldReceive('getDriverName')->andReturn('mysql'); - $connection->allows('transactionLevel')->andReturn(0); - $connection->expects('table')->times(2)->with('cache_locks')->andReturn($insertBuilder, $deleteBuilder); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection); + $connection->allows('getDriverName')->returns('mysql'); + $connection->expects('transactionLevel')->times($hasConcurrencyError ? 1 : 0)->returns(0); + $connection->expects('table')->times(2)->with('cache_locks')->returns($insertBuilder, $deleteBuilder); + $resolver->allows('connection')->with(null)->returns($connection); $lock = new DatabaseLock($resolver, null, 'foo', 'cache_locks', 0, lottery: [1, 1]); @@ -309,11 +313,11 @@ 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 = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $insertBuilder = m::mock(Builder::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $insertBuilder = Double::for(Builder::class); - $insertBuilder->expects('insert')->andThrow( + $insertBuilder->expects('insert')->throws( new QueryException( 'mysql', 'insert into cache_locks (key, owner, expiration) values (?, ?, ?)', @@ -322,10 +326,10 @@ public function testAcquireThrowsConcurrencyExceptionInsideTransaction(): void ) ); - $connection->shouldReceive('getDriverName')->andReturn('mysql'); - $connection->allows('transactionLevel')->andReturn(1); - $connection->expects('table')->with('cache_locks')->andReturn($insertBuilder); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection); + $connection->allows('getDriverName')->returns('mysql'); + $connection->allows('transactionLevel')->returns(1); + $connection->expects('table')->with('cache_locks')->returns($insertBuilder); + $resolver->allows('connection')->with(null)->returns($connection); $lock = new DatabaseLock($resolver, null, 'foo', 'cache_locks', 10, lottery: null); @@ -338,15 +342,15 @@ public function testAcquireThrowsConcurrencyExceptionInsideTransaction(): void #[TestWith(['Table does not exist', 1146, false])] public function testReleaseIgnoresConcurrencyException(string $message, int $code, bool $hasConcurrencyError): void { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $deleteBuilder = m::mock(Builder::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $deleteBuilder = Double::for(Builder::class); $owner = 'owner-123'; - $deleteBuilder->expects('where')->with('key', 'foo')->andReturnSelf(); - $deleteBuilder->expects('where')->with('owner', $owner)->andReturnSelf(); - $deleteBuilder->expects('delete')->andThrow( + $deleteBuilder->expects('where')->with('key', 'foo')->returns($deleteBuilder); + $deleteBuilder->expects('where')->with('owner', $owner)->returns($deleteBuilder); + $deleteBuilder->expects('delete')->throws( new QueryException( 'mysql', 'delete from cache_locks where key = ? and owner = ?', @@ -355,9 +359,9 @@ public function testReleaseIgnoresConcurrencyException(string $message, int $cod ) ); - $connection->allows('transactionLevel')->andReturn(0); - $connection->expects('table')->with('cache_locks')->andReturn($deleteBuilder); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection); + $connection->expects('transactionLevel')->times($hasConcurrencyError ? 1 : 0)->returns(0); + $connection->expects('table')->with('cache_locks')->returns($deleteBuilder); + $resolver->allows('connection')->with(null)->returns($connection); $lock = new DatabaseLock($resolver, null, 'foo', 'cache_locks', 10, $owner); @@ -372,12 +376,12 @@ public function testReleaseIgnoresConcurrencyException(string $message, int $cod public function testPruneThrowsConcurrencyExceptionInsideTransaction(): void { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $deleteBuilder = m::mock(Builder::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $deleteBuilder = Double::for(Builder::class); - $deleteBuilder->expects('where')->with('expiration', '<=', m::any())->andReturnSelf(); - $deleteBuilder->expects('delete')->andThrow( + $deleteBuilder->expects('where')->with('expiration', '<=', Argument::any())->returns($deleteBuilder); + $deleteBuilder->expects('delete')->throws( new QueryException( 'mysql', 'delete from cache_locks where expiration <= ?', @@ -386,9 +390,9 @@ public function testPruneThrowsConcurrencyExceptionInsideTransaction(): void ) ); - $connection->allows('transactionLevel')->andReturn(1); - $connection->expects('table')->with('cache_locks')->andReturn($deleteBuilder); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('table')->with('cache_locks')->returns($deleteBuilder); + $resolver->allows('connection')->with(null)->returns($connection); $lock = new DatabaseLock($resolver, null, 'foo', 'cache_locks', 10); @@ -399,15 +403,15 @@ public function testPruneThrowsConcurrencyExceptionInsideTransaction(): void public function testReleaseThrowsConcurrencyExceptionInsideTransaction(): void { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $deleteBuilder = m::mock(Builder::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $deleteBuilder = Double::for(Builder::class); $owner = 'owner-123'; - $deleteBuilder->expects('where')->with('key', 'foo')->andReturnSelf(); - $deleteBuilder->expects('where')->with('owner', $owner)->andReturnSelf(); - $deleteBuilder->expects('delete')->andThrow( + $deleteBuilder->expects('where')->with('key', 'foo')->returns($deleteBuilder); + $deleteBuilder->expects('where')->with('owner', $owner)->returns($deleteBuilder); + $deleteBuilder->expects('delete')->throws( new QueryException( 'mysql', 'delete from cache_locks where key = ? and owner = ?', @@ -416,9 +420,9 @@ public function testReleaseThrowsConcurrencyExceptionInsideTransaction(): void ) ); - $connection->allows('transactionLevel')->andReturn(1); - $connection->expects('table')->with('cache_locks')->andReturn($deleteBuilder); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('table')->with('cache_locks')->returns($deleteBuilder); + $resolver->allows('connection')->with(null)->returns($connection); $lock = new DatabaseLock($resolver, null, 'foo', 'cache_locks', 10, $owner); diff --git a/tests/Integration/Events/ListenerTest.php b/tests/Integration/Events/ListenerTest.php index 0adb18f48..cb5932377 100644 --- a/tests/Integration/Events/ListenerTest.php +++ b/tests/Integration/Events/ListenerTest.php @@ -36,6 +36,17 @@ public function testClassListenerRunsImmediatelyInsideTransaction(): void $this->assertTrue(ListenerTestListener::$ran); } + public function testClassListenerRunsNormallyIfNoTransactions(): void + { + $this->app->instance('db.transactions', new DatabaseTransactionsManager); + + Event::listen(ListenerTestEvent::class, ListenerTestListener::class); + + Event::dispatch(new ListenerTestEvent); + + $this->assertTrue(ListenerTestListener::$ran); + } + public function testClassListenerDoesntRunInsideTransaction(): void { $manager = new DatabaseTransactionsManager; diff --git a/tests/Integration/Foundation/Console/ConfigCacheCommandTest.php b/tests/Integration/Foundation/Console/ConfigCacheCommandTest.php index cf2748195..d243056fb 100644 --- a/tests/Integration/Foundation/Console/ConfigCacheCommandTest.php +++ b/tests/Integration/Foundation/Console/ConfigCacheCommandTest.php @@ -7,14 +7,18 @@ use Hypervel\Container\Container; use Hypervel\Filesystem\Filesystem; use Hypervel\Tests\Integration\Generators\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use RuntimeException; use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Process; class ConfigCacheCommandTest extends TestCase { + use VerifiesDoubles; + protected array $files = [ 'bootstrap/cache/config.php', 'config/testconfig.php', @@ -67,15 +71,16 @@ public function testConfigurationCanBeCachedSuccessfully(): void public function testConfigurationIsCachedAtomically(): void { - $files = m::mock(Filesystem::class)->makePartial(); - $files->shouldReceive('replace')->once()->with($this->app->getCachedConfigPath(), m::type('string'), null)->passthru(); - $files->shouldNotReceive('put'); + $files = Double::for(new Filesystem)->passthru(); + $files->expects('put')->never(); $this->app->instance('files', $files); $this->artisan('config:cache')->assertSuccessful(); $this->assertFileExists($this->app->getCachedConfigPath()); + + $files->received('replace')->times(1)->with($this->app->getCachedConfigPath(), Argument::type('string'), null); } public function testConfigurationCacheFailsWithNonSerializableValue(): void @@ -301,11 +306,10 @@ public function testExistingConfigurationCacheSurvivesPublicationFailure(): void ); $publicationException = new RuntimeException('publication failed'); - $mock = m::mock(Filesystem::class)->makePartial(); - $mock->shouldReceive('replace') - ->once() - ->with($cachePath, m::type('string'), 0640) - ->andThrow($publicationException); + $mock = Double::for(new Filesystem)->passthru(); + $mock->expects('replace') + ->with($cachePath, Argument::type('string'), 0640) + ->throws($publicationException); $this->app->instance(Filesystem::class, $mock); try { diff --git a/tests/Integration/Foundation/Console/EventCacheCommandTest.php b/tests/Integration/Foundation/Console/EventCacheCommandTest.php index d036408e4..b65dbd349 100644 --- a/tests/Integration/Foundation/Console/EventCacheCommandTest.php +++ b/tests/Integration/Foundation/Console/EventCacheCommandTest.php @@ -7,11 +7,15 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Foundation\Support\Providers\EventServiceProvider; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; class EventCacheCommandTest extends TestCase { + use VerifiesDoubles; + protected function tearDown(): void { @unlink($this->app->getCachedEventsPath()); @@ -21,8 +25,8 @@ protected function tearDown(): void public function testEventsAreCachedAtomically(): void { - $files = m::mock(Filesystem::class)->makePartial(); - $files->shouldReceive('replace')->once()->with($this->app->getCachedEventsPath(), m::type('string'), null)->passthru(); + $files = Double::for(new Filesystem)->passthru(); + $files->expects('put')->never(); $this->app->instance('files', $files); @@ -31,6 +35,8 @@ public function testEventsAreCachedAtomically(): void ->assertSuccessful(); $this->assertFileExists($this->app->getCachedEventsPath()); + + $files->received('replace')->times(1)->with($this->app->getCachedEventsPath(), Argument::type('string'), null); } public function testCachedFileContainsProviderEvents(): void @@ -98,11 +104,10 @@ public function testExistingEventCacheSurvivesPublicationFailure(): void chmod($cachePath, 0640); $publicationException = new RuntimeException('publication failed'); - $files = m::mock(Filesystem::class)->makePartial(); - $files->shouldReceive('replace') - ->once() - ->with($cachePath, m::type('string'), 0640) - ->andThrow($publicationException); + $files = Double::for(new Filesystem)->passthru(); + $files->expects('replace') + ->with($cachePath, Argument::type('string'), 0640) + ->throws($publicationException); $this->app->instance('files', $files); try { diff --git a/tests/Integration/Foundation/Console/RouteCacheCommandTest.php b/tests/Integration/Foundation/Console/RouteCacheCommandTest.php index 603324bec..5fb1086fa 100644 --- a/tests/Integration/Foundation/Console/RouteCacheCommandTest.php +++ b/tests/Integration/Foundation/Console/RouteCacheCommandTest.php @@ -12,7 +12,9 @@ use Hypervel\Support\Facades\Route; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Testing\Fixtures\CleanupActions; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Symfony\Component\Process\Exception\ProcessFailedException; @@ -20,6 +22,8 @@ class RouteCacheCommandTest extends TestCase { + use VerifiesDoubles; + protected Filesystem $files; /** @@ -80,9 +84,8 @@ public function testRoutesAreCachedAtomically(): void PHP ); - $files = m::mock(Filesystem::class)->makePartial(); - $files->shouldReceive('replace')->once()->with($this->app->getCachedRoutesPath(), m::type('string'), null)->passthru(); - $files->shouldNotReceive('put'); + $files = Double::for(new Filesystem)->passthru(); + $files->expects('put')->never(); $this->app->instance('files', $files); @@ -91,6 +94,8 @@ public function testRoutesAreCachedAtomically(): void ->expectsOutputToContain('Routes cached successfully'); $this->assertFileExists($this->app->getCachedRoutesPath()); + + $files->received('replace')->times(1)->with($this->app->getCachedRoutesPath(), Argument::type('string'), null); } public function testRouteCacheFailsWithNoRoutes(): void @@ -376,11 +381,10 @@ public function testExistingRouteCacheSurvivesPublicationFailure(): void ); $publicationException = new RuntimeException('publication failed'); - $mock = m::mock(Filesystem::class)->makePartial(); - $mock->shouldReceive('replace') - ->once() - ->with($cachePath, m::type('string'), 0640) - ->andThrow($publicationException); + $mock = Double::for(new Filesystem)->passthru(); + $mock->expects('replace') + ->with($cachePath, Argument::type('string'), 0640) + ->throws($publicationException); $this->app->instance(Filesystem::class, $mock); try { diff --git a/tests/Integration/Foundation/MaintenanceModeTest.php b/tests/Integration/Foundation/MaintenanceModeTest.php index 8b5b60a44..71b315d19 100644 --- a/tests/Integration/Foundation/MaintenanceModeTest.php +++ b/tests/Integration/Foundation/MaintenanceModeTest.php @@ -25,7 +25,9 @@ use Hypervel\Support\Facades\Exceptions; use Hypervel\Support\Facades\Route; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\HttpFoundation\Cookie; @@ -33,6 +35,8 @@ class MaintenanceModeTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ @@ -79,10 +83,10 @@ public function testBasicMaintenanceModeResponse(): void public function testCacheMaintenanceModeAllowsRequestWhenDeactivatedWhileReadingPayload(): void { - $cache = m::mock(Factory::class, Repository::class); - $cache->shouldReceive('store')->with('maintenance')->andReturnSelf(); - $cache->shouldReceive('has')->with('framework:down')->andReturn(true, false); - $cache->shouldReceive('get')->once()->with('framework:down')->andReturnNull(); + $cache = Double::for(Factory::class, Repository::class); + $cache->allows('store')->with('maintenance')->returns($cache); + $cache->allows('has')->with('framework:down')->returns(true, false); + $cache->expects('get')->with('framework:down')->returns(null); $this->app->instance(MaintenanceModeContract::class, new CacheBasedMaintenanceMode( $cache, @@ -99,10 +103,10 @@ public function testCacheMaintenanceModeAllowsRequestWhenDeactivatedWhileReading public function testActiveCacheMaintenanceModeWithAnEmptyPayloadBlocksRequests(): void { - $cache = m::mock(Factory::class, Repository::class); - $cache->shouldReceive('store')->with('maintenance')->andReturnSelf(); - $cache->shouldReceive('has')->with('framework:down')->andReturnTrue(); - $cache->shouldReceive('get')->once()->with('framework:down')->andReturn([]); + $cache = Double::for(Factory::class, Repository::class); + $cache->allows('store')->with('maintenance')->returns($cache); + $cache->allows('has')->with('framework:down')->returns(true); + $cache->expects('get')->with('framework:down')->returns([]); $this->app->instance(MaintenanceModeContract::class, new CacheBasedMaintenanceMode( $cache, @@ -118,10 +122,10 @@ public function testActiveCacheMaintenanceModeWithAnEmptyPayloadBlocksRequests() public function testConcurrentMaintenanceFileRemovalAllowsTheRequestToProceed(): void { $path = storage_path('framework/down'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->with($path)->andReturn(true, false); - $files->shouldReceive('get')->once()->with($path) - ->andThrow(new FileNotFoundException('removed')); + $files = Double::for(Filesystem::class); + $files->allows('exists')->with($path)->returns(true, false); + $files->expects('get')->with($path) + ->throws(new FileNotFoundException('removed')); $this->app->instance(MaintenanceModeContract::class, new FileBasedMaintenanceMode($files)); Route::get('/foo', fn (): string => 'Hello World')->middleware(PreventRequestsDuringMaintenance::class); @@ -138,9 +142,9 @@ public function testUnreadableMaintenanceFileDoesNotAllowTheRequestToProceed(): $path = storage_path('framework/down'); $exception = new FileNotFoundException('unreadable'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->with($path)->andReturnTrue(); - $files->shouldReceive('get')->once()->with($path)->andThrow($exception); + $files = Double::for(Filesystem::class); + $files->allows('exists')->with($path)->returns(true); + $files->expects('get')->with($path)->throws($exception); $this->app->instance(MaintenanceModeContract::class, new FileBasedMaintenanceMode($files)); Route::get('/foo', fn (): string => 'Hello World')->middleware(PreventRequestsDuringMaintenance::class); @@ -424,8 +428,8 @@ public function testDownAttemptsReloadAfterEventFailureAndPreservesTheEventFailu static fn (): never => throw $eventException, ); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($eventException, [])->andThrow($reportException); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with(Argument::same($eventException), [])->throws($reportException); $this->app->instance(ExceptionHandler::class, $handler); $this->artisan(FailingReloadDownCommand::class) @@ -476,9 +480,9 @@ public function testUpAttemptsReloadAfterEventFailureAndPreservesTheEventFailure public function testDownReportsDriverFailureBeforeMaintenanceStateIsCommitted(): void { - $mode = m::mock(MaintenanceModeContract::class); - $mode->shouldReceive('active')->once()->andReturnFalse(); - $mode->shouldReceive('activate')->once()->andThrow(new RuntimeException('activation failed')); + $mode = Double::for(MaintenanceModeContract::class); + $mode->expects('active')->returns(false); + $mode->expects('activate')->throws(new RuntimeException('activation failed')); $this->app->instance(MaintenanceModeContract::class, $mode); $this->artisan(DownCommand::class) @@ -494,13 +498,13 @@ public function testUpReportsDriverFailureBeforeMaintenanceStateIsCommitted(): v file_put_contents(storage_path('framework/down'), json_encode(['status' => 503])); $exception = new RuntimeException('deactivation failed'); - $mode = m::mock(MaintenanceModeContract::class); - $mode->shouldReceive('active')->once()->andReturnTrue(); - $mode->shouldReceive('deactivate')->once()->andThrow($exception); + $mode = Double::for(MaintenanceModeContract::class); + $mode->expects('active')->returns(true); + $mode->expects('deactivate')->throws($exception); $this->app->instance(MaintenanceModeContract::class, $mode); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($exception, []); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with(Argument::same($exception), []); $this->app->instance(ExceptionHandler::class, $handler); $this->artisan(UpCommand::class) diff --git a/tests/Integration/Queue/CallQueuedHandlerTest.php b/tests/Integration/Queue/CallQueuedHandlerTest.php index 8140eccea..c88f6e82e 100644 --- a/tests/Integration/Queue/CallQueuedHandlerTest.php +++ b/tests/Integration/Queue/CallQueuedHandlerTest.php @@ -13,6 +13,7 @@ use Hypervel\Cache\WorkerArrayStore; use Hypervel\Contracts\Cache\Factory as CacheFactory; use Hypervel\Contracts\Cache\Lock; +use Hypervel\Contracts\Cache\LockProvider; use Hypervel\Contracts\Cache\Repository as Cache; use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Events\Dispatcher as EventDispatcher; @@ -32,13 +33,17 @@ use Hypervel\Queue\Jobs\Job as BaseJob; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use stdClass; class CallQueuedHandlerTest extends TestCase { + use VerifiesDoubles; + public function testJobCanBeDispatched(): void { CallQueuedHandlerTestJob::$handled = false; @@ -124,12 +129,12 @@ public function testJobIsDeletedIfHasDeleteProperty(): void $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); - $job = m::mock(Job::class); - $job->expects('payload')->andReturn(['deleteWhenMissingModels' => true]); - $job->expects('resolveQueuedJobClass')->andReturn(CallQueuedHandlerExceptionThrower::class); - $job->shouldReceive('markAsFailed')->never(); + $job = Double::for(Job::class); + $job->expects('payload')->returns(['deleteWhenMissingModels' => true]); + $job->expects('resolveQueuedJobClass')->returns(CallQueuedHandlerExceptionThrower::class); + $job->expects('markAsFailed')->never(); $job->expects('delete'); - $job->shouldReceive('fail')->never(); + $job->expects('fail')->never(); $instance->call($job, [ 'command' => serialize(new CallQueuedHandlerExceptionThrower), @@ -144,12 +149,12 @@ public function testJobIsDeletedIfHasDeleteAttribute(): void $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); - $job = m::mock(Job::class); - $job->expects('payload')->andReturn(['deleteWhenMissingModels' => true]); - $job->expects('resolveQueuedJobClass')->andReturn(CallQueuedHandlerAttributeExceptionThrower::class); - $job->shouldReceive('markAsFailed')->never(); + $job = Double::for(Job::class); + $job->expects('payload')->returns(['deleteWhenMissingModels' => true]); + $job->expects('resolveQueuedJobClass')->returns(CallQueuedHandlerAttributeExceptionThrower::class); + $job->expects('markAsFailed')->never(); $job->expects('delete'); - $job->shouldReceive('fail')->never(); + $job->expects('fail')->never(); $instance->call($job, [ 'command' => serialize(new CallQueuedHandlerAttributeExceptionThrower), @@ -164,22 +169,22 @@ public function testBatchJobIsRecordedWhenDeletedDueToMissingModel(): void $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); - $batch = m::mock(Batch::class); + $batch = Double::for(Batch::class); $batch->expects('recordSuccessfulJob')->with('job-uuid'); - $repository = m::mock(BatchRepository::class); - $repository->expects('find')->with('test-batch-id')->andReturn($batch); + $repository = Double::for(BatchRepository::class); + $repository->expects('find')->with('test-batch-id')->returns($batch); $this->app->instance(BatchRepository::class, $repository); $serialized = serialize((new CallQueuedHandlerBatchableExceptionThrower)->withBatchId('test-batch-id')); - $job = m::mock(Job::class); - $job->expects('resolveQueuedJobClass')->andReturn(CallQueuedHandlerBatchableExceptionThrower::class); - $job->shouldReceive('markAsFailed')->never(); + $job = Double::for(Job::class); + $job->expects('resolveQueuedJobClass')->returns(CallQueuedHandlerBatchableExceptionThrower::class); + $job->expects('markAsFailed')->never(); $job->expects('delete'); - $job->shouldReceive('fail')->never(); - $job->expects('uuid')->times(3)->andReturn('job-uuid'); - $job->expects('payload')->times(2)->andReturn([ + $job->expects('fail')->never(); + $job->expects('uuid')->times(3)->returns('job-uuid'); + $job->expects('payload')->times(2)->returns([ 'deleteWhenMissingModels' => true, 'data' => [ 'batchId' => 'test-batch-id', @@ -200,11 +205,11 @@ public function testBatchJobIsRecordedAsFailedWhenModelIsMissing(): void $exception = new ModelNotFoundException('Foo'); - $batch = m::mock(Batch::class); - $batch->expects('recordFailedJob')->with('job-uuid', $exception); + $batch = Double::for(Batch::class); + $batch->expects('recordFailedJob')->with('job-uuid', Argument::same($exception)); - $repository = m::mock(BatchRepository::class); - $repository->expects('find')->with('test-batch-id')->andReturn($batch); + $repository = Double::for(BatchRepository::class); + $repository->expects('find')->with('test-batch-id')->returns($batch); $this->app->instance(BatchRepository::class, $repository); $this->expectException(ModelNotFoundException::class); @@ -217,25 +222,25 @@ public function testBatchJobIsRecordedAsFailedWhenModelIsMissing(): void public function testUniqueJobLockIsReleasedFromPayloadWhenDeletedForMissingModel(): void { - $lock = m::mock(Lock::class); + $lock = Double::for(Lock::class); $lock->expects('forceRelease'); - $cache = m::mock(Cache::class); - $cache->shouldReceive('lock')->with('laravel_unique_job:TestJob:42')->andReturn($lock); + $cache = Double::for(Cache::class, LockProvider::class); + $cache->allows('lock')->with('laravel_unique_job:TestJob:42')->returns($lock); - $cacheFactory = m::mock(CacheFactory::class); - $cacheFactory->shouldReceive('store')->with('array')->andReturn($cache); + $cacheFactory = Double::for(CacheFactory::class); + $cacheFactory->allows('store')->with('array')->returns($cache); $this->app->instance(CacheFactory::class, $cacheFactory); $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); - $job = m::mock(Job::class); - $job->shouldReceive('payload')->andReturn([ + $job = Double::for(Job::class); + $job->allows('payload')->returns([ 'deleteWhenMissingModels' => true, 'illuminate:log:context' => ['hidden' => $this->uniqueLockMetadata()], ]); - $job->shouldReceive('attempts')->andReturn(1); - $job->expects('resolveQueuedJobClass')->andReturn(CallQueuedHandlerExceptionThrower::class); + $job->allows('attempts')->returns(1); + $job->expects('resolveQueuedJobClass')->returns(CallQueuedHandlerExceptionThrower::class); $job->expects('delete'); $instance->call($job, [ @@ -245,28 +250,28 @@ public function testUniqueJobLockIsReleasedFromPayloadWhenDeletedForMissingModel public function testUniqueJobLockOwnerIsRestoredFromPayloadWhenDeletedForMissingModel(): void { - $lock = m::mock(Lock::class); + $lock = Double::for(Lock::class); $lock->expects('release'); - $cache = m::mock(Cache::class); - $cache->expects('getStore')->andReturn(new WorkerArrayStore); + $cache = Double::for(Cache::class, LockProvider::class); + $cache->expects('getStore')->returns(new WorkerArrayStore); $cache->expects('restoreLock') ->with('laravel_unique_job:TestJob:42', 'owner-token') - ->andReturn($lock); - $cache->shouldNotReceive('lock'); + ->returns($lock); + $cache->expects('lock')->never(); - $cacheFactory = m::mock(CacheFactory::class); - $cacheFactory->shouldReceive('store')->with('array')->andReturn($cache); + $cacheFactory = Double::for(CacheFactory::class); + $cacheFactory->allows('store')->with('array')->returns($cache); $this->app->instance(CacheFactory::class, $cacheFactory); $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); - $job = m::mock(Job::class); - $job->shouldReceive('payload')->andReturn([ + $job = Double::for(Job::class); + $job->allows('payload')->returns([ 'deleteWhenMissingModels' => true, 'illuminate:log:context' => ['hidden' => $this->uniqueLockMetadata('owner-token')], ]); - $job->expects('resolveQueuedJobClass')->andReturn(CallQueuedHandlerExceptionThrower::class); + $job->expects('resolveQueuedJobClass')->returns(CallQueuedHandlerExceptionThrower::class); $job->expects('delete'); $instance->call($job, [ @@ -347,14 +352,14 @@ public function testOwnerlessRegularUniqueListenerLockIsReleasedWhenFailingWithM #[TestWith([2, 0])] public function testMissingModelFailureReleasesAnOwnerlessUniqueUntilProcessingLockOnceBeforeProcessing(int $attempts, int $releases): void { - $lock = m::mock(Lock::class); + $lock = Double::for(Lock::class); $lock->expects('forceRelease')->times($releases); - $cache = m::mock(Cache::class); - $cache->shouldReceive('lock')->with('laravel_unique_job:TestJob:42')->andReturn($lock); + $cache = Double::for(Cache::class, LockProvider::class); + $cache->allows('lock')->with('laravel_unique_job:TestJob:42')->returns($lock); - $cacheFactory = m::mock(CacheFactory::class); - $cacheFactory->shouldReceive('store')->with('array')->andReturn($cache); + $cacheFactory = Double::for(CacheFactory::class); + $cacheFactory->allows('store')->with('array')->returns($cache); $this->app->instance(CacheFactory::class, $cacheFactory); $job = new CallQueuedHandlerMissingModelQueueJob($this->app, $this->missingModelPayload( @@ -399,13 +404,13 @@ public function testUniqueJobLockIsReleasedFromContextWhenFailingWithMissingMode public function testDebouncedJobEventIsSkippedWithoutListeners(): void { - $events = m::mock(EventDispatcher::class); - $events->expects('hasListeners')->with(JobDebounced::class)->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $events = Double::for(EventDispatcher::class); + $events->expects('hasListeners')->with(JobDebounced::class)->returns(false); + $events->expects('dispatch')->never(); $this->app->instance('events', $events); - $job = m::mock(Job::class); - $job->shouldNotReceive('getConnectionName'); + $job = Double::for(Job::class); + $job->expects('getConnectionName')->never(); $job->expects('delete'); $handler = new TestableCallQueuedHandler(new Dispatcher($this->app), $this->app); @@ -426,8 +431,8 @@ public function debounceId(): string } }; - $cache = m::mock(Cache::class); - $cache->expects('get')->with(DebounceLock::getKey($command))->andReturn('new-owner'); + $cache = Double::for(Cache::class); + $cache->expects('get')->with(DebounceLock::getKey($command))->returns('new-owner'); $this->app->instance(Cache::class, $cache); $handler = new TestableCallQueuedHandler(new Dispatcher($this->app), $this->app); @@ -439,8 +444,8 @@ public function testDebouncedJobEventRemainsVisibleToEventFake(): void { Event::fake([JobDebounced::class]); - $job = m::mock(Job::class); - $job->expects('getConnectionName')->andReturn('database'); + $job = Double::for(Job::class); + $job->expects('getConnectionName')->returns('database'); $job->expects('delete'); $command = new stdClass; diff --git a/tests/Integration/Queue/QueueConnectionTest.php b/tests/Integration/Queue/QueueConnectionTest.php index d046bb0cd..611bfd6c5 100644 --- a/tests/Integration/Queue/QueueConnectionTest.php +++ b/tests/Integration/Queue/QueueConnectionTest.php @@ -17,12 +17,15 @@ use Hypervel\Support\Facades\Bus; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; #[WithConfig('queue.default', 'sqs')] #[WithConfig('queue.connections.sqs.after_commit', true)] class QueueConnectionTest extends TestCase { + use VerifiesDoubles; + protected MockHandler $sqs; /** @@ -58,12 +61,12 @@ protected function tearDown(): void public function testJobWontGetDispatchedInsideATransaction(): void { $this->app->singleton('db.transactions', function (): DatabaseTransactionsManager { - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); $transactionManager->expects('callbackApplicableTransactions') - ->andReturn(new Collection([new DatabaseTransactionRecord('sqlite', 1)])); - $transactionManager->expects('addCallback')->andReturn(null); - $transactionManager->shouldNotReceive('addCallbackForRollback'); + ->returns(new Collection([new DatabaseTransactionRecord('sqlite', 1)])); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->never(); return $transactionManager; }); @@ -76,9 +79,9 @@ public function testJobWontGetDispatchedInsideATransaction(): void public function testJobWillGetDispatchedInsideATransactionWhenExplicitlyIndicated(): void { $this->app->singleton('db.transactions', function (): DatabaseTransactionsManager { - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->shouldNotReceive('addCallback')->andReturn(null); - $transactionManager->shouldNotReceive('addCallbackForRollback'); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('addCallback')->never(); + $transactionManager->expects('addCallbackForRollback')->never(); return $transactionManager; }); @@ -93,12 +96,12 @@ public function testJobWontGetDispatchedInsideATransactionWhenExplicitlyIndicate $this->app->make('config')->set('queue.connections.sqs.after_commit', false); $this->app->singleton('db.transactions', function (): DatabaseTransactionsManager { - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); $transactionManager->expects('callbackApplicableTransactions') - ->andReturn(new Collection([new DatabaseTransactionRecord('sqlite', 1)])); - $transactionManager->expects('addCallback')->andReturn(null); - $transactionManager->shouldNotReceive('addCallbackForRollback'); + ->returns(new Collection([new DatabaseTransactionRecord('sqlite', 1)])); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->never(); return $transactionManager; }); @@ -111,12 +114,12 @@ public function testJobWontGetDispatchedInsideATransactionWhenExplicitlyIndicate public function testUniqueJobWontGetDispatchedInsideATransaction(): void { $this->app->singleton('db.transactions', function (): DatabaseTransactionsManager { - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); $transactionManager->expects('callbackApplicableTransactions') - ->andReturn(new Collection([new DatabaseTransactionRecord('sqlite', 1)])); - $transactionManager->expects('addCallback')->andReturn(null); - $transactionManager->expects('addCallbackForRollback')->andReturn(null); + ->returns(new Collection([new DatabaseTransactionRecord('sqlite', 1)])); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); return $transactionManager; }); @@ -129,9 +132,9 @@ public function testUniqueJobWontGetDispatchedInsideATransaction(): void public function testUniqueJobWillGetDispatchedInsideATransactionWhenExplicitlyIndicated(): void { $this->app->singleton('db.transactions', function (): DatabaseTransactionsManager { - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->shouldNotReceive('addCallback')->andReturn(null); - $transactionManager->shouldNotReceive('addCallbackForRollback')->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('addCallback')->never(); + $transactionManager->expects('addCallbackForRollback')->never(); return $transactionManager; }); @@ -146,12 +149,12 @@ public function testUniqueJobWontGetDispatchedInsideATransactionWhenExplicitlyIn $this->app->make('config')->set('queue.connections.sqs.after_commit', false); $this->app->singleton('db.transactions', function (): DatabaseTransactionsManager { - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); $transactionManager->expects('callbackApplicableTransactions') - ->andReturn(new Collection([new DatabaseTransactionRecord('sqlite', 1)])); - $transactionManager->expects('addCallback')->andReturn(null); - $transactionManager->expects('addCallbackForRollback')->andReturn(null); + ->returns(new Collection([new DatabaseTransactionRecord('sqlite', 1)])); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); return $transactionManager; }); diff --git a/tests/Integration/Queue/Redis/RedisQueueTest.php b/tests/Integration/Queue/Redis/RedisQueueTest.php index ad004d5c6..2e13fa948 100644 --- a/tests/Integration/Queue/Redis/RedisQueueTest.php +++ b/tests/Integration/Queue/Redis/RedisQueueTest.php @@ -7,6 +7,7 @@ use Hypervel\Container\Container; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Contracts\Redis\Factory as RedisFactory; +use Hypervel\Events\Dispatcher as EventsDispatcher; use Hypervel\Foundation\Testing\Concerns\InteractsWithRedis; use Hypervel\Queue\Attributes\Delay; use Hypervel\Queue\Events\JobPayloadFinalizing; @@ -16,6 +17,8 @@ use Hypervel\Queue\Jobs\InspectedJob; use Hypervel\Queue\Jobs\RedisJob; use Hypervel\Queue\LuaScripts; +use Hypervel\Queue\Queue; +use Hypervel\Queue\QueueRoutes; use Hypervel\Queue\RedisQueue; use Hypervel\Redis\Exceptions\LuaScriptException; use Hypervel\Redis\RedisConnection; @@ -26,7 +29,9 @@ use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Queue\Fixtures\IntegerQueueName; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresPhpExtension; use Redis as PhpRedis; @@ -40,6 +45,7 @@ class RedisQueueTest extends TestCase { use InteractsWithRedis; use InteractsWithTime; + use VerifiesDoubles; private RedisQueue $queue; @@ -494,49 +500,48 @@ public function testSize(): void public function testPushJobQueueingAndJobQueuedEvents(): void { - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse(); - $events->expects('hasListeners')->with(JobQueueing::class)->andReturn(true); - $events->expects('hasListeners')->with(JobQueued::class)->andReturn(true); - $events->expects('dispatch')->withArgs(function (JobQueueing $jobQueueing): bool { - $this->assertInstanceOf(RedisQueueIntegrationTestJob::class, $jobQueueing->job); - - return true; - })->andReturnNull(); - $events->expects('dispatch')->withArgs(function (JobQueued $jobQueued): bool { - $this->assertInstanceOf(RedisQueueIntegrationTestJob::class, $jobQueued->job); - $this->assertIsString($jobQueued->id); - - return true; - })->andReturnNull(); - - $container = m::mock(Container::class)->makePartial(); - $container->expects('bound')->with('events')->andReturn(true)->times(3); - $container->expects('make')->with('events')->andReturn($events)->times(3); + $dispatched = []; + + $events = new EventsDispatcher; + $events->listen([JobQueueing::class, JobQueued::class], function (JobQueueing|JobQueued $event) use (&$dispatched): void { + $dispatched[] = $event; + }); + + $container = new Container; + $container->instance('events', $events); $queue = new RedisQueue($this->app->make(RedisFactory::class), $this->defaultQueueName()); $queue->setContainer($container); $queue->setConnectionName('redis'); - $queue->push(new RedisQueueIntegrationTestJob(5)); + $queue->push($job = new RedisQueueIntegrationTestJob(5)); + + $this->assertCount(2, $dispatched); + $this->assertInstanceOf(JobQueueing::class, $dispatched[0]); + $this->assertSame($job, $dispatched[0]->job); + $this->assertInstanceOf(JobQueued::class, $dispatched[1]); + $this->assertSame($job, $dispatched[1]->job); + $this->assertIsString($dispatched[1]->id); } public function testBulkJobQueuedEvent(): void { - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse()->times(3); - $events->expects('hasListeners')->with(JobQueueing::class)->andReturn(true)->times(3); - $events->expects('hasListeners')->with(JobQueued::class)->andReturn(true)->times(3); - $events->expects('dispatch')->with(m::type(JobQueueing::class))->andReturnNull()->times(3); - $events->expects('dispatch')->with(m::type(JobQueued::class))->andReturnNull()->times(3); - - $container = m::mock(Container::class)->makePartial(); - $container->expects('has')->with('db.transactions')->andReturnFalse(); - $container->expects('bound')->with('events')->andReturn(true)->times(9); - $container->expects('make')->with('events')->andReturn($events)->times(9); + $events = Double::for(Dispatcher::class); + $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->allows('bound')->with('queue.routes')->returns(false); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('has')->with('db.transactions')->returns(false); + $container->expects('bound')->with('events')->returns(true)->times(9); + $container->expects('make')->with('events')->returns($events)->times(9); $queue = new RedisQueue($this->app->make(RedisFactory::class), $this->defaultQueueName()); - $queue->setContainer($container); + $queue->setContainer($container->instance()); $queue->setConnectionName('redis'); $queue->bulk([ @@ -823,6 +828,67 @@ public function testBulkPushesAllJobsOntoQueue(): void $this->assertNull($this->queue->pop('bulk-test')); } + public function testPayloadHooksAreAppliedToTheQueuedPayload(): void + { + $default = $this->defaultQueueName(); + $this->setQueue($default); + + $receivedQueue = null; + + Queue::createPayloadUsing(function (string $connection, ?string $queue, array $payload) use (&$receivedQueue): array { + $receivedQueue = $queue; + + return ['custom' => 'taylor']; + }); + + Queue::createPayloadUsing(function (string $connection, ?string $queue, array $payload): array { + return ['bar' => 'foo']; + }); + + $this->queue->push('foo', ['data']); + + $payload = json_decode($this->queue->pop()->getRawBody(), true); + + $this->assertSame('foo', $payload['job']); + $this->assertSame(['data'], $payload['data']); + $this->assertSame('taylor', $payload['custom']); + $this->assertSame('foo', $payload['bar']); + + // The hook sees the queue name as configured, without any cluster hash tags... + $this->assertSame('queues:' . $default, $receivedQueue); + } + + public function testLaterAcceptsADateTimeDelay(): void + { + $default = $this->defaultQueueName(); + $this->setQueue($default); + + $due = new RedisQueueIntegrationTestJob(1); + $notDue = new RedisQueueIntegrationTestJob(2); + + $this->queue->later(CarbonImmutable::now()->subSeconds(100), $due); + $this->queue->later(CarbonImmutable::now()->addSeconds(1000), $notDue); + + $this->assertEquals($due, unserialize(json_decode($this->queue->pop()->getRawBody())->data->command)); + $this->assertNull($this->queue->pop()); + + $redisKey = $this->getQueueRedisKey($default); + $this->assertSame(1, $this->redisConnection()->zcard("{$redisKey}:delayed")); + } + + public function testQueueNamesCanBeEnums(): void + { + $this->setQueue('default'); + + $this->queue->push(new RedisQueueIntegrationTestJob(1), '', 'emails'); + $this->queue->push(new RedisQueueIntegrationTestJob(2), '', 'emails'); + $this->queue->push(new RedisQueueIntegrationTestJob(3), '', 'other'); + + $this->assertSame(2, $this->queue->size(RedisQueueIntegrationTestQueue::Emails)); + $this->assertSame(2, $this->queue->pendingJobs(RedisQueueIntegrationTestQueue::Emails)->count()); + $this->assertSame('emails', $this->queue->pendingJobs(RedisQueueIntegrationTestQueue::Emails)->first()->queue); + } + public function testBulkPushesDelayedJobsOntoDelayedQueue(): void { $this->setQueue('default'); @@ -1140,3 +1206,8 @@ public function __construct(int $i, public int $delay) parent::__construct($i); } } + +enum RedisQueueIntegrationTestQueue: string +{ + case Emails = 'emails'; +} diff --git a/tests/Integration/Queue/SkipIfBatchCancelledTest.php b/tests/Integration/Queue/SkipIfBatchCancelledTest.php index bc86e0daa..acc0eab45 100644 --- a/tests/Integration/Queue/SkipIfBatchCancelledTest.php +++ b/tests/Integration/Queue/SkipIfBatchCancelledTest.php @@ -13,10 +13,13 @@ use Hypervel\Queue\Middleware\SkipIfBatchCancelled; use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SkipIfBatchCancelledTest extends TestCase { + use VerifiesDoubles; + public function testJobsAreSkippedOnceBatchIsCancelled(): void { [$beforeCancelled] = (new SkipCancelledBatchableTestJob)->withFakeBatch(); @@ -52,12 +55,12 @@ protected function assertJobHandled(SkipCancelledBatchableTestJob $class, bool $ $class::$handled = false; $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app); - $job = m::mock(Job::class); + $job = Double::for(Job::class); - $job->expects('uuid')->andReturn('simple-test-uuid'); - $job->expects('hasFailed')->andReturn(false); - $job->shouldReceive('isReleased')->andReturn(false); - $job->expects('isDeletedOrReleased')->andReturn(false); + $job->expects('uuid')->returns('simple-test-uuid'); + $job->expects('hasFailed')->returns(false); + $job->allows('isReleased')->returns(false); + $job->expects('isDeletedOrReleased')->returns(false); $job->expects('delete'); $instance->call($job, [ diff --git a/tests/Integration/Queue/WorkCommandTest.php b/tests/Integration/Queue/WorkCommandTest.php index 67163607f..95760a020 100644 --- a/tests/Integration/Queue/WorkCommandTest.php +++ b/tests/Integration/Queue/WorkCommandTest.php @@ -20,13 +20,16 @@ use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\Attributes\WithMigration; use Hypervel\Tests\Integration\Queue\QueueTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; #[WithMigration] #[WithMigration('queue')] class WorkCommandTest extends QueueTestCase { + use VerifiesDoubles; + /** * Define the test environment. */ @@ -299,12 +302,12 @@ public function testDisableLastRestartCheck(): void Worker::$restartable = false; - $cache = m::mock(Repository::class); - $cache->shouldNotReceive('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY); - $cache->expects('get')->with('illuminate:queues:paused', false)->andReturn(false); + $cache = Double::for(Repository::class); + $cache->expects('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY)->never(); + $cache->expects('get')->with('illuminate:queues:paused', false)->returns(false); $cache->expects('get') ->with(['illuminate:queue:paused:database:default']) - ->andReturn(['illuminate:queue:paused:database:default' => false]); + ->returns(['illuminate:queue:paused:database:default' => false]); Cache::expects('store')->twice()->andReturn($cache); Cache::shouldNotReceive('driver'); @@ -329,9 +332,9 @@ public function testDisablePauseQueueCheck(): void Worker::$pausable = false; - $cache = m::mock(Repository::class); + $cache = Double::for(Repository::class); - $cache->expects('get')->twice()->with(Worker::RESTART_SIGNAL_CACHE_KEY)->andReturn(null); + $cache->expects('get')->times(2)->with(Worker::RESTART_SIGNAL_CACHE_KEY)->returns(null); Cache::expects('store')->andReturn($cache); Cache::shouldNotReceive('driver'); diff --git a/tests/Integration/Session/AuthenticateSessionTest.php b/tests/Integration/Session/AuthenticateSessionTest.php new file mode 100644 index 000000000..beba3e7f9 --- /dev/null +++ b/tests/Integration/Session/AuthenticateSessionTest.php @@ -0,0 +1,294 @@ +make('config')->set('auth.providers.users.model', User::class); + + $app->make('config')->set('auth.guards.unchecked', ['driver' => 'unchecked-session', 'provider' => 'users']); + + Auth::extend('unchecked-session', function (ApplicationContract $app, string $name, array $config): UncheckedRecallerSessionGuard { + $guard = new UncheckedRecallerSessionGuard( + $name, + Auth::createUserProvider($config['provider']), + $app->make('session.store'), + $app, + hashKey: $app->make('config')->string('app.key'), + ); + + $guard->setCookieJar($app->make('cookie')); + + return $guard; + }); + } + + /** + * Define the test routes. + */ + protected function defineRoutes(Router $router): void + { + $router->get('login', fn (): string => 'login')->name('login'); + $router->get('without-session', fn (): string => 'ok')->middleware(AuthenticateSession::class); + // Remember-login state belongs to the request coroutine, so expose it in the response. + $router->get('protected', fn (): string => Auth::guard()->viaRemember() ? 'remembered' : 'ok') + ->middleware(['web', AuthenticateSession::class]); + } + + public function testItPassesThroughWithoutASession(): void + { + $this->actingAs(UserFactory::new()->create()); + + $this->get('without-session')->assertOk(); + } + + public function testItPassesThroughForGuests(): void + { + $this->get('protected')->assertOk()->assertSessionMissing('password_hash_web'); + } + + public function testItPassesThroughForUsersWithoutAPassword(): void + { + $this->actingAs(UserFactory::new()->make(['password' => null])); + + $this->get('protected')->assertOk()->assertSessionMissing('password_hash_web'); + } + + public function testItStoresThePasswordHashInTheSession(): void + { + $user = UserFactory::new()->create(); + + $this->actingAs($user)->get('protected') + ->assertOk() + ->assertSessionHas('password_hash_web', $this->hashFor($user)); + } + + #[DataProvider('authenticatedRememberCookies')] + public function testItKeepsTheSessionWhenThePasswordHashMatches(bool $malformedCookie): void + { + $user = UserFactory::new()->create(); + + if ($malformedCookie) { + $this->withCookie(Auth::guard('web')->getRecallerName(), 'a|b'); + } + + $this->actingAs($user) + ->withSession(['password_hash_web' => $this->hashFor($user), 'a' => '1']) + ->get('protected') + ->assertOk() + ->assertSessionHas(['password_hash_web' => $this->hashFor($user), 'a' => '1']); + } + + /** + * Provide cookies that must not affect an already authenticated session. + */ + public static function authenticatedRememberCookies(): array + { + return ['no cookie' => [false], 'malformed cookie' => [true]]; + } + + public function testItLogsOutWhenThePasswordHashDoesNotMatch(): void + { + $user = UserFactory::new()->create(); + + $this->actingAs($user) + ->withSession(['password_hash_web' => 'invalid-password', 'a' => '1']) + ->getJson('protected') + ->assertUnauthorized() + ->assertJsonPath('message', 'Unauthenticated.') + ->assertSessionMissing('password_hash_web') + ->assertSessionMissing('a'); + + $this->assertGuest(); + } + + public function testItRedirectsUsingTheConfiguredCallback(): void + { + // The default redirect is registered once the HTTP kernel is resolved... + $this->app->make(Kernel::class); + + AuthenticateSession::redirectUsing(fn (): string => '/i-wanna-go-home'); + + $user = UserFactory::new()->create(); + + $this->actingAs($user) + ->withSession(['password_hash_web' => 'invalid-password']) + ->get('protected') + ->assertRedirect('/i-wanna-go-home'); + } + + public function testItAcceptsAValidRememberCookie(): void + { + $user = UserFactory::new()->create(); + + $this->withRecaller($user, $this->hashFor($user)) + ->withSession(['password_hash_web' => $this->hashFor($user), 'a' => '1']) + ->get('protected') + ->assertOk() + ->assertSessionHas('a', '1') + ->assertSeeText('remembered'); + } + + public function testAuthManagerRedirectGuestsToConfiguresSessionMismatchRedirect(): void + { + $this->app->make(Kernel::class); + Auth::redirectGuestsTo('/session-mismatch'); + + // Isolate AuthenticateSession's own slot so this tests the aggregate's direct registration. + AuthenticationException::flushState(); + + $this->actingAs(UserFactory::new()->create()) + ->withSession(['password_hash_web' => 'invalid-password']) + ->get('protected') + ->assertRedirect('/session-mismatch'); + } + + public function testItLogsOutWhenTheRememberedSessionHashDoesNotMatch(): void + { + $user = UserFactory::new()->create(); + + $this->withRecaller($user, $this->hashFor($user)) + ->withSession(['password_hash_web' => 'invalid-password', 'a' => '1']) + ->get('protected') + ->assertRedirect(route('login')) + ->assertSessionMissing('password_hash_web') + ->assertSessionMissing('a'); + } + + public function testItIgnoresARememberCookieWithAStaleHash(): void + { + $user = UserFactory::new()->create(); + + $this->withRecaller($user, $this->hashFor($user) . '-stale') + ->withSession(['a' => '1']) + ->get('protected') + ->assertOk() + ->assertSessionHas('a', '1') + ->assertSessionMissing('password_hash_web'); + + $this->assertGuest(); + } + + #[DataProvider('invalidRememberHashes')] + public function testItLogsOutWhenACustomGuardRemembersTheUserWithoutCheckingTheCookieHash(bool $rawHash): void + { + $user = UserFactory::new()->create(); + + $this->app->make('config')->set('auth.defaults.guard', 'unchecked'); + + $name = Auth::guard('unchecked')->getRecallerName(); + + $hash = $rawHash ? $user->password : 'stale-hash'; + + // The built-in guard rejects a stale hash itself, but a custom guard might not... + $this->withCookie($name, "{$user->getAuthIdentifier()}|{$user->getRememberToken()}|{$hash}") + ->withSession(['a' => '1']) + ->get('protected') + ->assertRedirect(route('login')) + ->assertSessionMissing('a'); + } + + /** + * Provide unsupported remember-cookie hashes. + */ + public static function invalidRememberHashes(): array + { + return ['stale hash' => [false], 'raw hash' => [true]]; + } + + // REMOVED: Laravel's raw-hash upgrade and guards without hashPasswordForCookie(); + // Hypervel supports only HMAC session and remember-cookie artifacts. + + #[DataProvider('invalidSessionHashes')] + public function testItRejectsRawOrMalformedSessionHashes(bool $rawHash): void + { + $user = UserFactory::new()->create(); + + $this->actingAs($user) + ->withSession(['password_hash_web' => $rawHash ? $user->password : ['not-a-password-hash'], 'a' => '1']) + ->getJson('protected') + ->assertUnauthorized() + ->assertSessionMissing('password_hash_web') + ->assertSessionMissing('a'); + + $this->assertGuest(); + } + + /** + * Provide unsupported password-hash representations. + */ + public static function invalidSessionHashes(): array + { + return ['raw hash' => [true], 'malformed hash' => [false]]; + } + + /** + * Get the password hash stored in session artifacts. + */ + protected function hashFor(User $user): string + { + return Auth::guard('web')->hashPasswordForCookie($user->password); + } + + /** + * Add the remember cookie for the user. + */ + protected function withRecaller(User $user, string $hash): static + { + $name = Auth::guard('web')->getRecallerName(); + + return $this->withCookie($name, "{$user->getAuthIdentifier()}|{$user->getRememberToken()}|{$hash}"); + } +} + +class UncheckedRecallerSessionGuard extends SessionGuard +{ + /** + * Recall the user without verifying the password hash. + */ + protected function userFromRecaller(Recaller $recaller): ?Authenticatable + { + if (! $recaller->valid() || $this->getContextState('recallAttempted', false)) { + return null; + } + + $this->setContextState('recallAttempted', true); + + $user = $this->provider->retrieveByToken( + $recaller->id(), + $recaller->token() + ); + + $this->setContextState('viaRemember', $user !== null); + + return $user; + } +} diff --git a/tests/Mail/MailMailableTest.php b/tests/Mail/MailMailableTest.php index 07517c99c..7fe110081 100644 --- a/tests/Mail/MailMailableTest.php +++ b/tests/Mail/MailMailableTest.php @@ -7,23 +7,21 @@ use Closure; use Hypervel\Contracts\Filesystem\Factory as FilesystemFactory; use Hypervel\Contracts\Mail\Attachable; -use Hypervel\Contracts\Mail\Mailer as MailerContract; use Hypervel\Contracts\Support\Htmlable; use Hypervel\Contracts\View\Factory as ViewFactory; -use Hypervel\Contracts\View\View as ViewContract; use Hypervel\Filesystem\FilesystemAdapter; use Hypervel\Mail\Attachment; use Hypervel\Mail\Mailable; use Hypervel\Mail\Mailables\Envelope; use Hypervel\Mail\Mailables\Headers; use Hypervel\Mail\Mailer; -use Hypervel\Mail\MailManager; use Hypervel\Mail\Message; use Hypervel\Mail\Transport\ArrayTransport; use Hypervel\Support\ClassInvoker; use Hypervel\Support\HtmlString; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\AssertionFailedError; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Email; @@ -31,9 +29,11 @@ class MailMailableTest extends TestCase { + use VerifiesDoubles; + public function testMailableSetsRecipientsCorrectly(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new WelcomeMailableStub; $mailable->to('taylor@laravel.com'); @@ -119,7 +119,7 @@ public function testMailableSetsRecipientsCorrectly(): void public function testMailableSetsCcRecipientsCorrectly(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new WelcomeMailableStub; $mailable->cc('taylor@laravel.com'); @@ -210,7 +210,7 @@ public function testMailableSetsCcRecipientsCorrectly(): void public function testMailableSetsBccRecipientsCorrectly(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new WelcomeMailableStub; $mailable->bcc('taylor@laravel.com'); @@ -301,7 +301,7 @@ public function testMailableSetsBccRecipientsCorrectly(): void public function testMailableSetsReplyToCorrectly(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new WelcomeMailableStub; $mailable->replyTo('taylor@laravel.com'); @@ -381,7 +381,7 @@ public function testMailableSetsReplyToCorrectly(): void public function testMailableSetsFromCorrectly(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new WelcomeMailableStub; $mailable->from('taylor@laravel.com'); @@ -629,7 +629,7 @@ public function testMailerMayBeSet(): void public function testMailablePriorityGetsSent(): void { - $view = $this->mockView(); + $view = Double::for(ViewFactory::class); $mailer = new Mailer('array', $view, new ArrayTransport); @@ -648,7 +648,7 @@ public function testMailablePriorityGetsSent(): void public function testMailableIsReleasedWithoutGarbageCollectionAfterSettingPriority(): void { - $mailer = new Mailer('array', $this->mockView(), new ArrayTransport); + $mailer = new Mailer('array', Double::for(ViewFactory::class), new ArrayTransport); $garbageCollectionEnabled = gc_enabled(); gc_disable(); @@ -674,7 +674,7 @@ public function testMailableIsReleasedWithoutGarbageCollectionAfterSettingPriori public function testEnvelopeCallbackCanInspectAndReplaceRenderedContent(): void { - $view = $this->mockView(); + $view = Double::for(ViewFactory::class); $mailer = new Mailer('array', $view, new ArrayTransport); $renderedContent = null; @@ -736,8 +736,8 @@ public function testMailableMergeMetadata(): void $this->assertTrue($mailable->hasMetadata('shipping_fee', 20)); $this->assertTrue($mailable->hasMetadata('total', 1670)); - $this->mockContainer(); - $view = $this->mockView(); + $this->stubMailer(); + $view = Double::for(ViewFactory::class); $mailer = new Mailer('array', $view, new ArrayTransport); $sentMessage = $mailer->send($mailable); @@ -752,9 +752,9 @@ public function testMailableMergeMetadata(): void public function testMailableMetadataGetsSent(): void { - $this->mockContainer(); + $this->stubMailer(); - $view = $this->mockView(); + $view = Double::for(ViewFactory::class); $mailer = new Mailer('array', $view, new ArrayTransport); @@ -797,9 +797,9 @@ public function envelope(): Envelope public function testMailableTagGetsSent(): void { - $this->mockContainer(); + $this->stubMailer(); - $view = $this->mockView(); + $view = Double::for(ViewFactory::class); $mailer = new Mailer('array', $view, new ArrayTransport); @@ -835,7 +835,7 @@ public function testMailableTagGetsSent(): void public function testAssertionDiagnosticsDoNotInvokeEnvelopeAgain(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new class extends Mailable { public int $envelopeCalls = 0; @@ -882,7 +882,7 @@ public function envelope(): Envelope public function testTagAssertionReportsWhenMailableHasNoTags(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new Mailable; $mailable->html('test content'); @@ -1016,7 +1016,7 @@ public function toMailAttachment(): Attachment public function testHasAttachmentWithEnvelopeAttachments(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new class extends Mailable { public function envelope(): Envelope { @@ -1061,14 +1061,14 @@ public function envelope(): Envelope public function testHasAttachmentWithDeclaredStorageAttachmentsAndNoEnvelope(): void { - $storage = m::mock(FilesystemAdapter::class); - $storage->shouldReceive('mimeType')->with('report.txt')->andReturn('text/plain'); - $storage->shouldReceive('mimeType')->with('other.txt')->andReturn('text/plain'); - $storage->shouldReceive('get')->with('report.txt')->andReturn('report content'); - $storage->shouldReceive('get')->with('other.txt')->andReturn('other content'); - - $factory = m::mock(FilesystemFactory::class); - $factory->shouldReceive('disk')->with('documents')->andReturn($storage); + $storage = Double::for(FilesystemAdapter::class); + $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->allows('disk')->with('documents')->returns($storage); $this->app->instance(FilesystemFactory::class, $factory); $mailable = new class extends Mailable { @@ -1248,12 +1248,12 @@ public function testItCanCheckForStorageBasedAttachments(): void public function testStorageAttachmentOmitsFailedMimeDetection(): void { - $storage = m::mock(FilesystemAdapter::class); - $storage->expects('mimeType')->with('report.txt')->andReturnFalse(); - $storage->expects('get')->with('report.txt')->andReturn('file content'); + $storage = Double::for(FilesystemAdapter::class); + $storage->expects('mimeType')->with('report.txt')->returns(false); + $storage->expects('get')->with('report.txt')->returns('file content'); - $factory = m::mock(FilesystemFactory::class); - $factory->expects('disk')->with('documents')->andReturn($storage); + $factory = Double::for(FilesystemFactory::class); + $factory->expects('disk')->with('documents')->returns($storage); $this->app->instance(FilesystemFactory::class, $factory); $mailable = new Mailable; @@ -1269,12 +1269,12 @@ public function testStorageAttachmentOmitsFailedMimeDetection(): void public function testExplicitStorageAttachmentMimeSkipsDetection(): void { - $storage = m::mock(FilesystemAdapter::class); - $storage->shouldNotReceive('mimeType'); - $storage->expects('get')->with('report.txt')->andReturn('file content'); + $storage = Double::for(FilesystemAdapter::class); + $storage->expects('mimeType')->never(); + $storage->expects('get')->with('report.txt')->returns('file content'); - $factory = m::mock(FilesystemFactory::class); - $factory->expects('disk')->with('documents')->andReturn($storage); + $factory = Double::for(FilesystemFactory::class); + $factory->expects('disk')->with('documents')->returns($storage); $this->app->instance(FilesystemFactory::class, $factory); $mailable = new Mailable; @@ -1290,7 +1290,7 @@ public function testExplicitStorageAttachmentMimeSkipsDetection(): void public function testAssertHasNoAttachments(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new class extends Mailable { /** @@ -1323,7 +1323,7 @@ public function build(): void public function testAssertHasAttachment(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new class extends Mailable { public function build(): void @@ -1350,7 +1350,7 @@ public function build(): void public function testAssertHasAttachedData(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new class extends Mailable { public function build(): void @@ -1377,7 +1377,7 @@ public function build(): void public function testAssertHasAttachmentFromStorage(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new class extends Mailable { public function build(): void @@ -1404,7 +1404,7 @@ public function build(): void public function testAssertHasSubject(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new class extends Mailable { public function build(): void @@ -1431,9 +1431,9 @@ public function build(): void public function testSubjectAssertionMatchesTheDeliveredDefaultSubject(): void { - $this->mockContainer(); + $this->stubMailer(); - $mailer = new Mailer('array', $this->mockView(), new ArrayTransport); + $mailer = new Mailer('array', Double::for(ViewFactory::class), new ArrayTransport); foreach ([new WelcomeMailableStub, (new WelcomeMailableStub)->subject('0')] as $mailable) { $mailable->from('sender@example.com')->to('recipient@example.com')->html('test content'); @@ -1446,7 +1446,7 @@ public function testSubjectAssertionMatchesTheDeliveredDefaultSubject(): void public function testSubjectAssertionReportsHydratedEnvelopeSubject(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new class extends Mailable { /** @@ -1466,7 +1466,7 @@ public function envelope(): Envelope public function testMailableHeadersGetSent(): void { - $view = $this->mockView(); + $view = Double::for(ViewFactory::class); $mailer = new Mailer('array', $view, new ArrayTransport); @@ -1490,7 +1490,7 @@ public function testMailableHeadersGetSent(): void public function testMailableIsReleasedWithoutGarbageCollectionAfterSendingWithHeaders(): void { - $mailer = new Mailer('array', $this->mockView(), new ArrayTransport); + $mailer = new Mailer('array', Double::for(ViewFactory::class), new ArrayTransport); $garbageCollectionEnabled = gc_enabled(); gc_disable(); @@ -1515,7 +1515,7 @@ public function testMailableIsReleasedWithoutGarbageCollectionAfterSendingWithHe public function testMailableAttributesInBuild(): void { - $this->mockContainer(); + $this->stubMailer(); $mailable = new class extends Mailable { public function build(): void @@ -1544,7 +1544,7 @@ public function build(): void public function testMailablesCanBeTapped(): void { - $this->mockContainer(); + $this->stubMailer(); $mail = new WelcomeMailableStub; @@ -1557,29 +1557,17 @@ public function testMailablesCanBeTapped(): void }); } - protected function mockContainer(): void + /** + * Stub rendering for mailable assertions. + */ + protected function stubMailer(): void { - $mailer = m::mock(MailerContract::class); - $mailer->shouldReceive('render') - ->andReturn(''); + $mailer = Double::for(Mailer::class); + $mailer->allows('render') + ->returns(''); - $this->app->singleton('mail.manager', fn ($app) => new MailManager($app)); - $this->app->instance('view', m::mock(ViewFactory::class)); $this->app->instance('mailer', $mailer); } - - protected function mockView(): ViewFactory - { - $viewInterface = m::mock(ViewContract::class); - $viewInterface->shouldReceive('render') - ->andReturn('rendered.view'); - - $view = m::mock(ViewFactory::class); - $view->shouldReceive('make') - ->andReturn($viewInterface); - - return $view; - } } class MailableHeadersStub extends Mailable diff --git a/tests/Mail/MailMailerTest.php b/tests/Mail/MailMailerTest.php index 3e0a77cba..bb3991788 100644 --- a/tests/Mail/MailMailerTest.php +++ b/tests/Mail/MailMailerTest.php @@ -22,12 +22,15 @@ use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Exception\InvalidArgumentException as MimeInvalidArgumentException; class MailMailerTest extends TestCase { + use VerifiesDoubles; + public function testMailerSendSendsMessageWithProperViewContent(): void { $view = $this->viewFactory('rendered.view'); @@ -84,8 +87,8 @@ public function testMailerSendSendsMessageWithCcAndBccRecipients(): void public function testMailerSendSendsMessageWithProperViewContentUsingHtmlStrings(): void { - $view = m::mock(ViewFactory::class); - $view->shouldNotReceive('make'); + $view = Double::for(ViewFactory::class); + $view->expects('make')->never(); $mailer = new Mailer('array', $view, new ArrayTransport); @@ -104,8 +107,8 @@ function (Message $message): void { public function testMailerSendSendsMessageWithProperViewContentUsingStringCallbacks(): void { - $view = m::mock(ViewFactory::class); - $view->shouldNotReceive('make'); + $view = Double::for(ViewFactory::class); + $view->expects('make')->never(); $mailer = new Mailer('array', $view, new ArrayTransport); @@ -135,8 +138,8 @@ function (Message $message): void { public function testMailerSendSendsMessageWithProperViewContentUsingHtmlMethod(): void { - $view = m::mock(ViewFactory::class); - $view->shouldNotReceive('make'); + $view = Double::for(ViewFactory::class); + $view->expects('make')->never(); $mailer = new Mailer('array', $view, new ArrayTransport); @@ -347,11 +350,11 @@ public function testEventsAreSkippedWhenNoListenersAreRegistered(): void { $view = $this->viewFactory('rendered.view'); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(MessageSending::class)->andReturn(false); - $events->expects('hasListeners')->with(MessageSent::class)->andReturn(false); - $events->shouldNotReceive('until'); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(MessageSending::class)->returns(false); + $events->expects('hasListeners')->with(MessageSent::class)->returns(false); + $events->expects('until')->never(); + $events->expects('dispatch')->never(); $mailer = new Mailer('array', $view, new ArrayTransport, $events); @@ -366,7 +369,7 @@ public function testMacroable(): void return 'bar'; }); - $mailer = new Mailer('array', m::mock(ViewFactory::class), new ArrayTransport); + $mailer = new Mailer('array', Double::for(ViewFactory::class), new ArrayTransport); $this->assertSame( 'bar', @@ -376,8 +379,8 @@ public function testMacroable(): void public function testSendQueuedMailableReturnsNull(): void { - $view = m::mock(ViewFactory::class); - $view->shouldNotReceive('make'); + $view = Double::for(ViewFactory::class); + $view->expects('make')->never(); $queueFake = new QueueFake($this->app); $mailer = new Mailer('array', $view, new ArrayTransport); @@ -397,14 +400,17 @@ public function testSendQueuedMailableReturnsNull(): void */ protected function viewFactory(string ...$rendered): ViewFactory { - $factory = m::mock(ViewFactory::class); + $factory = Double::for(ViewFactory::class); + $views = []; foreach ($rendered as $contents) { - $view = m::mock(ViewContract::class); - $view->expects('render')->andReturn($contents); - $factory->expects('make')->andReturn($view); + $view = Double::for(ViewContract::class); + $view->expects('render')->returns($contents); + $views[] = $view; } + $factory->expects('make')->times(count($views))->returns(...$views); + return $factory; } } diff --git a/tests/Mail/MailResendTransportTest.php b/tests/Mail/MailResendTransportTest.php index 56d46d210..987ead21a 100644 --- a/tests/Mail/MailResendTransportTest.php +++ b/tests/Mail/MailResendTransportTest.php @@ -5,24 +5,22 @@ namespace Hypervel\Tests\Mail; use Exception; -use Hypervel\Contracts\View\Factory as ViewFactory; use Hypervel\Mail\MailManager; use Hypervel\Mail\Transport\ResendTransport; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Resend\Contracts\Client; use Resend\Email as ResendEmail; +use Resend\Service\Email as EmailService; use Symfony\Component\Mailer\Exception\TransportException; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Email; class MailResendTransportTest extends TestCase { - protected function setUp(): void - { - parent::setUp(); - $this->app->instance('view', m::mock(ViewFactory::class)); - } + use VerifiesDoubles; public function testGetTransport(): void { @@ -50,9 +48,9 @@ public function testSend(): void $message->bcc('bcc@example.com'); $message->replyTo(new Address('reply@example.com', 'Reply')); - $emails = m::mock(); - $emails->shouldReceive('send')->once() - ->with(m::on(function ($arg) { + $emails = Double::for(EmailService::class); + $emails->expects('send') + ->with(Argument::satisfies(function (array $arg): bool { return $arg['from'] === 'sender@example.com' && $arg['to'] === ['recipient@example.com'] && $arg['cc'] === ['cc@example.com'] @@ -62,10 +60,16 @@ public function testSend(): void && $arg['html'] === '

Test body

' && $arg['text'] === 'Test body'; })) - ->andReturn(new ResendEmail(['id' => 'resend-message-id'])); + ->returns(new ResendEmail(['id' => 'resend-message-id'])); - $client = m::mock(Client::class); - $client->emails = $emails; + $client = new class($emails) implements Client { + /** + * Create a client backed by the test email service. + */ + public function __construct(public EmailService $emails) + { + } + }; $sentMessage = (new ResendTransport($client))->send($message); @@ -84,12 +88,18 @@ public function testSendError(): void $message->sender('sender@example.com'); $message->to('recipient@example.com'); - $emails = m::mock(); - $emails->shouldReceive('send')->once() - ->andThrow(new Exception('API key is invalid')); - - $client = m::mock(Client::class); - $client->emails = $emails; + $emails = Double::for(EmailService::class); + $emails->expects('send') + ->throws(new Exception('API key is invalid')); + + $client = new class($emails) implements Client { + /** + * Create a client backed by the test email service. + */ + public function __construct(public EmailService $emails) + { + } + }; $this->expectException(TransportException::class); $this->expectExceptionMessageIs('Request to Resend API failed. Reason: API key is invalid.'); diff --git a/tests/Mail/MailableQueuedTest.php b/tests/Mail/MailableQueuedTest.php index d8e13de34..9561895ba 100644 --- a/tests/Mail/MailableQueuedTest.php +++ b/tests/Mail/MailableQueuedTest.php @@ -5,9 +5,9 @@ namespace Hypervel\Tests\Mail; use Hypervel\Bus\Queueable; -use Hypervel\Contracts\Mail\Mailable as MailableContract; use Hypervel\Contracts\Queue\Queue as QueueContract; use Hypervel\Contracts\Queue\ShouldQueue; +use Hypervel\Contracts\View\Factory; use Hypervel\Mail\Mailable; use Hypervel\Mail\Mailer; use Hypervel\Mail\SendQueuedMailable; @@ -20,22 +20,15 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Testbench\TestCase; -use Hypervel\View\Factory; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Laravel\SerializableClosure\SerializableClosure; -use Mockery as m; use Symfony\Component\Mailer\Transport\TransportInterface; use Throwable; class MailableQueuedTest extends TestCase { - /** - * Set up the test environment. - */ - protected function setUp(): void - { - parent::setUp(); - $this->app->instance(MailableContract::class, m::mock(MailableContract::class)); - } + use VerifiesDoubles; public function testQueuedMailableSent(): void { @@ -373,7 +366,7 @@ public function testQueueMethodsPreserveStringAndEnumQueueNames(): void */ protected function getMocks(): array { - return ['smtp', m::mock(Factory::class), m::mock(TransportInterface::class)]; + return ['smtp', Double::for(Factory::class), Double::for(TransportInterface::class)]; } /** diff --git a/tests/Notifications/NotificationBroadcastChannelTest.php b/tests/Notifications/NotificationBroadcastChannelTest.php index 7f7472a32..c5ee234b9 100644 --- a/tests/Notifications/NotificationBroadcastChannelTest.php +++ b/tests/Notifications/NotificationBroadcastChannelTest.php @@ -12,20 +12,24 @@ use Hypervel\Notifications\Messages\BroadcastMessage; use Hypervel\Notifications\Notification; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use stdClass; class NotificationBroadcastChannelTest extends TestCase { + use VerifiesDoubles; + public function testDatabaseChannelCreatesDatabaseRecordWithProperData(): void { $notification = new NotificationBroadcastChannelTestNotification; $notification->id = '1'; $notifiable = new stdClass; - $events = m::mock(Dispatcher::class); - $events->expects('dispatch')->with(m::type(BroadcastNotificationCreated::class)); + $events = Double::for(Dispatcher::class); + $events->expects('dispatch')->with(Argument::type(BroadcastNotificationCreated::class)); $channel = new BroadcastChannel($events); $channel->send($notifiable, $notification); } @@ -134,8 +138,8 @@ public function testNotificationIsBroadcastedNow(): void $notification->id = '1'; $notifiable = new stdClass; - $events = m::mock(Dispatcher::class); - $events->expects('dispatch')->with(m::on(function (BroadcastNotificationCreated $event): bool { + $events = Double::for(Dispatcher::class); + $events->expects('dispatch')->with(Argument::satisfies(function (BroadcastNotificationCreated $event): bool { return $event->connection === 'sync'; })); $channel = new BroadcastChannel($events); diff --git a/tests/Notifications/NotificationChannelManagerTest.php b/tests/Notifications/NotificationChannelManagerTest.php index 054acdaf2..c8c270b57 100644 --- a/tests/Notifications/NotificationChannelManagerTest.php +++ b/tests/Notifications/NotificationChannelManagerTest.php @@ -38,17 +38,20 @@ use Hypervel\Tests\Notifications\Fixtures\ChannelSpy; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Laravel\SerializableClosure\SerializableClosure; -use Mockery as m; -use Mockery\MockInterface; use stdClass; class NotificationChannelManagerTest extends TestCase { + use VerifiesDoubles; + public function testGetDefaultChannel(): void { $container = $this->getContainer(); - $container->instance(MailChannel::class, m::mock(MailChannel::class)); + $container->instance(MailChannel::class, Double::for(MailChannel::class)); $manager = new ChannelManager($container); @@ -58,11 +61,11 @@ public function testGetDefaultChannel(): void public function testGetCustomChannelResolvesDirectly(): void { $container = $this->getContainer(); - $container->instance(MailChannel::class, m::mock(MailChannel::class)); + $container->instance(MailChannel::class, Double::for(MailChannel::class)); $manager = new ChannelManager($container); - $channel = m::mock('customChannel'); - $manager->extend('test', fn (): MockInterface => $channel); + $channel = new NotificationChannelManagerTestCustomChannel; + $manager->extend('test', fn (): NotificationChannelManagerTestCustomChannel => $channel); $this->assertSame($channel, $manager->channel('test')); } @@ -70,8 +73,8 @@ public function testGetCustomChannelResolvesDirectly(): void public function testIntegerEnumChannelNamesAreNormalizedByTheManagerAndFake(): void { $manager = new ChannelManager($this->getContainer()); - $channel = m::mock('customChannel'); - $manager->extend('0', fn (): MockInterface => $channel); + $channel = new NotificationChannelManagerTestCustomChannel; + $manager->extend('0', fn (): NotificationChannelManagerTestCustomChannel => $channel); $this->assertSame($channel, $manager->channel(NotificationChannelManagerTestIntIdentifier::Zero)); $this->assertNull((new NotificationFake)->channel(NotificationChannelManagerTestIntIdentifier::Zero)); @@ -109,9 +112,9 @@ public function testNotificationCanBeDispatchedToDriver(): void $events = new EventFake(new EventsDispatcher); $container->instance(Dispatcher::class, $events); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); + $manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container)); $driver = new ChannelSpy; - $manager->expects('driver')->andReturn($driver); + $manager->expects('driver')->returns($driver); $manager->send($notifiable = new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerTestNotification); @@ -164,9 +167,9 @@ public function testNotificationNotSentOnHalt(): void $events->listen(NotificationSent::class, function (NotificationSent $event) use (&$sent): void { $sent[] = $event; }); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); + $manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container)); $driver = new ChannelSpy; - $manager->expects('driver')->andReturn($driver); + $manager->expects('driver')->returns($driver); $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestNotificationWithTwoChannels); @@ -182,8 +185,8 @@ public function testNotificationNotSentWhenCancelled(): void $events = new EventFake(new EventsDispatcher); $container->instance(Dispatcher::class, $events); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); - $manager->shouldNotReceive('driver'); + $manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container)); + $manager->expects('driver')->never(); $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestCancelledNotification); @@ -197,9 +200,9 @@ public function testNotificationSentWhenNotCancelled(): void $events = new EventFake(new EventsDispatcher); $container->instance(Dispatcher::class, $events); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); + $manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container)); $driver = new ChannelSpy; - $manager->expects('driver')->andReturn($driver); + $manager->expects('driver')->returns($driver); $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestNotCancelledNotification); @@ -215,10 +218,10 @@ public function testNotificationNotSentWhenFailed(): void $events = new EventFake(new EventsDispatcher); $container->instance(Dispatcher::class, $events); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); + $manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container)); $driver = new ChannelSpy; $driver->exception = $exception = new Exception; - $manager->expects('driver')->andReturn($driver); + $manager->expects('driver')->returns($driver); try { $manager->send(new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerTestNotification); @@ -433,20 +436,20 @@ public function testQueuedNotificationForwardsArrayCallableDeduplicatorToQueueJo $deduplicator = [NotificationChannelManagerTestDeduplicator::class, 'resolve']; $container = $this->getContainer(); - $container->instance('queue.routes', $queueRoutes = m::mock(QueueRoutes::class)); - $queueRoutes->expects('getQueue')->times(2)->andReturn(null); - $queueRoutes->expects('getConnection')->times(2)->andReturn(null); + $container->instance('queue.routes', $queueRoutes = Double::for(QueueRoutes::class)); + $queueRoutes->expects('getQueue')->times(2)->returns(null); + $queueRoutes->expects('getConnection')->times(2)->returns(null); $container->make(BusDispatcherContract::class) - ->expects('dispatch')->times(2)->withArgs(function (SendQueuedNotifications $job) use ($deduplicator): bool { + ->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; - }); + })); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); + $manager = new ChannelManager($container); $notification = (new NotificationChannelManagerTestQueuedNotificationWithTwoChannels)->withDeduplicator($deduplicator); $manager->send([new NotificationChannelManagerTestNotifiable], $notification); @@ -531,9 +534,9 @@ public function testAfterSendingMethodAfterSendingNotification(): void $events = new EventFake(new EventsDispatcher); $container->instance(Dispatcher::class, $events); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); + $manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container)); $driver = new ChannelSpy; - $manager->expects('driver')->andReturn($driver); + $manager->expects('driver')->returns($driver); $driver->response = $response = new stdClass; $manager->send($notifiable = new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerWithAfterSendingMethodNotification); @@ -555,7 +558,7 @@ protected function getContainer(): Container $container = new Container; $container->instance(ContainerContract::class, $container); $container->instance('config', new ConfigRepository([])); - $container->instance(BusDispatcherContract::class, m::mock(BusDispatcherContract::class)); + $container->instance(BusDispatcherContract::class, Double::for(BusDispatcherContract::class)); $container->instance(Dispatcher::class, $this->mockEventDispatcher()); Container::setInstance($container); @@ -568,8 +571,8 @@ protected function getContainer(): Container */ protected function mockEventDispatcher(): Dispatcher { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->byDefault()->andReturn(true); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->returns(true); return $dispatcher; } diff --git a/tests/Notifications/NotificationDatabaseChannelTest.php b/tests/Notifications/NotificationDatabaseChannelTest.php index f1143c3bd..bc6a93bef 100644 --- a/tests/Notifications/NotificationDatabaseChannelTest.php +++ b/tests/Notifications/NotificationDatabaseChannelTest.php @@ -5,28 +5,33 @@ namespace Hypervel\Tests\Notifications; use Hypervel\Database\Eloquent\Model; +use Hypervel\Database\Eloquent\Relations\HasMany; use Hypervel\Notifications\AnonymousNotifiable; use Hypervel\Notifications\Channels\DatabaseChannel; use Hypervel\Notifications\Messages\DatabaseMessage; use Hypervel\Notifications\Notification; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class NotificationDatabaseChannelTest extends TestCase { + use VerifiesDoubles; + public function testDatabaseChannelCreatesDatabaseRecordWithProperData(): void { $notification = new NotificationDatabaseChannelTestNotification; $notification->id = '1'; - $notifiable = m::mock(AnonymousNotifiable::class); + $notifiable = Double::for(AnonymousNotifiable::class); - $notifiable->expects('routeNotificationFor->create')->with([ + $notifiable->expects('routeNotificationFor')->returns($relation = Double::for(HasMany::class)); + $relation->expects('create')->with([ 'id' => '1', 'type' => get_class($notification), 'data' => ['invoice_id' => '1'], 'read_at' => null, - ])->andReturn(m::mock(Model::class)); + ])->returns(Double::for(Model::class)); $channel = new DatabaseChannel; $channel->send($notifiable, $notification); @@ -36,15 +41,16 @@ public function testCorrectPayloadIsSentToDatabase(): void { $notification = new NotificationDatabaseChannelTestNotification; $notification->id = '1'; - $notifiable = m::mock(AnonymousNotifiable::class); + $notifiable = Double::for(AnonymousNotifiable::class); - $notifiable->expects('routeNotificationFor->create')->with([ + $notifiable->expects('routeNotificationFor')->returns($relation = Double::for(HasMany::class)); + $relation->expects('create')->with([ 'id' => '1', 'type' => get_class($notification), 'data' => ['invoice_id' => '1'], 'read_at' => null, 'something' => 'else', - ])->andReturn(m::mock(Model::class)); + ])->returns(Double::for(Model::class)); $channel = new ExtendedDatabaseChannel; $channel->send($notifiable, $notification); @@ -56,15 +62,16 @@ public function testCustomizeTypeIsSentToDatabase(): void $notification = new NotificationDatabaseChannelCustomizeTypeTestNotification; $notification->id = '1'; - $notifiable = m::mock(AnonymousNotifiable::class); + $notifiable = Double::for(AnonymousNotifiable::class); - $notifiable->expects('routeNotificationFor->create')->with([ + $notifiable->expects('routeNotificationFor')->returns($relation = Double::for(HasMany::class)); + $relation->expects('create')->with([ 'id' => '1', 'type' => 'MONTHLY', 'data' => ['invoice_id' => '1'], - 'read_at' => CarbonImmutable::now()->toDateTimeString(), + 'read_at' => CarbonImmutable::now(), 'something' => 'else', - ])->andReturn(m::mock(Model::class)); + ])->returns(Double::for(Model::class)); $channel = new ExtendedDatabaseChannel; $channel->send($notifiable, $notification); diff --git a/tests/Notifications/NotificationRoutesNotificationsTest.php b/tests/Notifications/NotificationRoutesNotificationsTest.php index 294dfc2f1..74a18b834 100644 --- a/tests/Notifications/NotificationRoutesNotificationsTest.php +++ b/tests/Notifications/NotificationRoutesNotificationsTest.php @@ -10,15 +10,18 @@ use Hypervel\Notifications\RoutesNotifications; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use stdClass; class NotificationRoutesNotificationsTest extends TestCase { + use VerifiesDoubles; + public function testNotificationCanBeDispatched(): void { $container = $this->getContainer(); - $factory = m::mock(Dispatcher::class); + $factory = Double::for(Dispatcher::class); $container->instance(Dispatcher::class, $factory); $notifiable = new RoutesNotificationsTestInstance; $instance = new stdClass; @@ -30,7 +33,7 @@ public function testNotificationCanBeDispatched(): void public function testNotificationCanBeSentNow(): void { $container = $this->getContainer(); - $factory = m::mock(Dispatcher::class); + $factory = Double::for(Dispatcher::class); $container->instance(Dispatcher::class, $factory); $notifiable = new RoutesNotificationsTestInstance; $instance = new stdClass; diff --git a/tests/Notifications/NotificationSendQueuedNotificationTest.php b/tests/Notifications/NotificationSendQueuedNotificationTest.php index b58669f8e..fe2fb6688 100644 --- a/tests/Notifications/NotificationSendQueuedNotificationTest.php +++ b/tests/Notifications/NotificationSendQueuedNotificationTest.php @@ -15,11 +15,15 @@ use Hypervel\Support\Collection; use Hypervel\Tests\Notifications\Fixtures\Models\NotifiableUser; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Throwable; class NotificationSendQueuedNotificationTest extends TestCase { + use VerifiesDoubles; + public function testManualFailureWithoutAnExceptionReachesTheNotification(): void { $notification = new class extends Notification { @@ -43,12 +47,12 @@ public function testNotificationsCanBeSent(): void { $notification = new TestNotification; $job = new SendQueuedNotifications('notifiables', $notification); - $manager = m::mock(ChannelManager::class); - $manager->expects('sendNow')->withArgs(function (mixed $notifiables, mixed $notification, ?array $channels): bool { + $manager = Double::for(ChannelManager::class); + $manager->expects('sendNow')->with(Argument::all(function (mixed $notifiables, mixed $notification, ?array $channels): bool { return $notifiables instanceof Collection && $notifiables->toArray() === ['notifiables'] && $notification instanceof TestNotification && $channels === null; - }); + })); $job->handle($manager); } diff --git a/tests/Notifications/NotificationSenderTest.php b/tests/Notifications/NotificationSenderTest.php index fcc86d459..991abd80e 100644 --- a/tests/Notifications/NotificationSenderTest.php +++ b/tests/Notifications/NotificationSenderTest.php @@ -34,7 +34,9 @@ use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Tests\Notifications\Fixtures\ChannelSpy; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use stdClass; @@ -46,19 +48,21 @@ class NotificationSenderTest extends TestCase { + use VerifiesDoubles; + public function testItCanSendNotificationsWithAStringVia(): void { - $notifiable = m::mock(Notifiable::class); - $manager = m::mock(ChannelManager::class); + $notifiable = new DummyNotifiable; + $manager = Double::for(ChannelManager::class); $manager->expects('driver') - ->andReturnSelf(); - $manager->expects('send'); - $bus = m::mock(BusDispatcherContract::class); - $bus->shouldNotReceive('dispatch'); + ->returns($driver = Double::for(ChannelSpy::class)); + $driver->expects('send'); + $bus = Double::for(BusDispatcherContract::class); + $bus->expects('dispatch')->never(); $events = $this->mockEventDispatcher(); - $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); - $events->expects('dispatch')->with(m::type(NotificationDelivered::class)); - $events->expects('dispatch')->with(m::type(NotificationSent::class)); + $events->allows('until')->with(Argument::type(NotificationSending::class))->returns(true); + $events->expects('dispatch')->with(Argument::type(NotificationDelivered::class)); + $events->expects('dispatch')->with(Argument::type(NotificationSent::class)); $sender = new NotificationSender($manager, $bus, $events); @@ -75,22 +79,22 @@ static function () use (&$order): void { $order[] = 'after-sending'; } ); - $manager = m::mock(ChannelManager::class); - $manager->expects('driver')->with('mail')->andReturn($driver = m::mock()); - $driver->expects('send')->andReturnUsing(function () use (&$order, $response): object { + $manager = Double::for(ChannelManager::class); + $manager->expects('driver')->with('mail')->returns($driver = Double::for(ChannelSpy::class)); + $driver->expects('send')->resolves(function () use (&$order, $response): object { $order[] = 'channel'; return $response; }); $events = $this->mockEventDispatcher(); - $events->expects('until')->with(m::type(NotificationSending::class))->andReturnUsing( + $events->expects('until')->with(Argument::type(NotificationSending::class))->resolves( function () use (&$order): bool { $order[] = 'sending'; return true; } ); - $events->expects('dispatch')->twice()->andReturnUsing( + $events->expects('dispatch')->times(2)->resolves( function (object $event) use (&$order, $notifiable, $response): void { $this->assertSame($notifiable, $event->notifiable); $this->assertSame('mail', $event->channel); @@ -109,7 +113,7 @@ function (object $event) use (&$order, $notifiable, $response): void { (new NotificationSender( $manager, - m::mock(BusDispatcherContract::class), + Double::for(BusDispatcherContract::class), $events, ))->sendNow($notifiable, $notification, ['mail']); @@ -128,11 +132,11 @@ public function shouldSend(mixed $notifiable, string $channel): bool return false; } }; - $manager = m::mock(ChannelManager::class); - $manager->shouldNotReceive('driver'); + $manager = Double::for(ChannelManager::class); + $manager->expects('driver')->never(); $events = $this->mockEventDispatcher(); - $events->shouldNotReceive('until'); - $events->expects('dispatch')->with(m::on( + $events->expects('until')->never(); + $events->expects('dispatch')->with(Argument::satisfies( fn (object $event): bool => $event instanceof NotificationSkipped && $event->notifiable === $notifiable && $event->channel === 'mail' @@ -140,22 +144,22 @@ public function shouldSend(mixed $notifiable, string $channel): bool (new NotificationSender( $manager, - m::mock(BusDispatcherContract::class), + Double::for(BusDispatcherContract::class), $events, ))->sendNow($notifiable, $notification, ['mail']); } public function testSendingVetoDispatchesSkippedWithoutResolvingTheChannel(): void { - $manager = m::mock(ChannelManager::class); - $manager->shouldNotReceive('driver'); + $manager = Double::for(ChannelManager::class); + $manager->expects('driver')->never(); $events = $this->mockEventDispatcher(); - $events->expects('until')->with(m::type(NotificationSending::class))->andReturnFalse(); - $events->expects('dispatch')->with(m::type(NotificationSkipped::class)); + $events->expects('until')->with(Argument::type(NotificationSending::class))->returns(false); + $events->expects('dispatch')->with(Argument::type(NotificationSkipped::class)); (new NotificationSender( $manager, - m::mock(BusDispatcherContract::class), + Double::for(BusDispatcherContract::class), $events, ))->sendNow(new AnonymousNotifiable, new Notification, ['mail']); } @@ -163,15 +167,15 @@ public function testSendingVetoDispatchesSkippedWithoutResolvingTheChannel(): vo public function testThrowingSendingListenerDispatchesFailedAndRethrows(): void { $exception = new RuntimeException('sending listener failed'); - $manager = m::mock(ChannelManager::class); - $manager->shouldNotReceive('driver'); + $manager = Double::for(ChannelManager::class); + $manager->expects('driver')->never(); $events = $this->mockEventDispatcher(); - $events->expects('until')->with(m::type(NotificationSending::class))->andThrow($exception); - $events->expects('dispatch')->with(m::on( + $events->expects('until')->with(Argument::type(NotificationSending::class))->throws($exception); + $events->expects('dispatch')->with(Argument::satisfies( fn (object $event): bool => $event instanceof NotificationFailed && $event->data['exception'] === $exception )); - $sender = new NotificationSender($manager, m::mock(BusDispatcherContract::class), $events); + $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class), $events); try { $sender->sendNow(new AnonymousNotifiable, new Notification, ['mail']); @@ -187,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 = m::mock(ChannelManager::class); - $driver = m::mock(); - $manager->shouldReceive('driver')->andReturn($driver); + $manager = Double::for(ChannelManager::class); + $driver = Double::for(ChannelSpy::class); + $manager->allows('driver')->returns($driver); $attempts = 0; - $driver->shouldReceive('send')->andReturnUsing(static function () use ($cancellation, &$attempts): never { + $driver->allows('send')->resolves(static function () use ($cancellation, &$attempts): never { ++$attempts; throw $cancellation; }); - $sender = new NotificationSender($manager, m::mock(BusDispatcherContract::class), $events); + $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class), $events); $caught = null; try { @@ -212,15 +216,15 @@ public function testThrowingFailureObserverDoesNotAllowRetryAfterCancellation(): public function testThrowingDeliveredListenerIsNotRelabeledAsDeliveryFailure(): void { $exception = new RuntimeException('delivered listener failed'); - $manager = m::mock(ChannelManager::class); - $manager->expects('driver')->andReturn($driver = m::mock()); - $driver->expects('send')->andReturn('response'); + $manager = Double::for(ChannelManager::class); + $manager->expects('driver')->returns($driver = Double::for(ChannelSpy::class)); + $driver->expects('send')->returns('response'); $events = $this->mockEventDispatcher(); - $events->expects('until')->with(m::type(NotificationSending::class))->andReturnTrue(); - $events->expects('dispatch')->with(m::type(NotificationDelivered::class))->andThrow($exception); - $events->shouldReceive('dispatch')->never()->with(m::type(NotificationFailed::class)); - $events->shouldReceive('dispatch')->never()->with(m::type(NotificationSent::class)); - $sender = new NotificationSender($manager, m::mock(BusDispatcherContract::class), $events); + $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); try { $sender->sendNow(new AnonymousNotifiable, new Notification, ['mail']); @@ -236,15 +240,15 @@ public function testThrowingAfterSendingCallbackIsNotRelabeledAsDeliveryFailure( $notification = new DummyNotificationWithAfterSendingCallback(static function () use ($exception): never { throw $exception; }); - $manager = m::mock(ChannelManager::class); - $manager->expects('driver')->andReturn($driver = m::mock()); - $driver->expects('send')->andReturn('response'); + $manager = Double::for(ChannelManager::class); + $manager->expects('driver')->returns($driver = Double::for(ChannelSpy::class)); + $driver->expects('send')->returns('response'); $events = $this->mockEventDispatcher(); - $events->expects('until')->with(m::type(NotificationSending::class))->andReturnTrue(); - $events->expects('dispatch')->with(m::type(NotificationDelivered::class)); - $events->shouldReceive('dispatch')->never()->with(m::type(NotificationFailed::class)); - $events->shouldReceive('dispatch')->never()->with(m::type(NotificationSent::class)); - $sender = new NotificationSender($manager, m::mock(BusDispatcherContract::class), $events); + $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); try { $sender->sendNow(new AnonymousNotifiable, $notification, ['mail']); @@ -259,7 +263,7 @@ public function testItCanSendQueuedNotificationsWithAStringVia(): void $notifiable = new DummyNotifiable; $manager = $this->getManager(); $bus = new BusFake(new BusDispatcher(new Container)); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -274,7 +278,7 @@ public function testItCanSendQueuedNotificationsWithAnArrayVia(): void $manager = $this->getManager(); $bus = new BusFake(new BusDispatcher(new Container)); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -292,10 +296,10 @@ public function testItCanSendQueuedNotificationsWithAnArrayVia(): void public function testItCanSendNotificationsWithAnEmptyStringVia(): void { $notifiable = new AnonymousNotifiable; - $manager = m::mock(ChannelManager::class); + $manager = Double::for(ChannelManager::class); $bus = new BusFake(new BusDispatcher(new Container)); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('dispatch')->never(); $sender = new NotificationSender($manager, $bus, $events); @@ -307,10 +311,10 @@ public function testItCanSendNotificationsWithAnEmptyStringVia(): void public function testItCannotSendNotificationsViaDatabaseForAnonymousNotifiables(): void { $notifiable = new AnonymousNotifiable; - $manager = m::mock(ChannelManager::class); + $manager = Double::for(ChannelManager::class); $bus = new BusFake(new BusDispatcher(new Container)); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('dispatch')->never(); $sender = new NotificationSender($manager, $bus, $events); @@ -324,7 +328,7 @@ public function testItCanSendQueuedNotificationsThroughMiddleware(): void $notifiable = new DummyNotifiable; $manager = $this->getManager(); $bus = new BusFake(new BusDispatcher(new Container)); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -341,7 +345,7 @@ public function testItCanSendQueuedMultiChannelNotificationsThroughDifferentMidd $notifiable = new DummyNotifiable; $manager = $this->getManager(); $bus = new BusFake(new BusDispatcher(new Container)); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -365,7 +369,7 @@ public function testItCanSendQueuedWithViaConnectionsNotifications(): void $manager = $this->getManager(); $bus = new BusFake(new BusDispatcher(new Container)); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -386,7 +390,7 @@ public function testItCanSendQueuedWithViaQueuesNotifications(): void $manager = $this->getManager(); $bus = new BusFake(new BusDispatcher(new Container)); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -410,7 +414,7 @@ public function testItCanSendQueuedNotificationsWithQueueRoute(): void $bus = new BusFake(new BusDispatcher(new Container)); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -442,19 +446,19 @@ public function viaConnections(): array } }; $notification->onConnection($connection); - $bus = m::mock(BusDispatcherContract::class); - $bus->expects('dispatch')->with(m::on( + $bus = Double::for(BusDispatcherContract::class); + $bus->expects('dispatch')->with(Argument::satisfies( fn (SendQueuedNotifications $job): bool => $job->channels === ['mail'] && $job->queue === 'admin_notifications' && $job->connection === $expectedConnection )); - $bus->expects('dispatch')->with(m::on( + $bus->expects('dispatch')->with(Argument::satisfies( fn (SendQueuedNotifications $job): bool => $job->channels === ['database'] && $job->queue === 'dummy' && $job->connection === 'database-connection' )); - (new NotificationSender(new ChannelManager($container), $bus, m::mock(Dispatcher::class))) + (new NotificationSender(new ChannelManager($container), $bus, Double::for(Dispatcher::class))) ->send(new AnonymousNotifiable, $notification); } @@ -472,19 +476,19 @@ public function via(mixed $notifiable): string } }; - $notifiable = m::mock(Notifiable::class); - $manager = m::mock(ChannelManager::class); - $manager->shouldReceive('getContainer')->andReturn(app()); - $manager->shouldReceive('resolveQueueFromQueueRoute')->andReturn(null); - $manager->shouldReceive('resolveConnectionFromQueueRoute')->andReturn(null); + $notifiable = new DummyNotifiable; + $manager = Double::for(ChannelManager::class); + $manager->allows('getContainer')->returns(app()); + $manager->allows('resolveQueueFromQueueRoute')->returns(null); + $manager->allows('resolveConnectionFromQueueRoute')->returns(null); - $bus = m::mock(BusDispatcherContract::class); + $bus = Double::for(BusDispatcherContract::class); $bus->expects('dispatch') - ->withArgs(function (SendQueuedNotifications $job): bool { + ->with(Argument::satisfies(function (SendQueuedNotifications $job): bool { return $job->delay === 30; - }); + })); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -513,19 +517,19 @@ public function withDelay(mixed $notifiable, string $channel): int } }; - $notifiable = m::mock(Notifiable::class); - $manager = m::mock(ChannelManager::class); - $manager->shouldReceive('getContainer')->andReturn(app()); - $manager->shouldReceive('resolveQueueFromQueueRoute')->andReturn(null); - $manager->shouldReceive('resolveConnectionFromQueueRoute')->andReturn(null); + $notifiable = new DummyNotifiable; + $manager = Double::for(ChannelManager::class); + $manager->allows('getContainer')->returns(app()); + $manager->allows('resolveQueueFromQueueRoute')->returns(null); + $manager->allows('resolveConnectionFromQueueRoute')->returns(null); - $bus = m::mock(BusDispatcherContract::class); + $bus = Double::for(BusDispatcherContract::class); $bus->expects('dispatch') - ->withArgs(function (SendQueuedNotifications $job): bool { + ->with(Argument::satisfies(function (SendQueuedNotifications $job): bool { return $job->delay === 60; - }); + })); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -534,19 +538,19 @@ public function withDelay(mixed $notifiable, string $channel): int public function testItCanSendQueuedNotificationsWithDelayProperty(): void { - $notifiable = m::mock(Notifiable::class); - $manager = m::mock(ChannelManager::class); - $manager->shouldReceive('getContainer')->andReturn(app()); - $manager->shouldReceive('resolveQueueFromQueueRoute')->andReturn(null); - $manager->shouldReceive('resolveConnectionFromQueueRoute')->andReturn(null); + $notifiable = new DummyNotifiable; + $manager = Double::for(ChannelManager::class); + $manager->allows('getContainer')->returns(app()); + $manager->allows('resolveQueueFromQueueRoute')->returns(null); + $manager->allows('resolveConnectionFromQueueRoute')->returns(null); - $bus = m::mock(BusDispatcherContract::class); + $bus = Double::for(BusDispatcherContract::class); $bus->expects('dispatch') - ->withArgs(function (SendQueuedNotifications $job): bool { + ->with(Argument::satisfies(function (SendQueuedNotifications $job): bool { return $job->delay === 45; - }); + })); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $sender = new NotificationSender($manager, $bus, $events); @@ -558,12 +562,12 @@ public function testNotificationFailedSentWithoutHttpTransportException(): void $notifiable = new AnonymousNotifiable; $container = new Container; $container->instance('config', new Config(['app' => ['name' => 'Name', 'logo' => 'Logo']])); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); + $manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container)); $driver = new ChannelSpy; - $response = m::mock(ResponseInterface::class); + $response = Double::for(ResponseInterface::class); $driver->exception = $exception = new HttpTransportException('Transport error', $response); - $manager->expects('driver')->andReturn($driver); - $bus = m::mock(BusDispatcherContract::class); + $manager->expects('driver')->returns($driver); + $bus = Double::for(BusDispatcherContract::class); $events = new EventDispatcher; $failed = null; @@ -589,7 +593,7 @@ public function testNotificationFailedIsDispatchedAfterAChannelDispatchedItWitho $notifiable = new AnonymousNotifiable; $container = new Application; $container->instance('config', new Config(['app' => ['name' => 'Name', 'logo' => 'Logo']])); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); + $manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container)); $bus = new BusFake(new BusDispatcher(new Container)); $events = new EventDispatcher; $container->instance('events', $events); @@ -620,8 +624,8 @@ public function send(mixed $notifiable, Notification $notification): void $smsChannel = new ChannelSpy; $smsChannel->exception = new RuntimeException('SMS gateway down'); - $manager->expects('driver')->with('push')->andReturn($pushChannel); - $manager->expects('driver')->with('sms')->andReturn($smsChannel); + $manager->expects('driver')->with('push')->returns($pushChannel); + $manager->expects('driver')->with('sms')->returns($smsChannel); $sender = new NotificationSender($manager, $bus, $events); $sender->sendNow($notifiable, new DummyNotificationWithViaConnections, ['push']); @@ -645,10 +649,10 @@ public function testItPreservesNotificationStateMutatedInViaMethod(): void $notifiable = new AnonymousNotifiable; $container = new Container; $container->instance('config', new Config(['app' => ['name' => 'Name', 'logo' => 'Logo']])); - $manager = m::mock(ChannelManager::class . '[driver]', [$container]); + $manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container)); $driver = new ChannelSpy; - $manager->expects('driver')->andReturn($driver); - $bus = m::mock(BusDispatcherContract::class); + $manager->expects('driver')->returns($driver); + $bus = Double::for(BusDispatcherContract::class); $events = new EventFake(new EventDispatcher); @@ -681,7 +685,7 @@ public function via(mixed $notifiable): string $notifiable = new DummyNotifiable; $manager = $this->getManager(); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $bus = new BusFake(new BusDispatcher(new Container)); @@ -710,7 +714,7 @@ public function via(mixed $notifiable): string $notifiable = new DummyNotifiable; $manager = $this->getManager(); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $bus = new BusFake(new BusDispatcher(new Container)); @@ -747,7 +751,7 @@ public function via(mixed $notifiable): string $notifiable = new DummyNotifiable; $manager = $this->getManager(); - $events = m::mock(Dispatcher::class); + $events = new EventDispatcher; $bus = new BusFake(new BusDispatcher(new Container)); @@ -761,19 +765,19 @@ public function via(mixed $notifiable): string public function testNotificationEventsAreSkippedWhenNoListenersAreRegistered(): void { - $notifiable = m::mock(Notifiable::class); - $manager = m::mock(ChannelManager::class); + $notifiable = new DummyNotifiable; + $manager = Double::for(ChannelManager::class); $manager->expects('driver') - ->andReturnSelf(); - $manager->expects('send'); - $bus = m::mock(BusDispatcherContract::class); - $bus->shouldNotReceive('dispatch'); - $events = $this->mockEventDispatcher(); - $events->shouldReceive('hasListeners')->with(NotificationSending::class)->andReturn(false); - $events->shouldReceive('hasListeners')->with(NotificationDelivered::class)->andReturn(false); - $events->shouldReceive('hasListeners')->with(NotificationSent::class)->andReturn(false); - $events->shouldNotReceive('until'); - $events->shouldNotReceive('dispatch'); + ->returns($driver = Double::for(ChannelSpy::class)); + $driver->expects('send'); + $bus = Double::for(BusDispatcherContract::class); + $bus->expects('dispatch')->never(); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(NotificationSending::class)->returns(false); + $events->expects('hasListeners')->with(NotificationDelivered::class)->returns(false); + $events->expects('hasListeners')->with(NotificationSent::class)->returns(false); + $events->expects('until')->never(); + $events->expects('dispatch')->never(); $sender = new NotificationSender($manager, $bus, $events); @@ -783,18 +787,18 @@ public function testNotificationEventsAreSkippedWhenNoListenersAreRegistered(): public function testNotificationFailedIsSkippedWithoutListeners(): void { $notifiable = new AnonymousNotifiable; - $manager = m::mock(ChannelManager::class); - $manager->shouldReceive('driver')->andReturn($driver = m::mock()); - $response = m::mock(ResponseInterface::class); + $manager = Double::for(ChannelManager::class); + $manager->allows('driver')->returns($driver = Double::for(ChannelSpy::class)); + $response = Double::for(ResponseInterface::class); $exception = new HttpTransportException('Transport error', $response); - $driver->expects('send')->andThrow($exception); - $bus = m::mock(BusDispatcherContract::class); + $driver->expects('send')->throws($exception); + $bus = Double::for(BusDispatcherContract::class); - $events = $this->mockEventDispatcher(); - $events->shouldReceive('hasListeners')->with(NotificationSending::class)->andReturn(false); - $events->shouldReceive('hasListeners')->with(NotificationFailed::class)->andReturn(false); - $events->shouldNotReceive('until'); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(NotificationSending::class)->returns(false); + $events->expects('hasListeners')->with(NotificationFailed::class)->returns(false); + $events->expects('until')->never(); + $events->expects('dispatch')->never(); $sender = new NotificationSender($manager, $bus, $events); @@ -837,8 +841,8 @@ protected function getManager(array $queueRoutes = []): ChannelManager */ private function mockEventDispatcher(): Dispatcher { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->byDefault()->andReturn(true); + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); return $events; } diff --git a/tests/Pagination/CursorPaginatorLoadMorphCountTest.php b/tests/Pagination/CursorPaginatorLoadMorphCountTest.php index 368a930fc..8f9cf0c32 100644 --- a/tests/Pagination/CursorPaginatorLoadMorphCountTest.php +++ b/tests/Pagination/CursorPaginatorLoadMorphCountTest.php @@ -9,10 +9,13 @@ use Hypervel\Pagination\AbstractCursorPaginator; use Hypervel\Support\HtmlString; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CursorPaginatorLoadMorphCountTest extends TestCase { + use VerifiesDoubles; + public function testCollectionLoadMorphCountCanChainOnThePaginator(): void { $relations = [ @@ -20,7 +23,7 @@ public function testCollectionLoadMorphCountCanChainOnThePaginator(): void 'App\Company' => ['employees', 'calendars'], ]; - $items = m::mock(Collection::class); + $items = Double::for(Collection::class); $items->expects('loadMorphCount')->with('parentable', $relations); $p = (new class extends AbstractCursorPaginator { diff --git a/tests/Pagination/CursorPaginatorLoadMorphTest.php b/tests/Pagination/CursorPaginatorLoadMorphTest.php index f99e12cab..3954c4514 100644 --- a/tests/Pagination/CursorPaginatorLoadMorphTest.php +++ b/tests/Pagination/CursorPaginatorLoadMorphTest.php @@ -9,10 +9,13 @@ use Hypervel\Pagination\AbstractCursorPaginator; use Hypervel\Support\HtmlString; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CursorPaginatorLoadMorphTest extends TestCase { + use VerifiesDoubles; + public function testCollectionLoadMorphCanChainOnThePaginator(): void { $relations = [ @@ -20,7 +23,7 @@ public function testCollectionLoadMorphCanChainOnThePaginator(): void 'App\Company' => ['employees', 'calendars'], ]; - $items = m::mock(Collection::class); + $items = Double::for(Collection::class); $items->expects('loadMorph')->with('parentable', $relations); $p = (new class extends AbstractCursorPaginator { diff --git a/tests/Pagination/PaginatorLoadMorphCountTest.php b/tests/Pagination/PaginatorLoadMorphCountTest.php index aae72f5a0..0213813f3 100644 --- a/tests/Pagination/PaginatorLoadMorphCountTest.php +++ b/tests/Pagination/PaginatorLoadMorphCountTest.php @@ -9,10 +9,13 @@ use Hypervel\Pagination\AbstractPaginator; use Hypervel\Support\HtmlString; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class PaginatorLoadMorphCountTest extends TestCase { + use VerifiesDoubles; + public function testCollectionLoadMorphCountCanChainOnThePaginator(): void { $relations = [ @@ -20,7 +23,7 @@ public function testCollectionLoadMorphCountCanChainOnThePaginator(): void 'App\Company' => ['employees', 'calendars'], ]; - $items = m::mock(Collection::class); + $items = Double::for(Collection::class); $items->expects('loadMorphCount')->with('parentable', $relations); $p = (new class extends AbstractPaginator { diff --git a/tests/Pagination/PaginatorLoadMorphTest.php b/tests/Pagination/PaginatorLoadMorphTest.php index 3343bb1af..6421fd652 100644 --- a/tests/Pagination/PaginatorLoadMorphTest.php +++ b/tests/Pagination/PaginatorLoadMorphTest.php @@ -9,10 +9,13 @@ use Hypervel\Pagination\AbstractPaginator; use Hypervel\Support\HtmlString; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class PaginatorLoadMorphTest extends TestCase { + use VerifiesDoubles; + public function testCollectionLoadMorphCanChainOnThePaginator(): void { $relations = [ @@ -20,7 +23,7 @@ public function testCollectionLoadMorphCanChainOnThePaginator(): void 'App\Company' => ['employees', 'calendars'], ]; - $items = m::mock(Collection::class); + $items = Double::for(Collection::class); $items->expects('loadMorph')->with('parentable', $relations); $p = (new class extends AbstractPaginator { diff --git a/tests/Queue/FailoverQueueTest.php b/tests/Queue/FailoverQueueTest.php index 59abc6492..1bedc35ec 100644 --- a/tests/Queue/FailoverQueueTest.php +++ b/tests/Queue/FailoverQueueTest.php @@ -15,6 +15,7 @@ use Hypervel\Cache\Repository as CacheRepository; use Hypervel\Container\Container; use Hypervel\Contracts\Cache\Lock as LockContract; +use Hypervel\Contracts\Cache\LockProvider; use Hypervel\Contracts\Cache\Repository as CacheContract; use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; use Hypervel\Contracts\Queue\Job; @@ -35,7 +36,9 @@ use Hypervel\Support\Collection; use Hypervel\Tests\Queue\Fixtures\IntegerQueueName; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -48,17 +51,19 @@ class FailoverQueueTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('forwardedQueueOperations')] public function testConnectionScopedForwardsApplyBeforeDelegating(string $method, array $arguments, array $expectedArguments, Collection|int|string|null $result): void { $routes = new QueueRoutes; $routes->forward(['default' => 'processing', 'reports' => 'processing', '0' => 'processing', 'processing' => 'archive'], connection: 'failover'); Container::getInstance()->instance('queue.routes', $routes); - $manager = m::mock(QueueManager::class); - $redis = m::mock(RedisQueue::class); - $manager->shouldReceive('connection')->once()->with('redis')->andReturn($redis); - $redis->shouldReceive($method)->once()->with(...$expectedArguments)->andReturn($result); - $queue = new FailoverQueue($manager, m::mock(DispatcherContract::class), ['redis']); + $manager = Double::for(QueueManager::class); + $redis = Double::for(RedisQueue::class); + $manager->expects('connection')->with('redis')->returns($redis); + $redis->expects($method)->with(...$expectedArguments)->returns($result); + $queue = new FailoverQueue($manager, Double::for(DispatcherContract::class), ['redis']); $queue->setConnectionName('failover'); $this->assertSame($result, $queue->{$method}(...$arguments)); @@ -91,7 +96,7 @@ public static function forwardedQueueOperations(): array #[DataProvider('failedConnectionNames')] public function testPushFailsOverOnException(UnitEnum|string|null $connection, ?string $expectedName): void { - $queue = m::mock(QueueManager::class); + $queue = Double::for(QueueManager::class); $events = new EventDispatcher; $failedOver = []; $events->listen(QueueFailedOver::class, function (QueueFailedOver $event) use (&$failedOver): void { @@ -102,13 +107,13 @@ public function testPushFailsOverOnException(UnitEnum|string|null $connection, ? 'sync', ]); - $redis = m::mock(RedisQueue::class); - $queue->expects('connection')->with($connection)->andReturn($redis); + $redis = Double::for(RedisQueue::class); + $queue->expects('connection')->with($connection)->returns($redis); - $sync = m::mock(SyncQueue::class); - $queue->expects('connection')->with('sync')->andReturn($sync); + $sync = Double::for(SyncQueue::class); + $queue->expects('connection')->with('sync')->returns($sync); - $redis->expects('push')->andReturnUsing( + $redis->expects('push')->resolves( fn (): never => throw new Exception('error') ); @@ -136,16 +141,16 @@ public static function failedConnectionNames(): array public function testReplacementQueueReportsItsOwnFirstFailure(): void { - $manager = m::mock(QueueManager::class); - $events = m::mock(DispatcherContract::class); - $primary = m::mock(Queue::class); - $secondary = m::mock(Queue::class); - $primary->allows('push')->andThrow(new RuntimeException('Primary unavailable.')); - $secondary->allows('push')->andReturn('job-id'); - $manager->allows('connection')->with('primary')->andReturn($primary); - $manager->allows('connection')->with('secondary')->andReturn($secondary); - $events->allows('hasListeners')->with(QueueFailedOver::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->twice()->with(m::type(QueueFailedOver::class)); + $manager = Double::for(QueueManager::class); + $events = Double::for(DispatcherContract::class); + $primary = Double::for(Queue::class); + $secondary = Double::for(Queue::class); + $primary->allows('push')->throws(new RuntimeException('Primary unavailable.')); + $secondary->allows('push')->returns('job-id'); + $manager->allows('connection')->with('primary')->returns($primary); + $manager->allows('connection')->with('secondary')->returns($secondary); + $events->allows('hasListeners')->with(QueueFailedOver::class)->returns(true); + $events->expects('dispatch')->times(2)->with(Argument::type(QueueFailedOver::class)); $queue = new FailoverQueue($manager, $events, ['primary', 'secondary']); $this->assertSame('job-id', $queue->push('job')); @@ -159,19 +164,20 @@ public function testReplacementQueueReportsItsOwnFirstFailure(): void #[TestWith([true])] public function testCancellationDoesNotFailOverOrEmitAnEvent(bool $cleanupThrows): void { - $manager = m::mock(QueueManager::class); - $events = m::mock(DispatcherContract::class); - $primary = m::mock(Queue::class); + $manager = Double::for(QueueManager::class); + $events = Double::for(DispatcherContract::class); + $primary = Double::for(Queue::class); $cancellation = new CanceledException; if ($cleanupThrows) { $cancellation = new RuntimeException('Queue cleanup failed.', previous: $cancellation); } $failover = new FailoverQueue($manager, $events, ['primary', 'secondary']); - $manager->shouldReceive('connection')->once()->with('primary')->andReturn($primary); - $manager->shouldNotReceive('connection')->with('secondary'); - $primary->shouldReceive('push')->once()->andThrow($cancellation); - $events->shouldNotReceive('hasListeners', 'dispatch'); + $manager->expects('connection')->with('primary')->returns($primary); + $manager->expects('connection')->never()->with('secondary'); + $primary->expects('push')->throws($cancellation); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); try { $failover->push('job'); @@ -186,9 +192,9 @@ public function testCancellationDoesNotFailOverOrEmitAnEvent(bool $cleanupThrows public function testCancellationAfterAnOrdinaryFailureRetainsFailureSuppressionState(bool $cleanupThrows): void { $events = new FailoverQueueFakeDispatcher; - $manager = m::mock(QueueManager::class); - $primary = m::mock(Queue::class); - $secondary = m::mock(Queue::class); + $manager = Double::for(QueueManager::class); + $primary = Double::for(Queue::class); + $secondary = Double::for(Queue::class); $cancellation = new CanceledException; if ($cleanupThrows) { $cancellation = new RuntimeException('Queue cleanup failed.', previous: $cancellation); @@ -196,11 +202,11 @@ public function testCancellationAfterAnOrdinaryFailureRetainsFailureSuppressionS $secondaryAttempts = 0; $failover = new FailoverQueue($manager, $events, ['primary', 'secondary', 'tertiary']); - $manager->shouldReceive('connection')->twice()->with('primary')->andReturn($primary); - $manager->shouldReceive('connection')->twice()->with('secondary')->andReturn($secondary); - $manager->shouldNotReceive('connection')->with('tertiary'); - $primary->shouldReceive('push')->twice()->andThrow(new RuntimeException('Primary failed.')); - $secondary->shouldReceive('push')->twice()->andReturnUsing( + $manager->expects('connection')->times(2)->with('primary')->returns($primary); + $manager->expects('connection')->times(2)->with('secondary')->returns($secondary); + $manager->expects('connection')->never()->with('tertiary'); + $primary->expects('push')->times(2)->throws(new RuntimeException('Primary failed.')); + $secondary->expects('push')->times(2)->resolves( static function () use (&$secondaryAttempts, $cancellation): string { if ($secondaryAttempts++ === 0) { throw $cancellation; @@ -224,20 +230,19 @@ static function () use (&$secondaryAttempts, $cancellation): string { public function testCancellationFromAFailoverListenerStopsFallback(): void { - $manager = m::mock(QueueManager::class); - $events = m::mock(DispatcherContract::class); - $primary = m::mock(Queue::class); + $manager = Double::for(QueueManager::class); + $events = Double::for(DispatcherContract::class); + $primary = Double::for(Queue::class); $cancellation = new CanceledException; $failover = new FailoverQueue($manager, $events, ['primary', 'secondary']); - $manager->shouldReceive('connection')->once()->with('primary')->andReturn($primary); - $manager->shouldNotReceive('connection')->with('secondary'); - $primary->shouldReceive('push')->once()->andThrow(new RuntimeException('Primary failed.')); - $events->shouldReceive('hasListeners')->once()->with(QueueFailedOver::class)->andReturnTrue(); - $events->shouldReceive('dispatch') - ->once() - ->with(m::type(QueueFailedOver::class)) - ->andThrow($cancellation); + $manager->expects('connection')->with('primary')->returns($primary); + $manager->expects('connection')->never()->with('secondary'); + $primary->expects('push')->throws(new RuntimeException('Primary failed.')); + $events->expects('hasListeners')->with(QueueFailedOver::class)->returns(true); + $events->expects('dispatch') + ->with(Argument::type(QueueFailedOver::class)) + ->throws($cancellation); try { $failover->push('job'); @@ -249,13 +254,13 @@ public function testCancellationFromAFailoverListenerStopsFallback(): void public function testBulkRespectsJobDelays(): void { - $manager = m::mock(QueueManager::class); - $failover = new FailoverQueue($manager, m::mock(DispatcherContract::class), ['sync']); - $sync = m::mock(SyncQueue::class); + $manager = Double::for(QueueManager::class); + $failover = new FailoverQueue($manager, Double::for(DispatcherContract::class), ['sync']); + $sync = Double::for(SyncQueue::class); - $manager->expects('connection')->times(3)->with('sync')->andReturn($sync); - $sync->expects('later')->with(15, m::type(FailoverJobWithDelayAttribute::class), '', null); - $sync->expects('later')->with(30, m::type(FailoverJobWithDelayProperty::class), '', null); + $manager->expects('connection')->times(3)->with('sync')->returns($sync); + $sync->expects('later')->with(15, Argument::type(FailoverJobWithDelayAttribute::class), '', null); + $sync->expects('later')->with(30, Argument::type(FailoverJobWithDelayProperty::class), '', null); $sync->expects('push')->with('regular-job', '', null); $failover->bulk([ @@ -356,11 +361,11 @@ protected function executePayload(string $payload, ?string $queue = null): int } }; $first->setContainer($container)->setConnectionName('first'); - $second = m::mock(Queue::class); + $second = Double::for(Queue::class); $job = new FailoverQueueUniqueDebouncedJob; $lock = new UniqueLock(new CacheRepository(new ArrayStore)); $this->assertTrue($lock->acquireForDispatch($job)); - $second->expects('push')->with($job)->andReturnUsing(function ($job) use ($lock): string { + $second->expects('push')->with($job)->resolves(function ($job) use ($lock): string { $this->assertTrue(DispatchLockContext::has($job)); $this->assertFalse($lock->acquire($job)); DispatchLockContext::accept($job); @@ -514,8 +519,8 @@ public function testRollbackAttemptsEveryJobLockReleaseWhenOneFails(): void true, ); $transactions = new DatabaseTransactionsManager; - $cache = m::mock(CacheContract::class); - $lock = m::mock(LockContract::class); + $cache = Double::for(CacheContract::class, LockProvider::class); + $lock = Double::for(LockContract::class); $container = new Container; $container->instance('db.transactions', $transactions); $container->instance(CacheContract::class, $cache); @@ -530,11 +535,11 @@ public function testRollbackAttemptsEveryJobLockReleaseWhenOneFails(): void DispatchLockContext::registerUnique($job, $cache, null, $uniqueKey, ''); DispatchLockContext::registerDebounce($job, $cache, $debounceKey, $job->debounceOwner); - $cache->shouldReceive('lock')->once()->with($uniqueKey)->andReturn($lock); - $lock->shouldReceive('forceRelease')->once()->andThrow($failure); - $cache->shouldReceive('get')->once()->with($debounceKey)->andReturn($job->debounceOwner); - $cache->shouldReceive('forget')->once()->with($debounceKey)->andReturnTrue(); - $cache->shouldReceive('forget')->once()->with($debounceKey . ':first_dispatched_at')->andReturnTrue(); + $cache->expects('lock')->with($uniqueKey)->returns($lock); + $lock->expects('forceRelease')->throws($failure); + $cache->expects('get')->with($debounceKey)->returns($job->debounceOwner); + $cache->expects('forget')->with($debounceKey)->returns(true); + $cache->expects('forget')->with($debounceKey . ':first_dispatched_at')->returns(true); $transactions->begin('database', 1); $failover->push($job); @@ -678,22 +683,22 @@ public function testFailingQueueStateIsIsolatedBetweenCoroutines(): void public function testInspectionDelegatesToTheFirstConnection(): void { - $manager = m::mock(QueueManager::class); - $events = m::mock(DispatcherContract::class); - $redis = m::mock(RedisQueue::class); + $manager = Double::for(QueueManager::class); + $events = Double::for(DispatcherContract::class); + $redis = Double::for(RedisQueue::class); $queue = new FailoverQueue($manager, $events, ['redis', 'sync']); - $manager->shouldReceive('connection')->times(10)->with('redis')->andReturn($redis); - $redis->shouldReceive('totalSize')->once()->withNoArgs()->andReturn(9); - $redis->shouldReceive('totalPendingSize')->once()->withNoArgs()->andReturn(2); - $redis->shouldReceive('totalDelayedSize')->once()->withNoArgs()->andReturn(3); - $redis->shouldReceive('totalReservedSize')->once()->withNoArgs()->andReturn(4); - $redis->shouldReceive('pendingJobs')->once()->with('emails')->andReturn($pending = new Collection(['pending'])); - $redis->shouldReceive('delayedJobs')->once()->with('emails')->andReturn($delayed = new Collection(['delayed'])); - $redis->shouldReceive('reservedJobs')->once()->with('emails')->andReturn($reserved = new Collection(['reserved'])); - $redis->shouldReceive('allPendingJobs')->once()->andReturn($allPending = new Collection(['all-pending'])); - $redis->shouldReceive('allDelayedJobs')->once()->andReturn($allDelayed = new Collection(['all-delayed'])); - $redis->shouldReceive('allReservedJobs')->once()->andReturn($allReserved = new Collection(['all-reserved'])); + $manager->expects('connection')->times(10)->with('redis')->returns($redis); + $redis->expects('totalSize')->with()->returns(9); + $redis->expects('totalPendingSize')->with()->returns(2); + $redis->expects('totalDelayedSize')->with()->returns(3); + $redis->expects('totalReservedSize')->with()->returns(4); + $redis->expects('pendingJobs')->with('emails')->returns($pending = new Collection(['pending'])); + $redis->expects('delayedJobs')->with('emails')->returns($delayed = new Collection(['delayed'])); + $redis->expects('reservedJobs')->with('emails')->returns($reserved = new Collection(['reserved'])); + $redis->expects('allPendingJobs')->returns($allPending = new Collection(['all-pending'])); + $redis->expects('allDelayedJobs')->returns($allDelayed = new Collection(['all-delayed'])); + $redis->expects('allReservedJobs')->returns($allReserved = new Collection(['all-reserved'])); $this->assertSame(9, $queue->totalSize()); $this->assertSame(2, $queue->totalPendingSize()); @@ -709,26 +714,26 @@ public function testInspectionDelegatesToTheFirstConnection(): void public function testPopForwardsTheQueueIndexToTheFirstConnection(): void { - $manager = m::mock(QueueManager::class); - $events = m::mock(DispatcherContract::class); - $redis = m::mock(RedisQueue::class); + $manager = Double::for(QueueManager::class); + $events = Double::for(DispatcherContract::class); + $redis = Double::for(RedisQueue::class); $queue = new FailoverQueue($manager, $events, ['redis', 'sync']); - $manager->shouldReceive('connection')->once()->with('redis')->andReturn($redis); - $redis->shouldReceive('pop')->once()->with('emails', 2)->andReturnNull(); + $manager->expects('connection')->with('redis')->returns($redis); + $redis->expects('pop')->with('emails', 2)->returns(null); $this->assertNull($queue->pop('emails', 2)); } public function testPopDoesNotForwardTheQueueIndexToAnOrdinaryConnection(): void { - $manager = m::mock(QueueManager::class); - $events = m::mock(DispatcherContract::class); - $sync = m::mock(SyncQueue::class); + $manager = Double::for(QueueManager::class); + $events = Double::for(DispatcherContract::class); + $sync = Double::for(SyncQueue::class); $queue = new FailoverQueue($manager, $events, ['sync']); - $manager->shouldReceive('connection')->once()->with('sync')->andReturn($sync); - $sync->shouldReceive('pop')->once()->with('emails')->andReturnNull(); + $manager->expects('connection')->with('sync')->returns($sync); + $sync->expects('pop')->with('emails')->returns(null); $this->assertNull($queue->pop('emails', 2)); } diff --git a/tests/Queue/Fixtures/FakeSqsJobWithMessageGroup.php b/tests/Queue/Fixtures/FakeSqsJobWithMessageGroup.php index 24a1ff384..380904de4 100644 --- a/tests/Queue/Fixtures/FakeSqsJobWithMessageGroup.php +++ b/tests/Queue/Fixtures/FakeSqsJobWithMessageGroup.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Queue\Fixtures; +use Closure; use Hypervel\Contracts\Queue\ShouldQueue; use Hypervel\Foundation\Queue\Queueable; @@ -11,6 +12,8 @@ class FakeSqsJobWithMessageGroup implements ShouldQueue { use Queueable; + protected static ?Closure $messageGroupFactory = null; + public function handle(): void { } @@ -20,6 +23,24 @@ public function handle(): void */ public function messageGroup(): string { - return 'group-1'; + return static::$messageGroupFactory + ? (string) call_user_func(static::$messageGroupFactory) + : 'group-1'; + } + + /** + * Set the callable that will be used to generate message groups. + */ + public static function createMessageGroupsUsing(?callable $factory = null): void + { + static::$messageGroupFactory = $factory === null ? null : Closure::fromCallable($factory); + } + + /** + * Indicate that message groups should be created normally and not using a custom factory. + */ + public static function createMessageGroupsNormally(): void + { + static::$messageGroupFactory = null; } } diff --git a/tests/Queue/InteractsWithQueueTest.php b/tests/Queue/InteractsWithQueueTest.php index 7c3c1a0f6..7daa9a0e3 100644 --- a/tests/Queue/InteractsWithQueueTest.php +++ b/tests/Queue/InteractsWithQueueTest.php @@ -10,18 +10,22 @@ use Hypervel\Queue\InteractsWithQueue; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class InteractsWithQueueTest extends TestCase { + use VerifiesDoubles; + public function testCreatesAnExceptionFromString(): void { - $queueJob = m::mock(Job::class); - $queueJob->expects('fail')->withArgs(function (Exception $exception): bool { + $queueJob = Double::for(Job::class); + $queueJob->expects('fail')->with(Argument::satisfies(function (Exception $exception): bool { $this->assertSame('Whoops!', $exception->getMessage()); return true; - }); + })); $job = new class { use InteractsWithQueue; @@ -37,7 +41,7 @@ public function testReleasesUsingDateInterval(): void { CarbonImmutable::setTestNow(CarbonImmutable::now()); - $queueJob = m::mock(Job::class); + $queueJob = Double::for(Job::class); $queueJob->expects('release')->with(60); $job = new class { diff --git a/tests/Queue/ListFailedCommandTest.php b/tests/Queue/ListFailedCommandTest.php index c76fa12b5..e6bebf4f6 100644 --- a/tests/Queue/ListFailedCommandTest.php +++ b/tests/Queue/ListFailedCommandTest.php @@ -8,7 +8,8 @@ use Hypervel\Queue\Console\ListFailedCommand; use Hypervel\Queue\Failed\FailedJobProviderInterface; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Symfony\Component\Console\Input\ArrayInput; @@ -17,6 +18,8 @@ class ListFailedCommandTest extends TestCase { + use VerifiesDoubles; + public function testItDisplaysEmptyFailedJobsAsJson(): void { $output = $this->runCommandWithFailedJobs([], ['--json' => true]); @@ -116,10 +119,10 @@ public function testItFiltersFailedJobsByQueue(string $queue): void protected function runCommandWithFailedJobs(array $failedJobs, array $arguments = [], bool $decorated = false): string { $container = new Application; - $failer = m::mock(FailedJobProviderInterface::class); + $failer = Double::for(FailedJobProviderInterface::class); $container->instance(FailedJobProviderInterface::class, $failer); - $failer->expects('all')->andReturn($failedJobs); + $failer->expects('all')->returns($failedJobs); $command = new ListFailedCommand; $command->setHypervel($container); diff --git a/tests/Queue/PruneBatchesCommandTest.php b/tests/Queue/PruneBatchesCommandTest.php index 0311ce3a5..90158b89a 100644 --- a/tests/Queue/PruneBatchesCommandTest.php +++ b/tests/Queue/PruneBatchesCommandTest.php @@ -8,15 +8,18 @@ use Hypervel\Bus\DatabaseBatchRepository; use Hypervel\Queue\Console\PruneBatchesCommand; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; class PruneBatchesCommandTest extends TestCase { + use VerifiesDoubles; + public function testAllowPruningAllUnfinishedBatches(): void { - $repo = m::spy(DatabaseBatchRepository::class); + $repo = Double::for(DatabaseBatchRepository::class); $repo->expects('prune'); $this->app->instance(BatchRepository::class, $repo); @@ -26,12 +29,12 @@ public function testAllowPruningAllUnfinishedBatches(): void $command->run(new ArrayInput(['--unfinished' => 0]), new NullOutput); - $repo->shouldHaveReceived('pruneUnfinished')->once(); + $repo->received('pruneUnfinished')->times(1); } public function testAllowPruningAllCancelledBatches(): void { - $repo = m::spy(DatabaseBatchRepository::class); + $repo = Double::for(DatabaseBatchRepository::class); $repo->expects('prune'); $this->app->instance(BatchRepository::class, $repo); @@ -41,6 +44,6 @@ public function testAllowPruningAllCancelledBatches(): void $command->run(new ArrayInput(['--cancelled' => 0]), new NullOutput); - $repo->shouldHaveReceived('pruneCancelled')->once(); + $repo->received('pruneCancelled')->times(1); } } diff --git a/tests/Queue/QueueBeanstalkdJobTest.php b/tests/Queue/QueueBeanstalkdJobTest.php index aa40ea003..295b24126 100644 --- a/tests/Queue/QueueBeanstalkdJobTest.php +++ b/tests/Queue/QueueBeanstalkdJobTest.php @@ -7,7 +7,8 @@ use Closure; use Exception; use Hypervel\Config\Repository as ConfigRepository; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; +use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Events\Dispatcher as EventsDispatcher; use Hypervel\ObjectPool\CallbackObjectPool; @@ -17,18 +18,23 @@ use Hypervel\Queue\Jobs\BeanstalkdJob; use Hypervel\Queue\TimeoutExceededException; use Hypervel\Tests\TestCase; -use Mockery as m; -use Pheanstalk\Contract\JobIdInterface; +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; use Pheanstalk\Pheanstalk; +use Pheanstalk\Values\Job as PheanstalkJob; +use Pheanstalk\Values\JobId; use Pheanstalk\Values\JobStats; use RuntimeException; use stdClass; class QueueBeanstalkdJobTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $pools = []; @@ -44,33 +50,36 @@ protected function tearDownInCoroutine(): void public function testFireProperlyCallsTheJobHandler(): void { - $job = $this->getJob(); - $job->getPheanstalkJob()->expects('getData')->andReturn(json_encode(['job' => 'foo', 'data' => ['data']])); - $handler = m::mock(stdClass::class); - $job->getContainer()->expects('make')->with('foo')->andReturn($handler); - $handler->expects('fire')->with($job, ['data']); + $job = $this->getJob(json_encode(['job' => 'foo', 'data' => ['data']])); + $handler = new BeanstalkdJobTestHandler; + $job->getContainer()->instance('foo', $handler); $job->fire(); + + $this->assertSame([[$job, ['data']]], $handler->fired); } public function testFailProperlyCallsTheJobHandler(): void { - $job = $this->getJob(); - // Failure handling reuses the decoded payload after its first read. - $job->getPheanstalkJob()->expects('getData')->andReturn(json_encode(['job' => 'foo', 'uuid' => 'test-uuid', 'data' => ['data']])); - $handler = m::mock(BeanstalkdJobTestFailedTest::class); - $job->getContainer()->expects('make')->with('foo')->andReturn($handler); - $job->getPheanstalk()->expects('delete')->with($job->getPheanstalkJob())->andReturnSelf(); - $handler->expects('failed')->with(['data'], m::type(Exception::class), 'test-uuid', m::type(BeanstalkdJob::class)); + $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()); $events = new EventsDispatcher; $failed = []; $events->listen(JobFailed::class, function (JobFailed $event) use (&$failed): void { $failed[] = $event; }); - $job->getContainer()->expects('make')->with(Dispatcher::class)->andReturn($events); + $job->getContainer()->instance(Dispatcher::class, $events); $job->fail($exception = new Exception); + $this->assertCount(1, $handler->failed); + $this->assertSame(['data'], $handler->failed[0][0]); + $this->assertSame($exception, $handler->failed[0][1]); + $this->assertSame('test-uuid', $handler->failed[0][2]); + $this->assertSame($job, $handler->failed[0][3]); + $this->assertCount(1, $failed); $this->assertSame($job, $failed[0]->job); $this->assertSame($exception, $failed[0]->exception); @@ -78,9 +87,12 @@ public function testFailProperlyCallsTheJobHandler(): void public function testFailWithNullFailedDriverDoesNotRollBackDatabaseTransaction(): void { - $job = $this->getJob(); - $job->getPheanstalkJob()->shouldReceive('getData')->andReturn(json_encode(['job' => 'foo', 'uuid' => 'test-uuid', 'data' => ['data']])); - $job->getContainer()->shouldReceive('make')->once()->with('config')->andReturn(new ConfigRepository([ + $container = Double::for(ContainerContract::class, override: true); + $job = $this->getJob( + json_encode(['job' => 'foo', 'uuid' => 'test-uuid', 'data' => ['data']]), + $container->instance(), + ); + $container->expects('make')->with('config')->returns(new ConfigRepository([ 'queue' => [ 'failed' => [ 'driver' => null, @@ -88,14 +100,14 @@ public function testFailWithNullFailedDriverDoesNotRollBackDatabaseTransaction() ], ], ])); - $job->getContainer()->shouldReceive('bound')->never(); - $job->getContainer()->shouldReceive('make')->never()->with('db'); - $job->getContainer()->shouldReceive('make')->once()->with('foo')->andReturn($handler = m::mock(BeanstalkdJobTestFailedTest::class)); - $job->getPheanstalk()->shouldReceive('delete')->once()->with($job->getPheanstalkJob())->andReturnSelf(); - $handler->shouldReceive('failed')->once()->with(['data'], m::type(TimeoutExceededException::class), 'test-uuid', m::type(BeanstalkdJob::class)); - $job->getContainer()->shouldReceive('make')->once()->with(Dispatcher::class)->andReturn($events = m::mock(Dispatcher::class)); - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->once()->with(m::type(JobFailed::class))->andReturnNull(); + $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()); + $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)); + $events->expects('hasListeners')->with(JobFailed::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(JobFailed::class))->returns(null); $job->fail(TimeoutExceededException::forJob($job)); } @@ -128,9 +140,9 @@ public function testDeleteReleasesPoolLeaseAfterBackendCall(): void { [$pool, $lease] = $this->lease(); $job = $this->getJob(); - $job->getPheanstalk()->shouldReceive('statsJob')->once()->andReturn($this->stats(1)); - $job->getPheanstalk()->shouldReceive('delete')->once()->with($job->getPheanstalkJob()) - ->andReturnUsing(function () use ($pool): void { + $job->getPheanstalk()->expects('statsJob')->returns($this->stats(1)); + $job->getPheanstalk()->expects('delete')->with($job->getPheanstalkJob()) + ->resolves(function () use ($pool): void { $this->assertSame(1, $pool->getBorrowedCount()); }); @@ -144,10 +156,10 @@ public function testReleaseReleasesPoolLeaseAfterBackendCall(): void { [$pool, $lease] = $this->lease(); $job = $this->getJob(); - $job->getPheanstalk()->shouldReceive('statsJob')->once()->andReturn($this->stats(1)); - $job->getPheanstalk()->shouldReceive('release')->once() + $job->getPheanstalk()->expects('statsJob')->returns($this->stats(1)); + $job->getPheanstalk()->expects('release') ->with($job->getPheanstalkJob(), Pheanstalk::DEFAULT_PRIORITY, 5) - ->andReturnUsing(function () use ($pool): void { + ->resolves(function () use ($pool): void { $this->assertSame(1, $pool->getBorrowedCount()); }); @@ -161,9 +173,9 @@ public function testBuryReleasesPoolLeaseAfterBackendCall(): void { [$pool, $lease] = $this->lease(); $job = $this->getJob(); - $job->getPheanstalk()->shouldReceive('statsJob')->once()->andReturn($this->stats(1)); - $job->getPheanstalk()->shouldReceive('bury')->once()->with($job->getPheanstalkJob()) - ->andReturnUsing(function () use ($pool): void { + $job->getPheanstalk()->expects('statsJob')->returns($this->stats(1)); + $job->getPheanstalk()->expects('bury')->with($job->getPheanstalkJob()) + ->resolves(function () use ($pool): void { $this->assertSame(1, $pool->getBorrowedCount()); }); @@ -181,8 +193,8 @@ public function testBackendFailureDiscardsPoolLeaseAndPreservesTheException(): v }); $job = $this->getJob(); $expected = new Exception('delete failed'); - $job->getPheanstalk()->shouldReceive('statsJob')->once()->andReturn($this->stats(1)); - $job->getPheanstalk()->shouldReceive('delete')->once()->andThrow($expected); + $job->getPheanstalk()->expects('statsJob')->returns($this->stats(1)); + $job->getPheanstalk()->expects('delete')->throws($expected); try { $job->withPoolLease($lease)->delete(); @@ -200,10 +212,10 @@ public function testAttemptsRemainAvailableButBackendAccessIsRejectedAfterFinali { [$pool, $lease] = $this->lease(); $job = $this->getJob(); - $job->getPheanstalk()->shouldReceive('statsJob') - ->twice() - ->andReturn($this->stats(1), $this->stats(2)); - $job->getPheanstalk()->shouldReceive('delete')->once(); + $job->getPheanstalk()->expects('statsJob') + ->times(2) + ->returns($this->stats(1), $this->stats(2)); + $job->getPheanstalk()->expects('delete'); $job->withPoolLease($lease); $this->assertSame(2, $job->attempts()); @@ -261,24 +273,40 @@ protected function stats(int $reserves): JobStats /** * Create a Beanstalkd job with mocked dependencies. */ - protected function getJob(): BeanstalkdJob + protected function getJob(string $data = '', ?ContainerContract $container = null): BeanstalkdJob { return new BeanstalkdJob( - m::mock(Container::class), - m::mock(implode(',', [PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class])), - m::mock(JobIdInterface::class), + $container ?? new Container, + Double::for(PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class), + new PheanstalkJob(new JobId(1), $data), 'connection-name', 'default' ); } } +class BeanstalkdJobTestHandler +{ + public array $fired = []; + + /** + * Record the invoked job handler. + */ + public function fire(BeanstalkdJob $job, array $data): void + { + $this->fired[] = [$job, $data]; + } +} + class BeanstalkdJobTestFailedTest { + public array $failed = []; + /** - * Handle a failed job. + * Record the failed job. */ - public function failed(array $data, Exception $exception, string $uuid, BeanstalkdJob $job): void + public function failed(array $data, ?Exception $exception = null, ?string $uuid = null, ?BeanstalkdJob $job = null): void { + $this->failed[] = [$data, $exception, $uuid, $job]; } } diff --git a/tests/Queue/QueueBeanstalkdQueueTest.php b/tests/Queue/QueueBeanstalkdQueueTest.php index bbcc36f23..accd2226e 100644 --- a/tests/Queue/QueueBeanstalkdQueueTest.php +++ b/tests/Queue/QueueBeanstalkdQueueTest.php @@ -5,7 +5,6 @@ namespace Hypervel\Tests\Queue; use Hypervel\Container\Container; -use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Events\Dispatcher; use Hypervel\Queue\Attributes\Delay; use Hypervel\Queue\BeanstalkdQueue; @@ -16,7 +15,10 @@ use Hypervel\Tests\Queue\Fixtures\IntegerQueueName; use Hypervel\Tests\Queue\Fixtures\UnitQueueName; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Pheanstalk\Contract\JobIdInterface; use Pheanstalk\Contract\PheanstalkManagerInterface; use Pheanstalk\Contract\PheanstalkPublisherInterface; @@ -34,9 +36,11 @@ class QueueBeanstalkdQueueTest extends TestCase { + use VerifiesDoubles; + private BeanstalkdQueue $queue; - private ContainerContract $container; + private DoubleInterface $container; public function testQueueNamesPreserveZeroAndDefaultEmptyString(): void { @@ -54,10 +58,9 @@ public function testSizeIncludesPendingDelayedAndReservedJobsWithOneStatsRequest $this->setQueue('default', 60); $this->queue->getPheanstalk() - ->shouldReceive('statsTube') - ->once() - ->with(m::on(fn (TubeName $tube): bool => $tube->value === 'stack')) - ->andReturn(new TubeStats( + ->expects('statsTube') + ->with(Argument::satisfies(fn (TubeName $tube): bool => $tube->value === 'stack')) + ->returns(new TubeStats( name: new TubeName('stack'), currentJobsUrgent: 0, currentJobsReady: 3, @@ -81,8 +84,8 @@ public function testSizeIncludesPendingDelayedAndReservedJobsWithOneStatsRequest public function testAnAbsentTubeHasNoJobs(string $method): void { $this->setQueue('default', 60); - $this->queue->getPheanstalk()->shouldReceive('statsTube') - ->once()->andThrow(new TubeNotFoundException(new TubeName('unused'))); + $this->queue->getPheanstalk()->expects('statsTube') + ->throws(new TubeNotFoundException(new TubeName('unused'))); $this->assertSame(0, $this->queue->{$method}('unused')); } @@ -99,7 +102,7 @@ public function testTubeStatisticsDoNotHideConnectionFailures(): void { $this->setQueue('default', 60); $failure = new RuntimeException('Beanstalkd connection failed.'); - $this->queue->getPheanstalk()->shouldReceive('statsTube')->once()->andThrow($failure); + $this->queue->getPheanstalk()->expects('statsTube')->throws($failure); $this->expectExceptionObject($failure); @@ -111,10 +114,10 @@ public function testTotalSizesUseOneServerStatsRequestPerCount(): void $this->setQueue('default', 60); $this->queue->getPheanstalk() - ->shouldReceive('stats') + ->expects('stats') ->times(4) - ->withNoArgs() - ->andReturn(new ServerStats( + ->with() + ->returns(new ServerStats( currentJobsUrgent: 1, currentJobsReady: 3, currentJobsReserved: 5, @@ -197,24 +200,23 @@ public function testPushProperlyPushesJobOntoBeanstalkd(): void $this->setQueue('default', 60); $pheanstalk = $this->queue->getPheanstalk(); - $pheanstalk->expects('useTube')->with(m::type(TubeName::class)); - $pheanstalk->expects('useTube')->with(m::type(TubeName::class)); + $pheanstalk->expects('useTube')->times(2)->with(Argument::type(TubeName::class)); $pheanstalk->expects('put')->times(2)->with(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(), 'delay' => null]), 1024, 0, 60); $this->queue->push('foo', ['data'], 'stack'); $this->queue->push('foo', ['data']); - $this->container->shouldHaveReceived('bound')->with('events')->times(6); + $this->container->received('bound')->with('events')->times(6); } public function testJobQueuedReceivesTheExactBeanstalkdJobIdentifier(): void { $this->setQueue('default', 60); - $jobId = m::mock(JobIdInterface::class); + $jobId = Double::for(JobIdInterface::class); $pheanstalk = $this->queue->getPheanstalk(); - $pheanstalk->shouldReceive('useTube')->once()->with(m::on(fn (TubeName $tube): bool => $tube->value === '0')); - $pheanstalk->shouldReceive('put')->once()->andReturn($jobId); + $pheanstalk->expects('useTube')->with(Argument::satisfies(fn (TubeName $tube): bool => $tube->value === '0')); + $pheanstalk->expects('put')->returns($jobId); $events = new Dispatcher; $queuedEvent = null; @@ -243,22 +245,21 @@ public function testDelayedPushProperlyPushesJobOntoBeanstalkd(): void $this->setQueue('default', 60); $pheanstalk = $this->queue->getPheanstalk(); - $pheanstalk->expects('useTube')->with(m::type(TubeName::class)); - $pheanstalk->expects('useTube')->with(m::type(TubeName::class)); + $pheanstalk->expects('useTube')->times(2)->with(Argument::type(TubeName::class)); $pheanstalk->expects('put')->times(2)->with(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(), 'delay' => 5]), Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR); $this->queue->later(5, 'foo', ['data'], 'stack'); $this->queue->later(5, 'foo', ['data']); - $this->container->shouldHaveReceived('bound')->with('events')->times(6); + $this->container->received('bound')->with('events')->times(6); } public function testBulkRespectsDelayAttributeWhenPushingOntoBeanstalkd(): void { $this->setQueue('default', 60); $pheanstalk = $this->queue->getPheanstalk(); - $pheanstalk->expects('useTube')->with(m::type(TubeName::class)); - $pheanstalk->expects('put')->with(m::type('string'), Pheanstalk::DEFAULT_PRIORITY, 15, Pheanstalk::DEFAULT_TTR); + $pheanstalk->expects('useTube')->with(Argument::type(TubeName::class)); + $pheanstalk->expects('put')->with(Argument::type('string'), Pheanstalk::DEFAULT_PRIORITY, 15, Pheanstalk::DEFAULT_TTR); $this->queue->bulk([new BeanstalkdJobWithDelayAttribute], ['data']); } @@ -269,13 +270,13 @@ public function testPopProperlyPopsJobOffOfBeanstalkd(): void $tube = new TubeName('default'); $pheanstalk = $this->queue->getPheanstalk(); - $pheanstalk->expects('watch')->with(m::type(TubeName::class)); - $pheanstalk->expects('listTubesWatched')->andReturn(new TubeList($tube)); + $pheanstalk->expects('watch')->with(Argument::type(TubeName::class)); + $pheanstalk->expects('listTubesWatched')->returns(new TubeList($tube)); - $jobId = m::mock(JobIdInterface::class); + $jobId = Double::for(JobIdInterface::class); $jobId->expects('getId'); $job = new Job($jobId, ''); - $pheanstalk->expects('reserveWithTimeout')->with(0)->andReturn($job); + $pheanstalk->expects('reserveWithTimeout')->with(0)->returns($job); $result = $this->queue->pop(); @@ -288,13 +289,13 @@ public function testBlockingPopProperlyPopsJobOffOfBeanstalkd(): void $tube = new TubeName('default'); $pheanstalk = $this->queue->getPheanstalk(); - $pheanstalk->expects('watch')->with(m::type(TubeName::class)); - $pheanstalk->expects('listTubesWatched')->andReturn(new TubeList($tube)); + $pheanstalk->expects('watch')->with(Argument::type(TubeName::class)); + $pheanstalk->expects('listTubesWatched')->returns(new TubeList($tube)); - $jobId = m::mock(JobIdInterface::class); + $jobId = Double::for(JobIdInterface::class); $jobId->expects('getId'); $job = new Job($jobId, ''); - $pheanstalk->expects('reserveWithTimeout')->with(60)->andReturn($job); + $pheanstalk->expects('reserveWithTimeout')->with(60)->returns($job); $result = $this->queue->pop(); @@ -306,8 +307,8 @@ public function testDeleteProperlyRemoveJobsOffBeanstalkd(): void $this->setQueue('default', 60); $pheanstalk = $this->queue->getPheanstalk(); - $pheanstalk->expects('useTube')->with(m::type(TubeName::class))->andReturn($pheanstalk); - $pheanstalk->expects('delete')->with(m::type(JobIdInterface::class)); + $pheanstalk->expects('useTube')->with(Argument::type(TubeName::class)); + $pheanstalk->expects('delete')->with(Argument::type(JobIdInterface::class)); $this->queue->deleteMessage('default', 1); } @@ -318,14 +319,14 @@ public function testDeleteProperlyRemoveJobsOffBeanstalkd(): void private function setQueue(string $default, int $timeToRun, int $blockFor = 0): void { $this->queue = new BeanstalkdQueue( - m::mock(implode(',', [PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class])), + Double::for(PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class), $default, $timeToRun, $blockFor ); $this->queue->setConnectionName('beanstalkd'); - $this->container = m::spy(Container::class)->makePartial(); - $this->queue->setContainer($this->container); + $this->container = Double::for(Container::class, override: true)->passthru(new Container); + $this->queue->setContainer($this->container->instance()); } } diff --git a/tests/Queue/QueueClearCommandTest.php b/tests/Queue/QueueClearCommandTest.php index 6c9a391d7..3434557ec 100644 --- a/tests/Queue/QueueClearCommandTest.php +++ b/tests/Queue/QueueClearCommandTest.php @@ -12,13 +12,16 @@ use Hypervel\Queue\NullQueue; use Hypervel\Queue\QueueManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; use UnitEnum; class QueueClearCommandTest extends TestCase { + use VerifiesDoubles; + public function testClearingDefaultQueue(): void { $queue = new FakeClearableQueue(['default' => 2]); @@ -84,8 +87,8 @@ public function testProhibitedCommandCannotBeForced(): void ClearCommand::prohibit(); $container = new Application; - $queueManager = m::mock(QueueManager::class); - $queueManager->shouldNotReceive('connection'); + $queueManager = Double::for(QueueManager::class); + $queueManager->expects('connection')->never(); $container->instance('queue', $queueManager); $command = new ClearCommand; @@ -104,14 +107,14 @@ protected function runClearCommand(Queue&ClearableQueue $queue, array $arguments $container = new Application; $container->instance('env', 'testing'); - $config = m::mock(Repository::class); - $config->expects('string')->with('queue.default')->andReturn('redis'); - $config->shouldReceive('string')->with('queue.connections.redis.queue', 'default')->andReturn('default'); + $config = Double::for(Repository::class); + $config->expects('string')->with('queue.default')->returns('redis'); + $config->allows('string')->with('queue.connections.redis.queue', 'default')->returns('default'); $container->instance('config', $config); - $queueManager = m::mock(QueueManager::class); - $queueManager->expects('connection')->with('redis')->andReturn($queue); + $queueManager = Double::for(QueueManager::class); + $queueManager->expects('connection')->with('redis')->returns($queue); $container->instance('queue', $queueManager); diff --git a/tests/Queue/QueueDatabaseQueueIntegrationTest.php b/tests/Queue/QueueDatabaseQueueIntegrationTest.php index e7d56a9e1..f0e534421 100644 --- a/tests/Queue/QueueDatabaseQueueIntegrationTest.php +++ b/tests/Queue/QueueDatabaseQueueIntegrationTest.php @@ -2,26 +2,40 @@ declare(strict_types=1); -namespace Hypervel\Tests\Queue; +namespace Hypervel\Tests\Queue\QueueDatabaseQueueIntegrationTest; +use Hypervel\Bus\Batchable; use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Contracts\Queue\Factory; use Hypervel\Contracts\Queue\Job; +use Hypervel\Contracts\Queue\ShouldQueue; use Hypervel\Database\ConnectionInterface; +use Hypervel\Database\Events\QueryExecuted; use Hypervel\Foundation\Testing\RefreshDatabase; +use Hypervel\Queue\Attributes\Backoff; +use Hypervel\Queue\Attributes\CountCrashesAsExceptions; +use Hypervel\Queue\Attributes\Delay; +use Hypervel\Queue\Attributes\FailOnTimeout; +use Hypervel\Queue\Attributes\MaxExceptions; +use Hypervel\Queue\Attributes\Timeout; +use Hypervel\Queue\Attributes\Tries; use Hypervel\Queue\DatabaseQueue; use Hypervel\Queue\Events\JobFailed; use Hypervel\Queue\Events\JobQueued; use Hypervel\Queue\Events\JobQueueing; +use Hypervel\Queue\Jobs\InspectedJob; use Hypervel\Queue\MaxAttemptsExceededException; use Hypervel\Queue\Queue; use Hypervel\Queue\Worker; use Hypervel\Queue\WorkerOptions; use Hypervel\Support\CarbonImmutable; +use Hypervel\Support\Collection; use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; +use Symfony\Component\Uid\Uuid; use Throwable; class QueueDatabaseQueueIntegrationTest extends TestCase @@ -336,6 +350,341 @@ public function testJobPayloadIsAvailableOnEvents(): void $this->assertIsArray($jobQueuedEvent->payload()); $this->assertSame((string) $uuid, $jobQueuedEvent->payload()['uuid']); } + + #[DataProvider('pushJobsDataProvider')] + public function testPushProperlyPushesJobOntoDatabase(Uuid $uuid, object|string $job, string $displayNameStartsWith, string $jobStartsWith): void + { + Str::createUuidsUsing(fn () => $uuid); + + $this->queue->push($job, ['data']); + + $row = $this->rows()->sole(); + $payload = json_decode($row->payload, true); + + $this->assertSame((string) $uuid, $payload['uuid']); + $this->assertStringContainsString($displayNameStartsWith, $payload['displayName']); + $this->assertStringContainsString($jobStartsWith, $payload['job']); + + $this->assertSame('default', $row->queue); + $this->assertEquals(0, $row->attempts); + $this->assertNull($row->reserved_at); + $this->assertIsInt($row->available_at); + } + + /** + * Provide object, closure and string jobs. + */ + public static function pushJobsDataProvider(): array + { + $uuid = Str::uuid(); + + return [ + [$uuid, new MyTestJob, 'MyTestJob', 'CallQueuedHandler'], + [$uuid, fn (): int => 0, 'Closure', 'CallQueuedHandler'], + [$uuid, 'foo', 'foo', 'foo'], + ]; + } + + public function testDelayedPushProperlyPushesJobOntoDatabase(): void + { + CarbonImmutable::setTestNow($time = CarbonImmutable::now()->startOfSecond()); + + $this->queue->later(10, 'foo', ['data']); + + $row = $this->rows()->sole(); + $payload = json_decode($row->payload, true); + + $this->assertSame('default', $row->queue); + $this->assertSame('foo', $payload['job']); + $this->assertSame(['data'], $payload['data']); + $this->assertSame(10, $payload['delay']); + $this->assertEquals(0, $row->attempts); + $this->assertNull($row->reserved_at); + $this->assertEquals($time->getTimestamp() + 10, $row->available_at); + } + + public function testPushIncludesBatchIdInPayloadForBatchableJob(): void + { + $this->queue->push((new MyBatchableJob)->withBatchId('test-batch-id'), ['data']); + + $payload = json_decode($this->rows()->sole()->payload, true); + + $this->assertSame('test-batch-id', $payload['data']['batchId']); + } + + public function testPushUsesPropertiesDeclaredOnChildClassOverInheritedAttributes(): void + { + $this->queue->push(new ChildJobWithPropertiesOverridingParentAttributes, ['data']); + + $payload = json_decode($this->rows()->sole()->payload, true); + + $this->assertSame(1700, $payload['timeout']); + $this->assertSame(7, $payload['maxTries']); + $this->assertSame('13', $payload['backoff']); + $this->assertSame(11, $payload['maxExceptions']); + $this->assertFalse($payload['failOnTimeout']); + $this->assertFalse($payload['countCrashesAsExceptions']); + } + + public function testPushStillUsesAttributesDeclaredOnSameClassOverDefaultProperties(): void + { + $this->queue->push(new JobWithAttributesAndDefaultProperties, ['data']); + + $payload = json_decode($this->rows()->sole()->payload, true); + + $this->assertSame(40, $payload['timeout']); + $this->assertSame(2, $payload['maxTries']); + $this->assertSame('9', $payload['backoff']); + $this->assertSame(3, $payload['maxExceptions']); + $this->assertTrue($payload['failOnTimeout']); + $this->assertTrue($payload['countCrashesAsExceptions']); + } + + public function testBulkBatchPushesOntoDatabase(): void + { + $uuids = [Str::uuid(), Str::uuid()]; + Str::createUuidsUsingSequence($uuids); + CarbonImmutable::setTestNow($time = CarbonImmutable::now()->startOfSecond()); + + $inserts = 0; + $this->connection()->listen(function (QueryExecuted $query) use (&$inserts): void { + $inserts += str_starts_with($query->sql, 'insert') ? 1 : 0; + }); + + $this->queue->bulk(['foo', 'bar'], ['data'], 'queue'); + + $rows = $this->rows()->values(); + + $this->assertSame(1, $inserts); + $this->assertCount(2, $rows); + + foreach ([['foo', $uuids[0]], ['bar', $uuids[1]]] as $index => [$name, $uuid]) { + $payload = json_decode($rows[$index]->payload, true); + + $this->assertSame('queue', $rows[$index]->queue); + $this->assertSame([ + 'uuid' => (string) $uuid, + 'displayName' => $name, + 'job' => $name, + 'stringJob' => true, + 'maxTries' => null, + 'maxExceptions' => null, + 'failOnTimeout' => false, + 'backoff' => null, + 'timeout' => null, + 'data' => ['data'], + 'createdAt' => $time->getTimestamp(), + 'delay' => null, + ], $payload); + $this->assertEquals(0, $rows[$index]->attempts); + $this->assertNull($rows[$index]->reserved_at); + $this->assertEquals($time->getTimestamp(), $rows[$index]->available_at); + $this->assertEquals($time->getTimestamp(), $rows[$index]->created_at); + } + } + + public function testDelayAttributeIsRespectedWhenBulkPushing(): void + { + CarbonImmutable::setTestNow($time = CarbonImmutable::now()->startOfSecond()); + + $this->queue->bulk([new JobWithDelayAttribute, new MyTestJob], ['data'], 'queue'); + + $rows = $this->rows()->values(); + + $this->assertEquals($time->getTimestamp() + 15, $rows[0]->available_at); + $this->assertEquals($time->getTimestamp(), $rows[1]->available_at); + } + + public function testBulkDefersAfterCommitJobsUntilTheTransactionCommits(): void + { + // RefreshDatabase already installs the manager that ignores its wrapper transaction. + $insertedDuringTransaction = null; + + $this->connection()->transaction(function () use (&$insertedDuringTransaction): void { + $this->assertNull($this->queue->bulk([new AfterCommitJob])); + + $insertedDuringTransaction = $this->rows()->count(); + }); + + $this->assertSame(0, $insertedDuringTransaction); + $this->assertCount(1, $this->rows()); + } + + public function testPendingJobs(): void + { + $this->seedJobsInEveryState(); + + $this->assertSame(['default-pending'], $this->names($this->queue->pendingJobs())); + $this->assertSame(['emails-pending'], $this->names($this->queue->pendingJobs('emails'))); + + $job = $this->queue->pendingJobs()->sole(); + $this->assertInstanceOf(InspectedJob::class, $job); + $this->assertSame('default-pending-uuid', $job->uuid); + $this->assertSame($this->rows()->get(0)->id, $job->id); + $this->assertInstanceOf(CarbonImmutable::class, $job->createdAt); + $this->assertSame(0, $job->attempts); + $this->assertSame('default', $job->queue); + $this->assertSame(1000000, $job->createdAt->getTimestamp()); + } + + public function testDelayedJobs(): void + { + $this->seedJobsInEveryState(); + + $this->assertSame(['default-delayed'], $this->names($this->queue->delayedJobs())); + $this->assertSame(['emails-delayed'], $this->names($this->queue->delayedJobs('emails'))); + + $job = $this->queue->delayedJobs()->sole(); + $this->assertInstanceOf(InspectedJob::class, $job); + $this->assertSame('default-delayed-uuid', $job->uuid); + $this->assertSame($this->rows()->get(1)->id, $job->id); + $this->assertInstanceOf(CarbonImmutable::class, $job->createdAt); + $this->assertSame(0, $job->attempts); + $this->assertSame('default', $job->queue); + $this->assertSame(1000000, $job->createdAt->getTimestamp()); + } + + public function testReservedJobs(): void + { + $this->seedJobsInEveryState(); + + $this->assertSame(['default-reserved'], $this->names($this->queue->reservedJobs())); + $this->assertSame(['emails-reserved'], $this->names($this->queue->reservedJobs('emails'))); + + $job = $this->queue->reservedJobs()->sole(); + $this->assertInstanceOf(InspectedJob::class, $job); + $this->assertSame('default-reserved-uuid', $job->uuid); + $this->assertSame($this->rows()->get(2)->id, $job->id); + $this->assertInstanceOf(CarbonImmutable::class, $job->createdAt); + $this->assertSame(1, $job->attempts); + $this->assertSame('default', $job->queue); + $this->assertSame(1000000, $job->createdAt->getTimestamp()); + } + + public function testAllPendingJobs(): void + { + $this->seedJobsInEveryState(); + + $jobs = $this->queue->allPendingJobs(); + + $this->assertSame(['default-pending', 'emails-pending'], $this->names($jobs)); + foreach ($jobs as $index => $job) { + $this->assertSame($job->name . '-uuid', $job->uuid); + $this->assertSame($this->rows()->get($index * 3)->id, $job->id); + $this->assertSame($index, $job->attempts); + $this->assertInstanceOf(CarbonImmutable::class, $job->createdAt); + $this->assertSame(1000000, $job->createdAt->getTimestamp()); + } + $this->assertSame(['default', 'emails'], $jobs->map->queue->all()); + } + + public function testAllDelayedJobs(): void + { + $this->seedJobsInEveryState(); + + $jobs = $this->queue->allDelayedJobs(); + + $this->assertSame(['default-delayed', 'emails-delayed'], $this->names($jobs)); + foreach ($jobs as $index => $job) { + $this->assertSame($job->name . '-uuid', $job->uuid); + $this->assertSame($this->rows()->get($index * 3 + 1)->id, $job->id); + $this->assertSame(0, $job->attempts); + $this->assertInstanceOf(CarbonImmutable::class, $job->createdAt); + $this->assertSame(1000000, $job->createdAt->getTimestamp()); + } + $this->assertSame(['default', 'emails'], $jobs->map->queue->all()); + } + + public function testAllReservedJobs(): void + { + $this->seedJobsInEveryState(); + + $jobs = $this->queue->allReservedJobs(); + + $this->assertSame(['default-reserved', 'emails-reserved'], $this->names($jobs)); + foreach ($jobs as $index => $job) { + $this->assertSame($job->name . '-uuid', $job->uuid); + $this->assertSame($this->rows()->get($index * 3 + 2)->id, $job->id); + $this->assertSame($index + 1, $job->attempts); + $this->assertInstanceOf(CarbonImmutable::class, $job->createdAt); + $this->assertSame(1000000, $job->createdAt->getTimestamp()); + } + $this->assertSame(['default', 'emails'], $jobs->map->queue->all()); + $this->assertSame([1, 2], $jobs->map->attempts->all()); + } + + public function testTotalSize(): void + { + $this->seedJobsInEveryState(); + + $this->assertSame(6, $this->queue->totalSize()); + } + + public function testTotalPendingSize(): void + { + $this->seedJobsInEveryState(); + + $this->assertSame(2, $this->queue->totalPendingSize()); + } + + public function testTotalDelayedSize(): void + { + $this->seedJobsInEveryState(); + + $this->assertSame(2, $this->queue->totalDelayedSize()); + } + + public function testTotalReservedSize(): void + { + $this->seedJobsInEveryState(); + + $this->assertSame(2, $this->queue->totalReservedSize()); + } + + /** + * Seed a pending (due right now), delayed (due a second from now) and reserved job on two queues. + */ + protected function seedJobsInEveryState(): void + { + CarbonImmutable::setTestNow($now = CarbonImmutable::now()->startOfSecond()); + + foreach (['default' => 1, 'emails' => 2] as $queue => $attempts) { + $this->seedJob($queue, "{$queue}-pending", availableAt: $now->getTimestamp(), attempts: $attempts - 1); + $this->seedJob($queue, "{$queue}-delayed", availableAt: $now->getTimestamp() + 1); + $this->seedJob($queue, "{$queue}-reserved", availableAt: $now->getTimestamp() - 10, reservedAt: $now->getTimestamp(), attempts: $attempts); + } + } + + /** + * Insert a job in the requested state. + */ + protected function seedJob(string $queue, string $name, int $availableAt, ?int $reservedAt = null, int $attempts = 0): void + { + $this->connection()->table('jobs')->insert([ + 'queue' => $queue, + 'payload' => json_encode(['uuid' => "{$name}-uuid", 'displayName' => $name, 'job' => 'foo', 'data' => [], 'createdAt' => 1000000]), + 'attempts' => $attempts, + 'reserved_at' => $reservedAt, + 'available_at' => $availableAt, + 'created_at' => 1000000, + ]); + } + + /** + * Get queued records in insertion order. + */ + protected function rows(): Collection + { + return $this->connection()->table('jobs')->orderBy('id')->get(); + } + + /** + * Get inspected job names. + */ + protected function names(Collection $jobs): array + { + return $jobs->map->name->all(); + } } class DatabaseQueueReleasedAttemptHandler @@ -371,3 +720,75 @@ public function failed(array $data, Throwable $exception, string $uuid, Job $job $this->failures[] = $exception; } } + +class MyTestJob +{ + /** + * Handle the queued job. + */ + public function handle(): void + { + // ... + } +} + +class MyBatchableJob +{ + use Batchable; +} + +#[Delay(15)] +class JobWithDelayAttribute +{ +} + +class AfterCommitJob implements ShouldQueue +{ + public bool $afterCommit = true; +} + +#[Backoff(9)] +#[CountCrashesAsExceptions] +#[FailOnTimeout] +#[MaxExceptions(3)] +#[Timeout(40)] +#[Tries(2)] +abstract class ParentJobWithAttributes implements ShouldQueue +{ +} + +class ChildJobWithPropertiesOverridingParentAttributes extends ParentJobWithAttributes +{ + public int $backoff = 13; + + public bool $countCrashesAsExceptions = false; + + public bool $failOnTimeout = false; + + public int $maxExceptions = 11; + + public int $timeout = 1700; + + public int $tries = 7; +} + +#[Backoff(9)] +#[CountCrashesAsExceptions] +#[FailOnTimeout] +#[MaxExceptions(3)] +#[Timeout(40)] +#[Tries(2)] +class JobWithAttributesAndDefaultProperties implements ShouldQueue +{ + public int $backoff = 13; + + public bool $countCrashesAsExceptions = false; + + public bool $failOnTimeout = false; + + public int $maxExceptions = 11; + + public int $timeout = 1700; + + public int $tries = 7; +} diff --git a/tests/Queue/QueueDatabaseQueueUnitTest.php b/tests/Queue/QueueDatabaseQueueUnitTest.php index eb78e7291..2242fb3da 100644 --- a/tests/Queue/QueueDatabaseQueueUnitTest.php +++ b/tests/Queue/QueueDatabaseQueueUnitTest.php @@ -7,13 +7,11 @@ use Closure; use DateInterval; use DateTimeInterface; -use Hypervel\Bus\Batchable; use Hypervel\Bus\DispatchLockContext; use Hypervel\Container\Container; use Hypervel\Contracts\Cache\Repository as CacheRepository; use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; -use Hypervel\Contracts\Queue\ShouldQueue; use Hypervel\Contracts\Queue\ShouldQueueAfterCommit; use Hypervel\Database\Connection; use Hypervel\Database\ConnectionResolverInterface; @@ -26,13 +24,7 @@ use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Events\Dispatcher; use Hypervel\Filesystem\Filesystem; -use Hypervel\Queue\Attributes\Backoff; -use Hypervel\Queue\Attributes\CountCrashesAsExceptions; use Hypervel\Queue\Attributes\Delay; -use Hypervel\Queue\Attributes\FailOnTimeout; -use Hypervel\Queue\Attributes\MaxExceptions; -use Hypervel\Queue\Attributes\Timeout; -use Hypervel\Queue\Attributes\Tries; use Hypervel\Queue\DatabaseQueue; use Hypervel\Queue\Events\JobFailed; use Hypervel\Queue\Events\JobPayloadFinalizing; @@ -42,7 +34,6 @@ use Hypervel\Queue\Events\JobQueueingFailed; use Hypervel\Queue\InvalidPayloadException; use Hypervel\Queue\Jobs\DatabaseJobRecord; -use Hypervel\Queue\Jobs\InspectedJob; use Hypervel\Queue\Queue; use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Str; @@ -51,7 +42,9 @@ use Hypervel\Tests\Queue\Fixtures\UnitQueueName; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PDO; use PDOException; use PHPUnit\Framework\Attributes\DataProvider; @@ -66,12 +59,14 @@ class QueueDatabaseQueueUnitTest extends TestCase { + use VerifiesDoubles; + public function testRetryAfterMustBeAnInteger(): void { $this->expectException(TypeError::class); new DatabaseQueue( - resolver: m::mock(ConnectionResolverInterface::class), + resolver: Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', retryAfter: null, @@ -81,7 +76,7 @@ public function testRetryAfterMustBeAnInteger(): void public function testQueueNamesPreserveZeroAndDefaultEmptyString(): void { $queue = new TestDatabaseQueue( - resolver: m::mock(ConnectionResolverInterface::class), + resolver: Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -99,11 +94,11 @@ public function testQueueNamesPreserveZeroAndDefaultEmptyString(): void #[TestWith([false, true])] public function testLockForPoppingUsesTheConnectionCapability(bool $supportsSkipLocked, bool|string $lock): void { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); - $resolver->shouldReceive('connection')->once()->with(null)->andReturn($connection); - $connection->shouldReceive('supportsSkipLocked')->once()->andReturn($supportsSkipLocked); + $resolver->expects('connection')->with(null)->returns($connection); + $connection->expects('supportsSkipLocked')->returns($supportsSkipLocked); $queue = new TestDatabaseQueue( resolver: $resolver, @@ -120,8 +115,8 @@ public function testLockForPoppingUsesTheConnectionCapability(bool $supportsSkip public function testTransientReservationFailuresDoNotFailTheJob(Throwable $failure): void { [$queue, $events] = $this->createFailingReservationQueue($failure); - $queue->shouldReceive('deleteReserved')->never(); - $events->shouldReceive('dispatch')->never(); + $queue->expects('deleteReserved')->never(); + $events->expects('dispatch')->never(); try { $queue->pop(); @@ -148,13 +143,13 @@ public function testReservationRecoveryPreservesFailureOrPropagatesCancellation( { $failure = new QueryException('database', 'update jobs', [], new PDOException('Reservation failed.')); [$queue, $events] = $this->createFailingReservationQueue($failure); - $queue->shouldReceive('causedByReservationQuery')->once()->andReturn(true); - $queue->shouldReceive('deleteReserved')->once()->with('default', '1')->andThrow($cleanupFailure); + $queue->expects('causedByReservationQuery')->returns(true); + $queue->expects('deleteReserved')->with('default', '1')->throws($cleanupFailure); if ($canceled) { - $events->shouldReceive('dispatch')->never(); + $events->expects('dispatch')->never(); } else { - $events->shouldReceive('hasListeners')->once()->with(JobFailed::class)->andReturn(false); + $events->expects('hasListeners')->with(JobFailed::class)->returns(false); } try { @@ -177,58 +172,8 @@ public static function reservationCleanupFailureProvider(): array ]; } - #[DataProvider('pushJobsDataProvider')] - public function testPushProperlyPushesJobOntoDatabase(Uuid $uuid, object|string $job, string $displayNameStartsWith, string $jobStartsWith): void - { - Str::createUuidsUsing(fn (): Uuid => $uuid); - - $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), - connection: null, - table: 'table', - default: 'default', - currentTime: 1732502704, - ); - $queue->setContainer($container = m::spy(Container::class)->makePartial()); - $connection = m::mock(Connection::class); - $resolver->expects('connection')->andReturn($connection); - $query = m::mock(Builder::class); - $connection->expects('table')->with('table')->andReturn($query); - $query->expects('insertGetId')->andReturnUsing(function (array $array) use ($uuid, $displayNameStartsWith, $jobStartsWith): int { - $payload = json_decode($array['payload'], true); - $this->assertSame((string) $uuid, $payload['uuid']); - $this->assertStringContainsString($displayNameStartsWith, $payload['displayName']); - $this->assertStringContainsString($jobStartsWith, $payload['job']); - - $this->assertSame('default', $array['queue']); - $this->assertEquals(0, $array['attempts']); - $this->assertNull($array['reserved_at']); - $this->assertIsInt($array['available_at']); - - return 1; - }); - - $queue->push($job, ['data']); - - $container->shouldHaveReceived('bound')->with('events')->times(3); - } - - /** - * Provide object, closure and string jobs. - */ - public static function pushJobsDataProvider(): array - { - $uuid = Str::uuid(); - - return [ - [$uuid, new MyTestJob, 'MyTestJob', 'CallQueuedHandler'], - [$uuid, fn (): int => 0, 'Closure', 'CallQueuedHandler'], - [$uuid, 'foo', 'foo', 'foo'], - ]; - } - #[DataProvider('delayedJobDeadlineProvider')] - public function testDelayedPushProperlyPushesJobOntoDatabase(DateInterval|DateTimeInterface|int $delay): void + public function testDelayedPushRoundsUpFractionalDeadlines(DateInterval|DateTimeInterface|int $delay): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); $now = CarbonImmutable::now(); @@ -238,19 +183,20 @@ public function testDelayedPushProperlyPushesJobOntoDatabase(DateInterval|DateTi Str::createUuidsUsing(fn (): Uuid => $uuid); $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', currentTime: 1000, ); - $queue->setContainer($container = m::spy(Container::class)->makePartial()); - $connection = m::mock(Connection::class); - $query = m::mock(Builder::class); - $connection->expects('table')->with('table')->andReturn($query); - $resolver->expects('connection')->andReturn($connection); - - $query->expects('insertGetId')->andReturnUsing(function (array $array) use ($uuid, $now): int { + $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->expects('table')->with('table')->returns($query); + $resolver->expects('connection')->returns($connection); + + $query->expects('insertGetId')->resolves(function (array $array) use ($uuid, $now): int { $this->assertSame('default', $array['queue']); $this->assertSame(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(), 'delay' => 1]), $array['payload']); $this->assertEquals(0, $array['attempts']); @@ -262,7 +208,7 @@ public function testDelayedPushProperlyPushesJobOntoDatabase(DateInterval|DateTi $queue->later($delay, 'foo', ['data']); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } /** @@ -277,92 +223,6 @@ public static function delayedJobDeadlineProvider(): array ]; } - public function testPushIncludesBatchIdInPayloadForBatchableJob(): void - { - $uuid = Str::uuid()->toString(); - - Str::createUuidsUsing(fn (): string => $uuid); - - $job = (new MyBatchableJob)->withBatchId('test-batch-id'); - - $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), - connection: null, - table: 'table', - default: 'default', - currentTime: 1732502704, - ); - $queue->setContainer($container = m::spy(Container::class)->makePartial()); - $connection = m::mock(Connection::class); - $resolver->expects('connection')->andReturn($connection); - $query = m::mock(Builder::class); - $connection->expects('table')->with('table')->andReturn($query); - $query->expects('insertGetId')->andReturnUsing(function (array $array): int { - $payload = json_decode($array['payload'], true); - $this->assertSame('test-batch-id', $payload['data']['batchId']); - - return 1; - }); - - $queue->push($job, ['data']); - - $container->shouldHaveReceived('bound')->with('events')->times(3); - } - - public function testPushUsesPropertiesDeclaredOnChildClassOverInheritedAttributes(): void - { - $resolver = m::mock(ConnectionResolverInterface::class); - $database = m::mock(Connection::class); - $resolver->expects('connection')->with(null)->andReturn($database); - $queue = new DatabaseQueue($resolver, null, 'table', 'default'); - $queue->setContainer($container = m::spy(Container::class)->makePartial()); - $query = m::mock(Builder::class); - $database->expects('table')->with('table')->andReturn($query); - $query->expects('insertGetId')->andReturnUsing(function (array $array): int { - $payload = json_decode($array['payload'], true); - - $this->assertSame(1700, $payload['timeout']); - $this->assertSame(7, $payload['maxTries']); - $this->assertSame('13', $payload['backoff']); - $this->assertSame(11, $payload['maxExceptions']); - $this->assertFalse($payload['failOnTimeout']); - $this->assertFalse($payload['countCrashesAsExceptions']); - - return 1; - }); - - $queue->push(new ChildJobWithPropertiesOverridingParentAttributes, ['data']); - - $container->shouldHaveReceived('bound')->with('events')->times(3); - } - - public function testPushStillUsesAttributesDeclaredOnSameClassOverDefaultProperties(): void - { - $resolver = m::mock(ConnectionResolverInterface::class); - $database = m::mock(Connection::class); - $resolver->expects('connection')->with(null)->andReturn($database); - $queue = new DatabaseQueue($resolver, null, 'table', 'default'); - $queue->setContainer($container = m::spy(Container::class)->makePartial()); - $query = m::mock(Builder::class); - $database->expects('table')->with('table')->andReturn($query); - $query->expects('insertGetId')->andReturnUsing(function (array $array): int { - $payload = json_decode($array['payload'], true); - - $this->assertSame(40, $payload['timeout']); - $this->assertSame(2, $payload['maxTries']); - $this->assertSame('9', $payload['backoff']); - $this->assertSame(3, $payload['maxExceptions']); - $this->assertTrue($payload['failOnTimeout']); - $this->assertTrue($payload['countCrashesAsExceptions']); - - return 1; - }); - - $queue->push(new JobWithAttributesAndDefaultProperties, ['data']); - - $container->shouldHaveReceived('bound')->with('events')->times(3); - } - public function testFailureToCreatePayloadFromObject(): void { $this->expectException(InvalidArgumentException::class); @@ -370,7 +230,7 @@ public function testFailureToCreatePayloadFromObject(): void $job = new stdClass; $job->invalid = "\xc3\x28"; - $queue = new DatabaseQueue(m::mock(ConnectionResolverInterface::class), null, 'table', 'default'); + $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class), null, 'table', 'default'); $class = new ReflectionClass(Queue::class); $createPayload = $class->getMethod('createPayload'); @@ -384,7 +244,7 @@ public function testFailureToCreatePayloadFromArray(): void { $this->expectException(InvalidArgumentException::class); - $queue = new DatabaseQueue(m::mock(ConnectionResolverInterface::class), null, 'table', 'default'); + $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class), null, 'table', 'default'); $class = new ReflectionClass(Queue::class); $createPayload = $class->getMethod('createPayload'); @@ -394,56 +254,10 @@ public function testFailureToCreatePayloadFromArray(): void ]); } - public function testBulkBatchPushesOntoDatabase(): void - { - $now = CarbonImmutable::now(); - CarbonImmutable::setTestNow($now); - - $uuid = Str::uuid(); - - Str::createUuidsUsing(fn (): Uuid => $uuid); - - $resolver = m::mock(ConnectionResolverInterface::class); - $queue = new TestDatabaseQueue( - resolver: $resolver, - connection: null, - table: 'table', - default: 'default', - currentTime: 1732502704, - availableAt: 1732502704, - ); - $queue->setContainer(new Container); - $connection = m::mock(Connection::class); - $query = m::mock(Builder::class); - $connection->expects('table')->with('table')->andReturn($query); - $resolver->expects('connection')->andReturn($connection); - $query->expects('insert')->andReturnUsing(function (array $records) use ($uuid, $now): bool { - $this->assertEquals([[ - 'queue' => 'queue', - 'payload' => 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(), 'delay' => null]), - 'attempts' => 0, - 'reserved_at' => null, - 'available_at' => 1732502704, - 'created_at' => 1732502704, - ], [ - 'queue' => 'queue', - 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'bar', 'job' => 'bar', 'stringJob' => true, 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $now->getTimestamp(), 'delay' => null]), - 'attempts' => 0, - 'reserved_at' => null, - 'available_at' => 1732502704, - 'created_at' => 1732502704, - ]], $records); - - return true; - }); - - $queue->bulk(['foo', 'bar'], ['data'], 'queue'); - } - public function testBulkUsesOneInsertWithoutATransactionAtTheBindingLimit(): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -451,11 +265,11 @@ public function testBulkUsesOneInsertWithoutATransactionAtTheBindingLimit(): voi ); $queue->setContainer(new Container); - $resolver->shouldReceive('connection')->once()->with(null)->andReturn($connection = m::mock(PdoConnection::class)); - $connection->shouldReceive('maxBindings')->once()->andReturn(12); - $connection->shouldNotReceive('transaction'); - $connection->shouldReceive('table')->once()->with('table')->andReturn($query = m::mock(Builder::class)); - $query->shouldReceive('insert')->once()->with(m::on(static fn (array $rows): bool => count($rows) === 2))->andReturnTrue(); + $resolver->expects('connection')->with(null)->returns($connection = Double::for(PdoConnection::class)); + $connection->expects('maxBindings')->returns(12); + $connection->expects('transaction')->never(); + $connection->expects('table')->with('table')->returns($query = Double::for(Builder::class)); + $query->expects('insert')->with(Argument::satisfies(static fn (array $rows): bool => count($rows) === 2))->returns(true); $this->assertTrue($queue->bulk(['first', 'second'])); } @@ -463,7 +277,7 @@ public function testBulkUsesOneInsertWithoutATransactionAtTheBindingLimit(): voi public function testBulkUsesTheMinimumChunksInsideOneTransactionAboveTheBindingLimit(): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -471,14 +285,14 @@ public function testBulkUsesTheMinimumChunksInsideOneTransactionAboveTheBindingL ); $queue->setContainer(new Container); - $resolver->shouldReceive('connection')->once()->with(null)->andReturn($connection = m::mock(PdoConnection::class)); - $connection->shouldReceive('maxBindings')->once()->andReturn(12); - $connection->shouldReceive('transaction')->once()->andReturnUsing( + $resolver->expects('connection')->with(null)->returns($connection = Double::for(PdoConnection::class)); + $connection->expects('maxBindings')->returns(12); + $connection->expects('transaction')->resolves( static fn (Closure $callback): mixed => $callback() ); - $connection->shouldReceive('table')->twice()->with('table')->andReturn($query = m::mock(Builder::class)); + $connection->expects('table')->times(2)->with('table')->returns($query = Double::for(Builder::class)); $chunkSizes = []; - $query->shouldReceive('insert')->twice()->andReturnUsing(static function (array $rows) use (&$chunkSizes): bool { + $query->expects('insert')->times(2)->resolves(static function (array $rows) use (&$chunkSizes): bool { $chunkSizes[] = count($rows); return true; @@ -491,7 +305,7 @@ public function testBulkUsesTheMinimumChunksInsideOneTransactionAboveTheBindingL public function testBulkTreatsAnExplicitFalseInsertAsFailure(): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -499,9 +313,9 @@ public function testBulkTreatsAnExplicitFalseInsertAsFailure(): void ); $queue->setContainer(new Container); - $resolver->shouldReceive('connection')->once()->with(null)->andReturn($connection = m::mock(Connection::class)); - $connection->shouldReceive('table')->once()->with('table')->andReturn($query = m::mock(Builder::class)); - $query->shouldReceive('insert')->once()->andReturnFalse(); + $resolver->expects('connection')->with(null)->returns($connection = Double::for(Connection::class)); + $connection->expects('table')->with('table')->returns($query = Double::for(Builder::class)); + $query->expects('insert')->returns(false); $this->expectExceptionObject(new RuntimeException('Unable to insert queued jobs into the database.')); @@ -511,7 +325,7 @@ public function testBulkTreatsAnExplicitFalseInsertAsFailure(): void public function testBulkRetainsDispatchOwnershipUntilTheTransactionCommits(): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -520,14 +334,14 @@ public function testBulkRetainsDispatchOwnershipUntilTheTransactionCommits(): vo $queue->setContainer(new Container); $first = new DatabaseBulkOwnedJob; $second = new DatabaseBulkOwnedJob; - $cache = m::mock(CacheRepository::class); + $cache = Double::for(CacheRepository::class); DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1'); DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2'); - $resolver->shouldReceive('connection')->once()->with(null)->andReturn($connection = m::mock(PdoConnection::class)); - $connection->shouldReceive('maxBindings')->once()->andReturn(6); - $connection->shouldReceive('transactionLevel')->twice()->andReturn(0); - $connection->shouldReceive('transaction')->once()->andReturnUsing(function (Closure $callback) use ($first, $second): mixed { + $resolver->expects('connection')->with(null)->returns($connection = Double::for(PdoConnection::class)); + $connection->expects('maxBindings')->returns(6); + $connection->expects('transactionLevel')->times(2)->returns(0); + $connection->expects('transaction')->resolves(function (Closure $callback) use ($first, $second): mixed { $this->assertTrue(DispatchLockContext::has($first)); $this->assertTrue(DispatchLockContext::has($second)); @@ -538,8 +352,8 @@ public function testBulkRetainsDispatchOwnershipUntilTheTransactionCommits(): vo return $result; }); - $connection->shouldReceive('table')->twice()->with('table')->andReturn($query = m::mock(Builder::class)); - $query->shouldReceive('insert')->twice()->andReturnTrue(); + $connection->expects('table')->times(2)->with('table')->returns($query = Double::for(Builder::class)); + $query->expects('insert')->times(2)->returns(true); $this->assertTrue($queue->bulk([$first, $second])); $this->assertFalse(DispatchLockContext::has($first)); @@ -549,7 +363,7 @@ public function testBulkRetainsDispatchOwnershipUntilTheTransactionCommits(): vo public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -561,16 +375,16 @@ public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void $queue->setConnectionName('database'); $first = new DatabaseBulkOwnedJob; $second = new DatabaseBulkOwnedJob; - $cache = m::mock(CacheRepository::class); + $cache = Double::for(CacheRepository::class); DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1'); DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2'); $exception = new RuntimeException('Listener failed.'); $notified = []; - $resolver->shouldReceive('connection')->once()->with(null)->andReturn($connection = m::mock(Connection::class)); - $connection->shouldReceive('transactionLevel')->twice()->andReturn(0); - $connection->shouldReceive('table')->once()->with('table')->andReturn($query = m::mock(Builder::class)); - $query->shouldReceive('insert')->once()->andReturnTrue(); + $resolver->expects('connection')->with(null)->returns($connection = Double::for(Connection::class)); + $connection->expects('transactionLevel')->times(2)->returns(0); + $connection->expects('table')->with('table')->returns($query = Double::for(Builder::class)); + $query->expects('insert')->returns(true); $dispatcher->listen(JobQueued::class, static function (JobQueued $event) use (&$notified): void { $notified[] = $event->job; }); @@ -590,36 +404,10 @@ public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void $this->assertSame([$first, $second], $notified); } - public function testDelayAttributeIsRespectedWhenBulkPushing(): void - { - CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(1732502704)); - - $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), - connection: null, - table: 'table', - default: 'default', - currentTime: 1732502704, - ); - $queue->setContainer(new Container); - $connection = m::mock(Connection::class); - $resolver->expects('connection')->andReturn($connection); - $query = m::mock(Builder::class); - $connection->expects('table')->with('table')->andReturn($query); - $query->expects('insert') - ->andReturnUsing(function (array $records): bool { - $this->assertSame(1732502713, $records[0]['available_at']); - - return true; - }); - - $queue->bulk([new DatabaseBulkAttributeDelayJob]); - } - public function testBulkRaisesExactSuccessEventsAroundOneInsert(): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -630,10 +418,10 @@ public function testBulkRaisesExactSuccessEventsAroundOneInsert(): void $queue->setContainer($container); $queue->setConnectionName('database'); - $connection = m::mock(Connection::class); - $connection->shouldReceive('table')->with('table')->andReturn($query = m::mock(Builder::class)); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection)->once(); - $query->shouldReceive('insert')->once()->andReturnUsing(function (array $records): bool { + $connection = Double::for(Connection::class); + $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class)); + $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']); $this->assertSame('second-final', json_decode($records[1]['payload'], true)['telemetry']); @@ -673,7 +461,7 @@ public function testBulkRaisesExactSuccessEventsAroundOneInsert(): void public function testBulkRaisesExactFailureEventsWhenInsertThrows(): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -685,10 +473,10 @@ public function testBulkRaisesExactFailureEventsWhenInsertThrows(): void $queue->setConnectionName('database'); $exception = new RuntimeException('Insert failed.'); - $connection = m::mock(Connection::class); - $connection->shouldReceive('table')->with('table')->andReturn($query = m::mock(Builder::class)); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection)->once(); - $query->shouldReceive('insert')->once()->andThrow($exception); + $connection = Double::for(Connection::class); + $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class)); + $resolver->expects('connection')->with(null)->returns($connection); + $query->expects('insert')->throws($exception); $events = []; $dispatcher->listen(JobQueueing::class, static function (JobQueueing $event) use (&$events): void { @@ -725,7 +513,7 @@ public function testBulkRaisesExactFailureEventsWhenInsertThrows(): void public function testBulkInsertFailureListenerErrorReporting(string $reporting): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -738,10 +526,10 @@ public function testBulkInsertFailureListenerErrorReporting(string $reporting): $queue->setConnectionName('database'); $exception = new RuntimeException('Insert failed.'); - $connection = m::mock(Connection::class); - $connection->shouldReceive('table')->with('table')->andReturn($query = m::mock(Builder::class)); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection)->once(); - $query->shouldReceive('insert')->once()->andThrow($exception); + $connection = Double::for(Connection::class); + $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class)); + $resolver->expects('connection')->with(null)->returns($connection); + $query->expects('insert')->throws($exception); $listener = new RuntimeException('Listener failed.'); $failed = []; @@ -749,7 +537,7 @@ public function testBulkInsertFailureListenerErrorReporting(string $reporting): $failed[] = $event->job; }); $dispatcher->listen(JobQueueingFailed::class, static fn () => throw $listener); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class); $report = $handler->expects('report')->with($listener); $reportingFailure = match ($reporting) { 'ordinary' => new RuntimeException('Reporting failed.'), @@ -758,7 +546,7 @@ public function testBulkInsertFailureListenerErrorReporting(string $reporting): default => null, }; if ($reportingFailure !== null) { - $report->andThrow($reportingFailure); + $report->throws($reportingFailure); } $container->instance(ExceptionHandler::class, $handler); $directory = ParallelTesting::tempDir('QueueDatabaseQueueReportingTest'); @@ -797,7 +585,7 @@ public function testBulkInsertFailureListenerErrorReporting(string $reporting): #[TestWith([true])] public function testOutboxSelectionCancellationRaisesACanceledEventInsteadOfAFailureEvent(bool $cleanupThrows): void { - $queue = new DatabaseQueue(m::mock(ConnectionResolverInterface::class), null, 'jobs', 'default'); + $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class), null, 'jobs', 'default'); $queue->setConnectionName('database'); $container = new Container; $events = new Dispatcher($container); @@ -850,7 +638,7 @@ public function testOutboxSelectionCancellationRaisesACanceledEventInsteadOfAFai public function testBulkCancellationRaisesCanceledEventsInsteadOfFailureEvents(bool $cleanupThrows): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -861,12 +649,12 @@ public function testBulkCancellationRaisesCanceledEventsInsteadOfFailureEvents(b $queue->setContainer($container); $queue->setConnectionName('database'); - $connection = m::mock(Connection::class); - $connection->shouldReceive('table')->with('table')->andReturn($query = m::mock(Builder::class)); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection)->once(); + $connection = Double::for(Connection::class); + $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class)); + $resolver->expects('connection')->with(null)->returns($connection); $gate = $this->armCurrentCoroutineCancellation(); $cleanup = new RuntimeException('Insert cleanup failed.'); - $query->shouldReceive('insert')->once()->andReturnUsing(static function () use ($gate, $cleanup, $cleanupThrows): never { + $query->expects('insert')->resolves(static function () use ($gate, $cleanup, $cleanupThrows): never { try { $gate->push(true); } finally { @@ -923,14 +711,14 @@ public function testBulkSplitsImmediateAndAfterCommitJobsAndReacquiresTheQueue() CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(1732502704)); $queue = new TestDatabaseQueue( - resolver: $immediateResolver = m::mock(ConnectionResolverInterface::class), + resolver: $immediateResolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', currentTime: 1732502704, ); $deferredQueue = new TestDatabaseQueue( - resolver: $deferredResolver = m::mock(ConnectionResolverInterface::class), + resolver: $deferredResolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -944,21 +732,21 @@ public function testBulkSplitsImmediateAndAfterCommitJobsAndReacquiresTheQueue() $queue->setContainer($container); $deferredQueue->setContainer(new Container); - $immediateConnection = m::mock(Connection::class); - $immediateConnection->shouldReceive('table')->with('table')->andReturn($immediateQuery = m::mock(Builder::class)); - $immediateResolver->shouldReceive('connection')->with(null)->andReturn($immediateConnection)->once(); + $immediateConnection = Double::for(Connection::class); + $immediateConnection->allows('table')->with('table')->returns($immediateQuery = Double::for(Builder::class)); + $immediateResolver->expects('connection')->with(null)->returns($immediateConnection); $immediateRecords = []; - $immediateQuery->shouldReceive('insert')->once()->andReturnUsing(static function (array $records) use (&$immediateRecords): bool { + $immediateQuery->expects('insert')->resolves(static function (array $records) use (&$immediateRecords): bool { $immediateRecords = $records; return true; }); - $deferredConnection = m::mock(Connection::class); - $deferredConnection->shouldReceive('table')->with('table')->andReturn($deferredQuery = m::mock(Builder::class)); - $deferredResolver->shouldReceive('connection')->with(null)->andReturn($deferredConnection)->once(); + $deferredConnection = Double::for(Connection::class); + $deferredConnection->allows('table')->with('table')->returns($deferredQuery = Double::for(Builder::class)); + $deferredResolver->expects('connection')->with(null)->returns($deferredConnection); $deferredRecords = []; - $deferredQuery->shouldReceive('insert')->once()->andReturnUsing(static function (array $records) use (&$deferredRecords): bool { + $deferredQuery->expects('insert')->resolves(static function (array $records) use (&$deferredRecords): bool { $deferredRecords = $records; return true; @@ -992,7 +780,7 @@ public function testBulkSplitsImmediateAndAfterCommitJobsAndReacquiresTheQueue() public function testBulkRollbackDoesNotBeginAnEnqueueAttempt(): void { $queue = new TestDatabaseQueue( - resolver: $resolver = m::mock(ConnectionResolverInterface::class), + resolver: $resolver = Double::for(ConnectionResolverInterface::class), connection: null, table: 'table', default: 'default', @@ -1005,7 +793,7 @@ public function testBulkRollbackDoesNotBeginAnEnqueueAttempt(): void $container->instance('events', $dispatcher); $queue->setContainer($container); - $resolver->shouldNotReceive('connection'); + $resolver->expects('connection')->never(); $dispatched = []; $dispatcher->listen(JobQueueing::class, static function (JobQueueing $event) use (&$dispatched): void { $dispatched[] = $event; @@ -1025,39 +813,9 @@ public function testBulkRollbackDoesNotBeginAnEnqueueAttempt(): void $this->assertSame([], $dispatched); } - public function testBulkDefersAfterCommitJobsUntilTheTransactionCommits(): void - { - $transactions = new DatabaseTransactionsManager; - $transactions->begin('database', 1); - $container = new Container; - $container->instance('db.transactions', $transactions); - - $resolver = m::mock(ConnectionResolverInterface::class); - $database = m::mock(Connection::class); - $resolver->expects('connection')->with(null)->andReturn($database); - $queue = new DatabaseQueue($resolver, null, 'table', 'default'); - $queue->setContainer($container); - - $inserted = false; - $query = m::mock(Builder::class); - $database->expects('table')->with('table')->andReturn($query); - $query->expects('insert')->andReturnUsing(static function () use (&$inserted): bool { - $inserted = true; - - return true; - }); - - $this->assertNull($queue->bulk([new AfterCommitJob])); - $this->assertFalse($inserted); - - $transactions->commit('database', 1, 0); - - $this->assertTrue($inserted); - } - public function testBuildDatabaseRecordWithPayloadAtTheEnd(): void { - $queue = new DatabaseQueue(m::mock(ConnectionResolverInterface::class), null, 'table', 'default'); + $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class), null, 'table', 'default'); $class = new ReflectionClass(DatabaseQueue::class); $record = $class->getMethod('buildDatabaseRecord')->invoke($queue, 'queue', 'any_payload', 0); $this->assertArrayHasKey('payload', $record); @@ -1074,212 +832,14 @@ public function testReservedTimestampRoundsUpAtFractionalSecond(): void $this->assertSame(1001, $record->reserved_at); } - public function testPendingJobs(): void - { - [$queue, $query] = $this->createInspectionQueue(); - $payload = json_encode([ - 'uuid' => 'uuid-11', - 'displayName' => 'PendingJob', - 'job' => 'handler', - 'data' => [], - 'createdAt' => 1000000, - ]); - - $query->expects('where')->with('queue', 'default')->andReturnSelf(); - $query->expects('whereNull')->with('reserved_at')->andReturnSelf(); - $query->expects('where')->with('available_at', '<=', 1732502704)->andReturnSelf(); - $query->expects('get')->andReturn(collect([ - (object) [ - 'id' => 11, - 'queue' => 'default', - 'payload' => $payload, - 'attempts' => 0, - ], - ])); - - $jobs = $queue->pendingJobs(); - - $this->assertInspectedJob($jobs->sole(), 'PendingJob', 'default', 0, 11); - } - - public function testDelayedJobs(): void - { - [$queue, $query] = $this->createInspectionQueue(); - $payload = json_encode([ - 'uuid' => 'uuid-12', - 'displayName' => 'DelayedJob', - 'job' => 'handler', - 'data' => [], - 'createdAt' => 1000000, - ]); - - $query->expects('where')->with('queue', 'emails')->andReturnSelf(); - $query->expects('whereNull')->with('reserved_at')->andReturnSelf(); - $query->expects('where')->with('available_at', '>', 1732502704)->andReturnSelf(); - $query->expects('get')->andReturn(collect([ - (object) [ - 'id' => 12, - 'queue' => 'emails', - 'payload' => $payload, - 'attempts' => 0, - ], - ])); - - $jobs = $queue->delayedJobs('emails'); - - $this->assertInspectedJob($jobs->sole(), 'DelayedJob', 'emails', 0, 12); - } - - public function testReservedJobs(): void - { - [$queue, $query] = $this->createInspectionQueue(); - $payload = json_encode([ - 'uuid' => 'uuid-13', - 'displayName' => 'ReservedJob', - 'job' => 'handler', - 'data' => [], - 'createdAt' => 1000000, - ]); - - $query->expects('where')->with('queue', 'default')->andReturnSelf(); - $query->expects('whereNotNull')->with('reserved_at')->andReturnSelf(); - $query->expects('get')->andReturn(collect([ - (object) [ - 'id' => 13, - 'queue' => 'default', - 'payload' => $payload, - 'attempts' => 3, - ], - ])); - - $jobs = $queue->reservedJobs(); - - $this->assertInspectedJob($jobs->sole(), 'ReservedJob', 'default', 3, 13); - } - - public function testAllPendingJobs(): void - { - [$queue, $query] = $this->createInspectionQueue(); - $query->expects('whereNull')->with('reserved_at')->andReturnSelf(); - $query->expects('where')->with('available_at', '<=', 1732502704)->andReturnSelf(); - $query->expects('get')->andReturn(collect([ - $this->inspectionRecord(21, 'default', 'FirstPendingJob', 0), - $this->inspectionRecord(22, 'emails', 'SecondPendingJob', 1), - ])); - - $jobs = $queue->allPendingJobs(); - - $this->assertCount(2, $jobs); - $this->assertInspectedJob($jobs->first(), 'FirstPendingJob', 'default', 0, 21); - $this->assertInspectedJob($jobs->last(), 'SecondPendingJob', 'emails', 1, 22); - } - - public function testAllDelayedJobs(): void - { - [$queue, $query] = $this->createInspectionQueue(); - $query->expects('whereNull')->with('reserved_at')->andReturnSelf(); - $query->expects('where')->with('available_at', '>', 1732502704)->andReturnSelf(); - $query->expects('get')->andReturn(collect([ - $this->inspectionRecord(31, 'default', 'FirstDelayedJob', 0), - $this->inspectionRecord(32, 'emails', 'SecondDelayedJob', 0), - ])); - - $jobs = $queue->allDelayedJobs(); - - $this->assertCount(2, $jobs); - $this->assertInspectedJob($jobs->first(), 'FirstDelayedJob', 'default', 0, 31); - $this->assertInspectedJob($jobs->last(), 'SecondDelayedJob', 'emails', 0, 32); - } - - public function testAllReservedJobs(): void - { - [$queue, $query] = $this->createInspectionQueue(); - $query->expects('whereNotNull')->with('reserved_at')->andReturnSelf(); - $query->expects('get')->andReturn(collect([ - $this->inspectionRecord(41, 'default', 'FirstReservedJob', 1), - $this->inspectionRecord(42, 'emails', 'SecondReservedJob', 2), - ])); - - $jobs = $queue->allReservedJobs(); - - $this->assertCount(2, $jobs); - $this->assertInspectedJob($jobs->first(), 'FirstReservedJob', 'default', 1, 41); - $this->assertInspectedJob($jobs->last(), 'SecondReservedJob', 'emails', 2, 42); - } - - public function testTotalSize(): void - { - $resolver = m::mock(ConnectionResolverInterface::class); - $database = m::mock(Connection::class); - $resolver->expects('connection')->with(null)->andReturn($database); - $queue = new TestDatabaseQueue($resolver, null, 'table', 'default', 1732502704); - $queue->setContainer(new Container); - - $query = m::mock(Builder::class); - $database->expects('table')->with('table')->andReturn($query); - $query->expects('count')->andReturn(9); - - $this->assertSame(9, $queue->totalSize()); - } - - public function testTotalPendingSize(): void - { - $resolver = m::mock(ConnectionResolverInterface::class); - $database = m::mock(Connection::class); - $resolver->expects('connection')->with(null)->andReturn($database); - $queue = new TestDatabaseQueue($resolver, null, 'table', 'default', 1732502704); - $queue->setContainer(new Container); - - $query = m::mock(Builder::class); - $database->expects('table')->with('table')->andReturn($query); - $query->expects('whereNull')->with('reserved_at')->andReturnSelf(); - $query->expects('where')->with('available_at', '<=', 1732502704)->andReturnSelf(); - $query->expects('count')->andReturn(2); - - $this->assertSame(2, $queue->totalPendingSize()); - } - - public function testTotalDelayedSize(): void - { - $resolver = m::mock(ConnectionResolverInterface::class); - $database = m::mock(Connection::class); - $resolver->expects('connection')->with(null)->andReturn($database); - $queue = new TestDatabaseQueue($resolver, null, 'table', 'default', 1732502704); - $queue->setContainer(new Container); - - $query = m::mock(Builder::class); - $database->expects('table')->with('table')->andReturn($query); - $query->expects('whereNull')->with('reserved_at')->andReturnSelf(); - $query->expects('where')->with('available_at', '>', 1732502704)->andReturnSelf(); - $query->expects('count')->andReturn(3); - - $this->assertSame(3, $queue->totalDelayedSize()); - } - - public function testTotalReservedSize(): void - { - $resolver = m::mock(ConnectionResolverInterface::class); - $database = m::mock(Connection::class); - $resolver->expects('connection')->with(null)->andReturn($database); - $queue = new TestDatabaseQueue($resolver, null, 'table', 'default', 1732502704); - $queue->setContainer(new Container); - - $query = m::mock(Builder::class); - $database->expects('table')->with('table')->andReturn($query); - $query->expects('whereNotNull')->with('reserved_at')->andReturnSelf(); - $query->expects('count')->andReturn(4); - - $this->assertSame(4, $queue->totalReservedSize()); - } - public function testGetLockForPoppingIsCached(): void { - $pdo = m::mock(PDO::class); + $pdo = Double::for(PDO::class); // Initial resolution reads the version and identifies MariaDB; later calls reuse the lock. - $pdo->expects('getAttribute')->twice()->with(PDO::ATTR_SERVER_VERSION)->andReturn('8.0.36'); + $pdo->expects('getAttribute')->times(2)->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.36'); $database = new MySqlConnection($pdo, 'test'); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->expects('connection')->twice()->with(null)->andReturn($database); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->times(2)->with(null)->returns($database); $queue = new TestDatabaseQueue($resolver, null, 'table', 'default', 1732502704); $result1 = $queue->lockForPopping(); @@ -1292,10 +852,10 @@ public function testGetLockForPoppingIsCached(): void public function testInvalidInspectedPayloadIdentifiesItsQueueAndRecord(): void { [$queue, $query] = $this->createInspectionQueue(); - $query->shouldReceive('where')->with('queue', 'emails')->andReturnSelf(); - $query->shouldReceive('whereNull')->with('reserved_at')->andReturnSelf(); - $query->shouldReceive('where')->with('available_at', '<=', 1732502704)->andReturnSelf(); - $query->shouldReceive('get')->andReturn(collect([ + $query->allows('where')->with('queue', 'emails')->returns($query); + $query->allows('whereNull')->with('reserved_at')->returns($query); + $query->allows('where')->with('available_at', '<=', 1732502704)->returns($query); + $query->allows('get')->returns(collect([ (object) [ 'id' => 99, 'queue' => 'emails', @@ -1318,18 +878,16 @@ public function testInvalidInspectedPayloadIdentifiesItsQueueAndRecord(): void */ private function createFailingReservationQueue(Throwable $failure): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection); - $connection->shouldReceive('transactionLevel')->andReturn(0); - $connection->shouldReceive('transaction')->once()->andReturnUsing(static fn (Closure $callback): mixed => $callback()); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $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 = m::mock(DispatcherContract::class); + $events = Double::for(DispatcherContract::class); $container->instance(DispatcherContract::class, $events); - $queue = m::mock(DatabaseQueue::class, [$resolver, null, 'jobs']) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); + $queue = Double::for(DatabaseQueue::class)->passthru(new DatabaseQueue($resolver, null, 'jobs')); $queue->setContainer($container); $queue->setConnectionName('database'); $record = new DatabaseJobRecord((object) [ @@ -1337,8 +895,8 @@ private function createFailingReservationQueue(Throwable $failure): array 'payload' => json_encode(['job' => stdClass::class, 'data' => []]), 'attempts' => 255, ]); - $queue->shouldReceive('getNextAvailableJob')->once()->with('default')->andReturn($record); - $queue->shouldReceive('marshalJob')->once()->with('default', $record)->andThrow($failure); + $queue->expects('getNextAvailableJob')->with('default')->returns($record); + $queue->expects('marshalJob')->with('default', $record)->throws($failure); return [$queue, $events]; } @@ -1348,11 +906,11 @@ private function createFailingReservationQueue(Throwable $failure): array */ private function createInspectionQueue(): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $query = m::mock(Builder::class); - $resolver->expects('connection')->with(null)->andReturn($connection); - $connection->expects('table')->with('table')->andReturn($query); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $query = Double::for(Builder::class); + $resolver->expects('connection')->with(null)->returns($connection); + $connection->expects('table')->with('table')->returns($query); return [ new TestDatabaseQueue( @@ -1381,69 +939,6 @@ private function armCurrentCoroutineCancellation(): Channel return $gate; } - - /** - * Create a database record for inspection. - */ - private function inspectionRecord( - int $id, - string $queue, - string $name, - int $attempts, - ): object { - return (object) [ - 'id' => $id, - 'queue' => $queue, - 'payload' => json_encode([ - 'uuid' => "uuid-{$id}", - 'displayName' => $name, - 'job' => 'handler', - 'data' => [], - 'createdAt' => 1000000, - ]), - 'attempts' => $attempts, - ]; - } - - /** - * Assert the inspected job metadata. - */ - private function assertInspectedJob( - InspectedJob $job, - string $name, - string $queue, - int $attempts, - int $id, - ): void { - $this->assertSame($name, $job->name); - $this->assertSame("uuid-{$id}", $job->uuid); - $this->assertSame($queue, $job->queue); - $this->assertSame($attempts, $job->attempts); - $this->assertSame($id, $job->id); - $this->assertInstanceOf(CarbonImmutable::class, $job->createdAt); - $this->assertSame(1000000, $job->createdAt->getTimestamp()); - } -} - -class MyTestJob -{ - /** - * Handle the queued job. - */ - public function handle(): void - { - // ... - } -} - -class MyBatchableJob -{ - use Batchable; -} - -#[Delay(9)] -class DatabaseBulkAttributeDelayJob -{ } #[Delay(9)] @@ -1455,57 +950,6 @@ class DatabaseBulkOwnedJob { } -class AfterCommitJob implements ShouldQueue -{ - public bool $afterCommit = true; -} - -#[Backoff(9)] -#[CountCrashesAsExceptions] -#[FailOnTimeout] -#[MaxExceptions(3)] -#[Timeout(40)] -#[Tries(2)] -abstract class ParentJobWithAttributes implements ShouldQueue -{ -} - -class ChildJobWithPropertiesOverridingParentAttributes extends ParentJobWithAttributes -{ - public int $backoff = 13; - - public bool $countCrashesAsExceptions = false; - - public bool $failOnTimeout = false; - - public int $maxExceptions = 11; - - public int $timeout = 1700; - - public int $tries = 7; -} - -#[Backoff(9)] -#[CountCrashesAsExceptions] -#[FailOnTimeout] -#[MaxExceptions(3)] -#[Timeout(40)] -#[Tries(2)] -class JobWithAttributesAndDefaultProperties implements ShouldQueue -{ - public int $backoff = 13; - - public bool $countCrashesAsExceptions = false; - - public bool $failOnTimeout = false; - - public int $maxExceptions = 11; - - public int $timeout = 1700; - - public int $tries = 7; -} - class TestDatabaseQueue extends DatabaseQueue { /** @@ -1517,7 +961,6 @@ public function __construct( string $table, string $default, private readonly int $currentTime, - private readonly ?int $availableAt = null, ) { parent::__construct($resolver, $connection, $table, $default); } @@ -1537,12 +980,4 @@ public function lockForPopping(): bool|string { return $this->getLockForPopping(); } - - /** - * Get the available timestamp for the delay. - */ - protected function availableAt(DateInterval|DateTimeInterface|int|null $delay = 0): int - { - return $this->availableAt ?? parent::availableAt($delay); - } } diff --git a/tests/Queue/QueueForgetFailedCommandTest.php b/tests/Queue/QueueForgetFailedCommandTest.php index 4c8c47f1f..9df3611a7 100644 --- a/tests/Queue/QueueForgetFailedCommandTest.php +++ b/tests/Queue/QueueForgetFailedCommandTest.php @@ -9,17 +9,20 @@ use Hypervel\Queue\Console\ForgetFailedCommand; use Hypervel\Queue\Failed\FailedJobProviderInterface; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; class QueueForgetFailedCommandTest extends TestCase { + use VerifiesDoubles; + public function testItForgetsASingleJob(): void { $container = new Application; - $failer = m::mock(FailedJobProviderInterface::class); - $failer->shouldReceive('forget')->with('5')->andReturnTrue(); + $failer = Double::for(FailedJobProviderInterface::class); + $failer->expects('forget')->with('5')->returns(true); $container->instance(FailedJobProviderInterface::class, $failer); $command = new ForgetFailedCommand; @@ -34,9 +37,9 @@ public function testItForgetsASingleJob(): void public function testItForgetsMultipleJobs(): void { $container = new Application; - $failer = m::mock(FailedJobProviderInterface::class); - $failer->shouldReceive('forget')->with('5')->andReturnTrue(); - $failer->shouldReceive('forget')->with('6')->andReturnTrue(); + $failer = Double::for(FailedJobProviderInterface::class); + $failer->expects('forget')->with('5')->returns(true); + $failer->expects('forget')->with('6')->returns(true); $container->instance(FailedJobProviderInterface::class, $failer); $command = new ForgetFailedCommand; @@ -55,8 +58,8 @@ public function testItForgetsMultipleJobs(): void public function testItFailsWhenAJobCannotBeFound(): void { $container = new Application; - $failer = m::mock(FailedJobProviderInterface::class); - $failer->shouldReceive('forget')->with('5')->andReturnFalse(); + $failer = Double::for(FailedJobProviderInterface::class); + $failer->expects('forget')->with('5')->returns(false); $container->instance(FailedJobProviderInterface::class, $failer); $command = new ForgetFailedCommand; @@ -71,10 +74,10 @@ public function testItFailsWhenAJobCannotBeFound(): void public function testItForgetsTheRemainingJobsWhenOneCannotBeFound(): void { $container = new Application; - $failer = m::mock(FailedJobProviderInterface::class); - $failer->shouldReceive('forget')->with('5')->andReturnTrue(); - $failer->shouldReceive('forget')->with('6')->andReturnFalse(); - $failer->shouldReceive('forget')->with('7')->andReturnTrue(); + $failer = Double::for(FailedJobProviderInterface::class); + $failer->expects('forget')->with('5')->returns(true); + $failer->expects('forget')->with('6')->returns(false); + $failer->expects('forget')->with('7')->returns(true); $container->instance(FailedJobProviderInterface::class, $failer); $command = new ForgetFailedCommand; diff --git a/tests/Queue/QueueListFailedCommandTest.php b/tests/Queue/QueueListFailedCommandTest.php index bc63556ac..ead57f424 100644 --- a/tests/Queue/QueueListFailedCommandTest.php +++ b/tests/Queue/QueueListFailedCommandTest.php @@ -9,12 +9,15 @@ use Hypervel\Queue\Failed\FailedJobProviderInterface; use Hypervel\Queue\SyncQueue; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; class QueueListFailedCommandTest extends TestCase { + use VerifiesDoubles; + public function testQueuedListenerShowsUnderlyingListenerClassNotWrapper(): void { // CallQueuedListener is the wrapper class Hypervel uses to dispatch @@ -166,8 +169,8 @@ private function executeCommand(array $rows): string $container = new Application; // The command resolves the failer via the queue.failer container binding. - $failer = m::mock(FailedJobProviderInterface::class); - $failer->expects('all')->andReturn($rows); + $failer = Double::for(FailedJobProviderInterface::class); + $failer->expects('all')->returns($rows); $container->instance('queue.failer', $failer); $command = new ListFailedCommand; diff --git a/tests/Queue/QueueListenerTest.php b/tests/Queue/QueueListenerTest.php index 53d022e56..d3a1609ef 100644 --- a/tests/Queue/QueueListenerTest.php +++ b/tests/Queue/QueueListenerTest.php @@ -8,7 +8,8 @@ use Hypervel\Queue\ListenerOptions; use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Symfony\Component\Process\Process; @@ -19,6 +20,8 @@ class QueueListenerTest extends TestCase { + use VerifiesDoubles; + public function testOutputFailureStopsTheWorkerProcess(): void { $process = new Process([PHP_BINARY, '-r', 'echo "progress"; usleep(5000000);']); @@ -43,20 +46,20 @@ public function testOutputFailureStopsTheWorkerProcess(): void public function testRunProcessCallsProcess(): void { - $process = m::mock(Process::class)->makePartial(); + $process = Double::for(Process::class)->passthru(new Process([PHP_BINARY])); $process->expects('run'); - $listener = m::mock(Listener::class)->makePartial(); - $listener->expects('memoryExceeded')->with(1)->andReturn(false); + $listener = Double::for(Listener::class)->passthru(new Listener(__DIR__)); + $listener->expects('memoryExceeded')->with(1.0)->returns(false); $listener->runProcess($process, 1); } public function testListenerStopsWhenMemoryIsExceeded(): void { - $process = m::mock(Process::class)->makePartial(); + $process = Double::for(Process::class)->passthru(new Process([PHP_BINARY])); $process->expects('run'); - $listener = m::mock(Listener::class)->makePartial(); - $listener->expects('memoryExceeded')->with(1)->andReturn(true); + $listener = Double::for(Listener::class)->passthru(new Listener(__DIR__)); + $listener->expects('memoryExceeded')->with(1.0)->returns(true); $listener->expects('stop'); $listener->runProcess($process, 1); @@ -67,9 +70,9 @@ public function testListenRestsForFractionalSecondsBetweenWorkers(): void Sleep::fake(); $stop = new RuntimeException('Stop listening.'); $runs = 0; - $listener = m::mock(Listener::class)->makePartial(); - $listener->allows('makeProcess')->andReturn(m::mock(Process::class)); - $listener->expects('runProcess')->twice()->andReturnUsing(static function () use (&$runs, $stop): void { + $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/QueuePauseResumeTest.php b/tests/Queue/QueuePauseResumeTest.php index a0e7ac916..a83fd7ff3 100644 --- a/tests/Queue/QueuePauseResumeTest.php +++ b/tests/Queue/QueuePauseResumeTest.php @@ -8,6 +8,7 @@ use Hypervel\Cache\Repository as CacheRepository; use Hypervel\Config\Repository as ConfigRepository; use Hypervel\Container\Container; +use Hypervel\Contracts\Cache\Factory as CacheFactory; use Hypervel\Contracts\Cache\Repository as CacheContract; use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; use Hypervel\Events\Dispatcher; @@ -19,13 +20,16 @@ use Hypervel\Queue\QueueManager; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use UnitEnum; class QueuePauseResumeTest extends TestCase { + use VerifiesDoubles; + protected QueueManager $manager; protected CacheRepository $cache; @@ -61,23 +65,9 @@ protected function createManager(CacheContract $cache): QueueManager ], ], ])); - $container->instance('cache', new class($cache) { - /** - * Create a cache manager fixture. - */ - public function __construct( - private readonly CacheContract $repository, - ) { - } - - /** - * Get the cache repository. - */ - public function store(?string $name = null): CacheContract - { - return $this->repository; - } - }); + $cacheManager = Double::for(CacheFactory::class); + $cacheManager->allows('store')->returns($cache); + $container->instance('cache', $cacheManager); $container->instance('events', $this->events); $container->instance(DispatcherContract::class, $this->events); @@ -275,12 +265,12 @@ public function testGetPausedQueues(): void public function testGetPausedQueuesUsesTheCacheRepositoryContract(): void { - $cache = m::mock(CacheContract::class); - $cache->shouldReceive('get')->once()->with('illuminate:queues:paused', false)->andReturn(false); - $cache->shouldReceive('get')->once()->with([ + $cache = Double::for(CacheContract::class); + $cache->expects('get')->with('illuminate:queues:paused', false)->returns(false); + $cache->expects('get')->with([ 'illuminate:queue:paused:redis:default', 'illuminate:queue:paused:redis:emails', - ])->andReturn([ + ])->returns([ 'illuminate:queue:paused:redis:default' => null, 'illuminate:queue:paused:redis:emails' => true, ]); diff --git a/tests/Queue/QueueRedisJobTest.php b/tests/Queue/QueueRedisJobTest.php index d413512d1..60e8359ab 100644 --- a/tests/Queue/QueueRedisJobTest.php +++ b/tests/Queue/QueueRedisJobTest.php @@ -4,24 +4,27 @@ namespace Hypervel\Tests\Queue; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; use Hypervel\Queue\InvalidPayloadException; use Hypervel\Queue\Jobs\RedisJob; use Hypervel\Queue\RedisQueue; use Hypervel\Tests\TestCase; -use Mockery as m; -use stdClass; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class QueueRedisJobTest extends TestCase { + use VerifiesDoubles; + public function testFireProperlyCallsTheJobHandler(): void { $job = $this->getJob(); - $handler = m::mock(stdClass::class); - $job->getContainer()->expects('make')->with('foo')->andReturn($handler); - $handler->expects('fire')->with($job, ['data']); + $handler = new RedisJobTestHandler; + $job->getContainer()->instance('foo', $handler); $job->fire(); + + $this->assertSame([[$job, ['data']]], $handler->fired); } public function testDeleteRemovesTheJobFromRedis(): void @@ -102,8 +105,8 @@ protected function capturePayloadException(RedisJob $job): InvalidPayloadExcepti protected function getJob(?string $payload = null, ?int $attempts = 2): RedisJob { return new RedisJob( - m::mock(Container::class), - m::mock(RedisQueue::class), + new Container, + Double::for(RedisQueue::class), $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', @@ -112,3 +115,16 @@ protected function getJob(?string $payload = null, ?int $attempts = 2): RedisJob ); } } + +class RedisJobTestHandler +{ + public array $fired = []; + + /** + * Record the invoked job handler. + */ + public function fire(RedisJob $job, array $data): void + { + $this->fired[] = [$job, $data]; + } +} diff --git a/tests/Queue/QueueRedisQueueTest.php b/tests/Queue/QueueRedisQueueTest.php index e0a6a4569..b9fcbb690 100644 --- a/tests/Queue/QueueRedisQueueTest.php +++ b/tests/Queue/QueueRedisQueueTest.php @@ -25,7 +25,6 @@ use Hypervel\Queue\Queue; use Hypervel\Queue\QueueRoutes; use Hypervel\Queue\RedisQueue; -use Hypervel\Redis\RedisConnection; use Hypervel\Redis\RedisProxy; use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Collection; @@ -33,7 +32,9 @@ use Hypervel\Tests\Queue\Fixtures\IntegerQueueName; use Hypervel\Tests\Queue\Fixtures\UnitQueueName; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -43,6 +44,8 @@ class QueueRedisQueueTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('totalSizeMethods')] public function testTotalsCountPhysicalQueuesInsidePinnedConnection(string $totalMethod, string $command, array $firstArguments, array $secondArguments): void { @@ -50,8 +53,8 @@ public function testTotalsCountPhysicalQueuesInsidePinnedConnection(string $tota $routes->forward('emails', 'reports:high'); Container::getInstance()->instance('queue.routes', $routes); $pinned = false; - $connection = m::mock(RedisProxy::class); - $connection->expects('withPinnedConnection')->andReturnUsing(function (callable $callback) use (&$pinned): int { + $connection = Double::for(QueueRedisProxy::class); + $connection->expects('withPinnedConnection')->resolves(function (callable $callback) use (&$pinned): int { $pinned = true; try { @@ -60,23 +63,21 @@ public function testTotalsCountPhysicalQueuesInsidePinnedConnection(string $tota $pinned = false; } }); - $connection->expects('isCluster')->andReturnFalse(); - $connection->expects($command)->with(...$firstArguments)->andReturnUsing(function () use (&$pinned): int { + $connection->expects('isCluster')->returns(false); + $connection->expects($command)->with(...$firstArguments)->resolves(function () use (&$pinned): int { $this->assertTrue($pinned); return 5; }); - $connection->expects($command)->with(...$secondArguments)->andReturnUsing(function () use (&$pinned): int { + $connection->expects($command)->with(...$secondArguments)->resolves(function () use (&$pinned): int { $this->assertTrue($pinned); return 7; }); - $redis = m::mock(Redis::class); - $redis->shouldReceive('connection')->with(null)->andReturn($connection); - $queue = m::mock(RedisQueue::class, [$redis, 'default']) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); - $queue->expects('allQueueNames')->andReturnUsing(function () use (&$pinned): Collection { + $redis = Double::for(Redis::class); + $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 { $this->assertTrue($pinned); return new Collection(['emails', 'reports:high']); @@ -105,10 +106,10 @@ public function testBulkRespectsDelayAttributeWhenPushingOntoRedis(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); - $connection = $this->mockRedisProxyWithShaCache(); - $connection->expects('isCluster')->andReturnFalse(); + $connection = Double::for(QueueRedisProxy::class); + $connection->expects('isCluster')->returns(false); $connection->expects('evalWithShaCache') - ->withArgs(function (string $script, array $keys, array $arguments): bool { + ->with(Argument::all(function (string $script, array $keys, array $arguments): bool { $this->assertSame(LuaScripts::bulk(), $script); $this->assertSame([ 'queues:critical', @@ -127,10 +128,10 @@ public function testBulkRespectsDelayAttributeWhenPushingOntoRedis(): void ]); return true; - }) - ->andReturn(3); - $redis = m::mock(Redis::class); - $redis->expects('connection')->with('default')->andReturn($connection); + })) + ->returns(3); + $redis = Double::for(Redis::class); + $redis->expects('connection')->with('default')->returns($connection); $queue = new RedisQueue($redis, 'default', 'default'); $queue->setContainer(new Container); @@ -144,20 +145,20 @@ public function testBulkRespectsDelayAttributeWhenPushingOntoRedis(): void public function testBulkUsesOneClusterSafeLuaCall(): void { - $connection = $this->mockRedisProxyWithShaCache(); - $connection->expects('isCluster')->andReturnTrue(); + $connection = Double::for(QueueRedisProxy::class); + $connection->expects('isCluster')->returns(true); $connection->expects('evalWithShaCache') ->with( LuaScripts::bulk(), ['queues:{default}', 'queues:{default}:notify', 'queues:{default}:delayed'], - m::on(static fn (array $arguments): bool => $arguments[0] === 'i' + Argument::satisfies(static fn (array $arguments): bool => $arguments[0] === 'i' && json_decode($arguments[1], true)['job'] === 'first' && $arguments[2] === 'i' && json_decode($arguments[3], true)['job'] === 'second'), ) - ->andReturn(2); - $redis = m::mock(Redis::class); - $redis->expects('connection')->with('default')->andReturn($connection); + ->returns(2); + $redis = Double::for(Redis::class); + $redis->expects('connection')->with('default')->returns($connection); $queue = new RedisQueue($redis, 'default', 'default'); $queue->setContainer(new Container); @@ -168,11 +169,11 @@ public function testBulkUsesOneClusterSafeLuaCall(): void public function testBulkRedisFailureIsNotReplacedByAFailingFailureListener(): void { $exception = new RuntimeException('Redis unavailable.'); - $connection = $this->mockRedisProxyWithShaCache(); - $connection->expects('isCluster')->andReturnFalse(); - $connection->expects('evalWithShaCache')->andThrow($exception); - $redis = m::mock(Redis::class); - $redis->expects('connection')->with('default')->andReturn($connection); + $connection = Double::for(QueueRedisProxy::class); + $connection->expects('isCluster')->returns(false); + $connection->expects('evalWithShaCache')->throws($exception); + $redis = Double::for(Redis::class); + $redis->expects('connection')->with('default')->returns($connection); Container::setInstance($container = new Container); $events = new EventDispatcher($container); @@ -187,7 +188,7 @@ public function testBulkRedisFailureIsNotReplacedByAFailingFailureListener(): vo $failed[] = $event; }); $events->listen(JobQueueingFailed::class, static fn () => throw $listener); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class); $handler->expects('report')->with($listener); $container->instance(ExceptionHandler::class, $handler); @@ -212,11 +213,11 @@ public function testCancellationRaisesCanceledEventsInsteadOfFailureEvents(strin if ($cleanupThrows) { $cancellation = new RuntimeException('Redis cleanup failed.', previous: $cancellation); } - $connection = $this->mockRedisProxyWithShaCache(); - $connection->expects('isCluster')->andReturnFalse(); - $connection->expects('evalWithShaCache')->andThrow($cancellation); - $redis = m::mock(Redis::class); - $redis->shouldReceive('connection')->with('default')->andReturn($connection); + $connection = Double::for(QueueRedisProxy::class); + $connection->expects('isCluster')->returns(false); + $connection->expects('evalWithShaCache')->throws($cancellation); + $redis = Double::for(Redis::class); + $redis->allows('connection')->with('default')->returns($connection); Container::setInstance($container = new Container); $events = new EventDispatcher($container); @@ -252,24 +253,24 @@ public function testCancellationRaisesCanceledEventsInsteadOfFailureEvents(strin public function testEmptyBulkDoesNotResolveRedis(): void { - $redis = m::mock(Redis::class); - $redis->shouldNotReceive('connection'); + $redis = Double::for(Redis::class); + $redis->expects('connection')->never(); $this->assertNull((new RedisQueue($redis, 'default', 'default'))->bulk([])); } public function testBulkAcceptsDispatchOwnershipOnlyAfterRedisConfirmsEveryJob(): void { - $connection = $this->mockRedisProxyWithShaCache(); - $connection->expects('isCluster')->andReturnFalse(); - $connection->expects('evalWithShaCache')->andReturn(2); - $redis = m::mock(Redis::class); - $redis->expects('connection')->with('default')->andReturn($connection); + $connection = Double::for(QueueRedisProxy::class); + $connection->expects('isCluster')->returns(false); + $connection->expects('evalWithShaCache')->returns(2); + $redis = Double::for(Redis::class); + $redis->expects('connection')->with('default')->returns($connection); $queue = new RedisQueue($redis, 'default', 'default'); $queue->setContainer(new Container); $first = new RedisBulkOwnedJob; $second = new RedisBulkOwnedJob; - $cache = m::mock(CacheRepository::class); + $cache = Double::for(CacheRepository::class); DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1'); DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2'); @@ -281,11 +282,11 @@ public function testBulkAcceptsDispatchOwnershipOnlyAfterRedisConfirmsEveryJob() public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void { - $connection = $this->mockRedisProxyWithShaCache(); - $connection->expects('isCluster')->andReturnFalse(); - $connection->expects('evalWithShaCache')->andReturn(2); - $redis = m::mock(Redis::class); - $redis->expects('connection')->with('default')->andReturn($connection); + $connection = Double::for(QueueRedisProxy::class); + $connection->expects('isCluster')->returns(false); + $connection->expects('evalWithShaCache')->returns(2); + $redis = Double::for(Redis::class); + $redis->expects('connection')->with('default')->returns($connection); $queue = new RedisQueue($redis, 'default', 'default'); $dispatcher = new EventDispatcher($container = new Container); $container->instance('events', $dispatcher); @@ -293,7 +294,7 @@ public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void $queue->setConnectionName('redis'); $first = new RedisBulkOwnedJob; $second = new RedisBulkOwnedJob; - $cache = m::mock(CacheRepository::class); + $cache = Double::for(CacheRepository::class); DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1'); DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2'); $exception = new RuntimeException('Listener failed.'); @@ -320,16 +321,16 @@ public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void public function testBulkRetainsDispatchOwnershipWhenRedisDoesNotConfirmEveryJob(): void { - $connection = $this->mockRedisProxyWithShaCache(); - $connection->expects('isCluster')->andReturnFalse(); - $connection->expects('evalWithShaCache')->andReturn(1); - $redis = m::mock(Redis::class); - $redis->expects('connection')->with('default')->andReturn($connection); + $connection = Double::for(QueueRedisProxy::class); + $connection->expects('isCluster')->returns(false); + $connection->expects('evalWithShaCache')->returns(1); + $redis = Double::for(Redis::class); + $redis->expects('connection')->with('default')->returns($connection); $queue = new RedisQueue($redis, 'default', 'default'); $queue->setContainer(new Container); $first = new RedisBulkOwnedJob; $second = new RedisBulkOwnedJob; - $cache = m::mock(CacheRepository::class); + $cache = Double::for(CacheRepository::class); DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1'); DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2'); $caught = null; @@ -347,18 +348,18 @@ public function testBulkRetainsDispatchOwnershipWhenRedisDoesNotConfirmEveryJob( public function testBulkDefersAfterCommitMembersWithoutLosingOwnership(): void { - $connection = $this->mockRedisProxyWithShaCache(); - $connection->expects('isCluster')->andReturnFalse(); + $connection = Double::for(QueueRedisProxy::class); + $connection->expects('isCluster')->returns(false); $storedJobs = []; - $connection->expects('evalWithShaCache')->twice()->andReturnUsing( + $connection->expects('evalWithShaCache')->times(2)->resolves( static function (string $script, array $keys, array $arguments) use (&$storedJobs): int { $storedJobs[] = json_decode($arguments[1], true)['displayName']; return 1; } ); - $redis = m::mock(Redis::class); - $redis->expects('connection')->twice()->with('default')->andReturn($connection); + $redis = Double::for(Redis::class); + $redis->expects('connection')->times(2)->with('default')->returns($connection); $transactions = new DatabaseTransactionsManager; $transactions->begin('default', 1); $container = new Container; @@ -366,7 +367,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, m::mock(CacheRepository::class), 'deferred', 'owner'); + DispatchLockContext::registerDebounce($deferred, Double::for(CacheRepository::class), 'deferred', 'owner'); $queue->bulk(['immediate', $deferred]); @@ -379,83 +380,33 @@ static function (string $script, array $keys, array $arguments) use (&$storedJob $this->assertFalse(DispatchLockContext::has($deferred)); } - public function testPushProperlyPushesJobOntoRedis(): void - { - $now = CarbonImmutable::now(); - CarbonImmutable::setTestNow($now); - $uuid = $this->mockUuid(); - - $redis = m::mock(Redis::class); - $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis, 'default', 'default'])->getMock(); - $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); - $container = m::spy(Container::class)->makePartial(); - $queue->setContainer($container); - $queue->setConnectionName('default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(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')->twice()->andReturn($redisProxy); - - $id = $queue->push('foo', ['data']); - $this->assertSame('foo', $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); - } - - public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook(): void - { - $now = CarbonImmutable::now(); - CarbonImmutable::setTestNow($now); - $uuid = $this->mockUuid(); - - $redis = m::mock(Redis::class); - $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis, 'default', 'default'])->getMock(); - $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); - $container = m::spy(Container::class)->makePartial(); - $queue->setContainer($container); - $queue->setConnectionName('default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(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(), 'custom' => 'taylor', 'id' => 'foo', 'attempts' => 0, 'delay' => null])]); - $redis->expects('connection')->twice()->andReturn($redisProxy); - - Queue::createPayloadUsing(function (string $connection, ?string $queue, array $payload): array { - return ['custom' => 'taylor']; - }); - - $id = $queue->push('foo', ['data']); - $this->assertSame('foo', $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - Queue::createPayloadUsing(null); - } - public function testJobQueueingAndQueuedEventsAreSkippedWhenNoListenersAreRegistered(): void { $now = CarbonImmutable::now(); CarbonImmutable::setTestNow($now); $uuid = $this->mockUuid(); - $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock(Redis::class), 'default', 'default'])->getMock(); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default'])->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); - $queue->setContainer($container = m::mock(Container::class)->makePartial()); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $queue->setContainer($container->instance()); $queue->setConnectionName('default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(false); + $redisProxy = Double::for(QueueRedisProxy::class); + $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')->twice()->andReturn($redisProxy); + $redis->expects('connection')->times(2)->returns($redisProxy); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(JobPayloadFinalizing::class)->andReturn(false); - $events->expects('hasListeners')->with(JobQueueing::class)->andReturn(false); - $events->expects('hasListeners')->with(JobQueued::class)->andReturn(false); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(JobPayloadFinalizing::class)->returns(false); + $events->expects('hasListeners')->with(JobQueueing::class)->returns(false); + $events->expects('hasListeners')->with(JobQueued::class)->returns(false); + $events->expects('dispatch')->never(); - $container->expects('bound')->with('events')->andReturn(true)->times(3); - $container->expects('make')->with('events')->andReturn($events)->times(3); + $container->allows('bound')->with('queue.routes')->returns(false); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('bound')->with('events')->returns(true)->times(3); + $container->expects('make')->with('events')->returns($events)->times(3); $id = $queue->push('foo', ['data']); $this->assertSame('foo', $id); @@ -468,7 +419,7 @@ public function testFinalPayloadListenerMutatesTheBrokerAndTerminalPayload(): vo $uuid = $this->mockUuid(); $queue = $this->getMockBuilder(RedisQueue::class) ->onlyMethods(['getRandomId']) - ->setConstructorArgs([$redis = m::mock(Redis::class), 'default', 'default']) + ->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default']) ->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('job-id'); $dispatcher = new EventDispatcher($container = new Container); @@ -490,15 +441,14 @@ public function testFinalPayloadListenerMutatesTheBrokerAndTerminalPayload(): vo $events[] = $event; }); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturnFalse(); - $redisProxy->expects('evalWithShaCache')->withArgs( + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(false); + $redisProxy->expects('evalWithShaCache')->with(Argument::all( static fn (string $script, array $keys, array $arguments): bool => $script === LuaScripts::push() && $keys === ['queues:default', 'queues:default:notify'] && json_decode($arguments[0], true)['telemetry'] === 'final', - ); - $redis->expects('connection')->twice()->andReturn($redisProxy); + )); + $redis->expects('connection')->times(2)->returns($redisProxy); $this->assertSame('job-id', $queue->push('foo', ['data'])); $this->assertSame([ @@ -516,7 +466,7 @@ public function testFinalPayloadListenerFailureRaisesFailureBeforeQueueingAndBro $exception = new RuntimeException('Unable to finalize payload.'); $queue = $this->getMockBuilder(RedisQueue::class) ->onlyMethods(['getRandomId']) - ->setConstructorArgs([$redis = m::mock(Redis::class), 'default', 'default']) + ->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default']) ->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('job-id'); $dispatcher = new EventDispatcher($container = new Container); @@ -534,7 +484,7 @@ public function testFinalPayloadListenerFailureRaisesFailureBeforeQueueingAndBro $dispatcher->listen(JobQueueingFailed::class, static function (JobQueueingFailed $event) use (&$failure): void { $failure = $event; }); - $redis->shouldNotReceive('connection'); + $redis->expects('connection')->never(); $caught = null; @@ -556,139 +506,104 @@ public function testPushRaisesFailedEventWhenRedisThrows(): void $uuid = $this->mockUuid(); $exception = new RuntimeException('Redis unavailable.'); - $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock(Redis::class), 'default', 'default'])->getMock(); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default'])->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); - $queue->setContainer($container = m::mock(Container::class)->makePartial()); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $queue->setContainer($container->instance()); $queue->setConnectionName('default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturnFalse(); - $redisProxy->expects('evalWithShaCache')->andThrow($exception); - $redis->expects('connection')->twice()->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(false); + $redisProxy->expects('evalWithShaCache')->throws($exception); + $redis->expects('connection')->times(2)->returns($redisProxy); - $events = m::mock(Dispatcher::class); - $events->expects('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse(); - $events->expects('hasListeners')->with(JobQueueing::class)->andReturnTrue(); - $events->expects('hasListeners')->with(JobQueueingFailed::class)->andReturnTrue(); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(JobPayloadFinalizing::class)->returns(false); + $events->expects('hasListeners')->with(JobQueueing::class)->returns(true); + $events->expects('hasListeners')->with(JobQueueingFailed::class)->returns(true); $events->expects('dispatch') - ->withArgs(function (JobQueueing $event) use ($uuid, $now): bool { + ->with(Argument::type(JobQueueing::class)) + ->resolves(function (JobQueueing $event) use ($uuid, $now): void { $this->assertSame('foo', $event->job); $this->assertSame('default', $event->connectionName); $this->assertNull($event->queue); $this->assertSame(['uuid' => (string) $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], $event->payload()); - - return true; }) ->ordered(); $events->expects('dispatch') - ->withArgs(function (JobQueueingFailed $event) use ($exception): bool { + ->with(Argument::type(JobQueueingFailed::class)) + ->resolves(function (JobQueueingFailed $event) use ($exception): void { $this->assertSame('foo', $event->job); $this->assertSame('default', $event->connectionName); $this->assertNull($event->queue); $this->assertNull($event->delay); $this->assertSame($exception, $event->exception); $this->assertTrue($event->sendAttempted); - - return true; }) ->ordered(); - $container->expects('bound')->with('events')->andReturnTrue()->times(3); - $container->expects('make')->with('events')->andReturn($events)->times(3); + $container->allows('bound')->with('queue.routes')->returns(false); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('bound')->with('events')->returns(true)->times(3); + $container->expects('make')->with('events')->returns($events)->times(3); $this->expectExceptionObject($exception); $queue->push('foo', ['data']); } - public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook(): void - { - $now = CarbonImmutable::now(); - CarbonImmutable::setTestNow($now); - $uuid = $this->mockUuid(); - - $redis = m::mock(Redis::class); - $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis, 'default', 'default'])->getMock(); - $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); - $container = m::spy(Container::class)->makePartial(); - $queue->setContainer($container); - $queue->setConnectionName('default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(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(), 'custom' => 'taylor', 'bar' => 'foo', 'id' => 'foo', 'attempts' => 0, 'delay' => null])]); - $redis->expects('connection')->twice()->andReturn($redisProxy); - - Queue::createPayloadUsing(function (string $connection, ?string $queue, array $payload): array { - return ['custom' => 'taylor']; - }); - - Queue::createPayloadUsing(function (string $connection, ?string $queue, array $payload): array { - return ['bar' => 'foo']; - }); - - $id = $queue->push('foo', ['data']); - $this->assertSame('foo', $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - Queue::createPayloadUsing(null); - } - - public function testDelayedPushProperlyPushesJobOntoRedis(): void + public function testDelayedPushRoundsUpFractionalDeadlines(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); $now = CarbonImmutable::now(); $uuid = $this->mockUuid(); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis, 'default', 'default'])->getMock(); - $container = m::spy(Container::class)->makePartial(); - $queue->setContainer($container); + $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 = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(false); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(false); $redisProxy->expects('evalWithShaCache')->with( LuaScripts::later(), ['queues:default:delayed'], [1002, 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' => 1])] ); - $redis->expects('connection')->twice()->andReturn($redisProxy); + $redis->expects('connection')->times(2)->returns($redisProxy); $id = $queue->later(1, 'foo', ['data']); $this->assertSame('foo', $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } - public function testDelayedPushWithDateTimeProperlyPushesJobOntoRedis(): void + public function testDelayedDateTimePushRoundsUpFractionalDeadlines(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); $now = CarbonImmutable::now(); $uuid = $this->mockUuid(); $date = CarbonImmutable::createFromTimestampUTC('1001.100000'); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis, 'default', 'default'])->getMock(); - $container = m::spy(Container::class)->makePartial(); - $queue->setContainer($container); + $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 = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(false); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(false); $redisProxy->expects('evalWithShaCache')->with( LuaScripts::later(), ['queues:default:delayed'], [1002, 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' => 1])] ); - $redis->expects('connection')->twice()->andReturn($redisProxy); + $redis->expects('connection')->times(2)->returns($redisProxy); $queue->later($date, 'foo', ['data']); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testDelayedPushWithIntervalNeverRunsBeforeRequestedLifetime(): void @@ -698,28 +613,28 @@ public function testDelayedPushWithIntervalNeverRunsBeforeRequestedLifetime(): v $uuid = $this->mockUuid(); $delay = new DateInterval('PT1S'); - $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock(Redis::class), 'default', 'default'])->getMock(); - $queue->setContainer($container = m::spy(Container::class)->makePartial()); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = Double::for(Redis::class), '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 = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(false); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(false); $redisProxy->expects('evalWithShaCache')->with( LuaScripts::later(), ['queues:default:delayed'], [1002, 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' => 1])] ); - $redis->expects('connection')->twice()->andReturn($redisProxy); + $redis->expects('connection')->times(2)->returns($redisProxy); $queue->later($delay, 'foo', ['data']); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testGetQueueRemainsUnchangedForNonCluster(): void { - $queue = new RedisQueue(m::mock(Redis::class), 'default', 'default'); + $queue = new RedisQueue(Double::for(Redis::class), 'default', 'default'); $this->assertSame('queues:default', $queue->getQueue(null)); $this->assertSame('queues:default', $queue->getQueue('')); @@ -732,9 +647,9 @@ public function testGetQueueRemainsUnchangedForNonCluster(): void public function testGetQueueRemainsUnchangedForCluster(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new RedisQueue($redis, 'default', 'default'); - $redis->shouldNotReceive('connection'); + $redis->expects('connection')->never(); // getQueue() does not add hash tags. $this->assertSame('queues:default', $queue->getQueue(null)); @@ -745,11 +660,11 @@ public function testGetQueueRemainsUnchangedForCluster(): void public function testGetRedisKeyReturnsPlainKeyForNonCluster(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new TestableRedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(false); - $redis->expects('connection')->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(false); + $redis->expects('connection')->returns($redisProxy); $this->assertSame('queues:default', $queue->testGetQueueRedisKey(null)); $this->assertSame('queues:default', $queue->testGetQueueRedisKey('')); @@ -759,11 +674,11 @@ public function testGetRedisKeyReturnsPlainKeyForNonCluster(): void public function testGetRedisKeyWrapsWithHashTagsForPhpRedisCluster(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new TestableRedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); - $redis->expects('connection')->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redis->expects('connection')->returns($redisProxy); $this->assertSame('queues:{default}', $queue->testGetQueueRedisKey(null)); $this->assertSame('queues:{default}', $queue->testGetQueueRedisKey('')); @@ -775,11 +690,11 @@ public function testGetRedisKeyWrapsWithHashTagsForPhpRedisCluster(): void public function testGetRedisKeyDoesNotDoubleWrapExistingHashTags(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new TestableRedisQueue($redis, '{default}', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); - $redis->expects('connection')->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redis->expects('connection')->returns($redisProxy); $this->assertSame('queues:{default}', $queue->testGetQueueRedisKey(null)); $this->assertSame('queues:{custom}', $queue->testGetQueueRedisKey('{custom}')); @@ -787,11 +702,11 @@ public function testGetRedisKeyDoesNotDoubleWrapExistingHashTags(): void public function testGetRedisKeySkipsWrappingWhenQueueNameContainsBraces(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new TestableRedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); - $redis->expects('connection')->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redis->expects('connection')->returns($redisProxy); // Queue name already contains hash tags — skip wrapping. $this->assertSame('queues:process-{batch}-results', $queue->testGetQueueRedisKey('process-{batch}-results')); @@ -799,11 +714,11 @@ public function testGetRedisKeySkipsWrappingWhenQueueNameContainsBraces(): void public function testGetRedisKeyWrapsEmptyHashTagOnCluster(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new TestableRedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); - $redis->expects('connection')->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redis->expects('connection')->returns($redisProxy); // Empty braces '{}' are not a valid hash tag — still wrap the name. $this->assertSame('queues:{my{}queue}', $queue->testGetQueueRedisKey('my{}queue')); @@ -811,11 +726,11 @@ public function testGetRedisKeyWrapsEmptyHashTagOnCluster(): void public function testGetRedisKeyWrapsUnmatchedOpeningBrace(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new TestableRedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); - $redis->expects('connection')->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redis->expects('connection')->returns($redisProxy); // An unmatched '{' is not a valid hash tag — still wrap the name. $this->assertSame('queues:{my{broken}', $queue->testGetQueueRedisKey('my{broken')); @@ -823,11 +738,11 @@ public function testGetRedisKeyWrapsUnmatchedOpeningBrace(): void public function testGetRedisKeyWrapsUnmatchedClosingBrace(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new TestableRedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); - $redis->expects('connection')->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redis->expects('connection')->returns($redisProxy); // An unmatched '}' is not a valid hash tag — still wrap the name. $this->assertSame('queues:{broken}queue}', $queue->testGetQueueRedisKey('broken}queue')); @@ -835,11 +750,11 @@ public function testGetRedisKeyWrapsUnmatchedClosingBrace(): void public function testGetRedisKeyWrapsEmptyFirstHashTagFollowedByValidPair(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new TestableRedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); - $redis->expects('connection')->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redis->expects('connection')->returns($redisProxy); // Redis hashes the whole key when the first '{}' is empty, even if a // later pair is valid. Wrap the name to keep related keys in one slot. @@ -852,28 +767,27 @@ public function testPushUsesGetRedisKeyForLuaScript(): void CarbonImmutable::setTestNow($now); $uuid = $this->mockUuid(); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = $this->getMockBuilder(RedisQueue::class) ->onlyMethods(['getRandomId']) ->setConstructorArgs([$redis, 'default', 'default']) ->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); - $container = m::spy(Container::class)->makePartial(); - $queue->setContainer($container); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $queue->setContainer($container->instance()); $queue->setConnectionName('default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(true); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); $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')->twice()->andReturn($redisProxy); + $redis->expects('connection')->times(2)->returns($redisProxy); $this->assertSame('foo', $queue->push('foo', ['data'])); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testPushPassesUnchangedQueueToCreatePayload(): void @@ -882,7 +796,7 @@ public function testPushPassesUnchangedQueueToCreatePayload(): void CarbonImmutable::setTestNow($now); $this->mockUuid(); - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = $this->getMockBuilder(RedisQueue::class) ->onlyMethods(['getRandomId']) ->setConstructorArgs([$redis, 'default', 'default']) @@ -891,11 +805,10 @@ public function testPushPassesUnchangedQueueToCreatePayload(): void $queue->setContainer(new Container); $queue->setConnectionName('default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(true); - $redisProxy->expects('evalWithShaCache')->andReturn(null); - $redis->expects('connection')->twice()->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redisProxy->expects('evalWithShaCache')->returns(null); + $redis->expects('connection')->times(2)->returns($redisProxy); $receivedQueue = null; @@ -922,41 +835,41 @@ public function testLaterUsesClusterSafeRedisKeyForDelayedSet(): void $queue = $this->getMockBuilder(RedisQueue::class) ->onlyMethods(['availableAt', 'getRandomId']) - ->setConstructorArgs([$redis = m::mock(Redis::class), 'default', 'default']) + ->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default']) ->getMock(); - $queue->setContainer($container = m::spy(Container::class)->makePartial()); + $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'); $queue->expects($this->once())->method('availableAt')->with(1)->willReturn(2); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldAllowMockingMethod('evalWithShaCache'); - $redisProxy->expects('isCluster')->andReturn(true); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); $redisProxy->expects('evalWithShaCache')->with( LuaScripts::later(), ['queues:{default}:delayed'], [2, 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' => 1])] ); - $redis->expects('connection')->twice()->andReturn($redisProxy); + $redis->expects('connection')->times(2)->returns($redisProxy); $this->assertSame('foo', $queue->later(1, 'foo', ['data'])); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testSizeUsesGetRedisKeyOnCluster(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new RedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); $redisProxy->expects('eval')->with( LuaScripts::size(), 3, 'queues:{default}', 'queues:{default}:delayed', 'queues:{default}:reserved' - )->andReturn(5); - $redis->expects('connection')->twice()->andReturn($redisProxy); + )->returns(5); + $redis->expects('connection')->times(2)->returns($redisProxy); $this->assertSame(5, $queue->size()); } @@ -965,28 +878,28 @@ public function testPopUsesClusterSafeRedisKeys(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); - $queue = new RedisQueue($redis = m::mock(Redis::class), 'default', 'default'); + $queue = new RedisQueue($redis = Double::for(Redis::class), 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); $redisProxy->expects('eval')->with( LuaScripts::migrateExpiredJobs(), 3, 'queues:{default}:delayed', 'queues:{default}', 'queues:{default}:notify', - m::type('int'), + Argument::type('int'), -1 - )->andReturn([]); + )->returns([]); $redisProxy->expects('eval')->with( LuaScripts::migrateExpiredJobs(), 3, 'queues:{default}:reserved', 'queues:{default}', 'queues:{default}:notify', - m::type('int'), + Argument::type('int'), -1 - )->andReturn([]); + )->returns([]); $redisProxy->expects('eval')->with( LuaScripts::pop(), 3, @@ -994,8 +907,8 @@ public function testPopUsesClusterSafeRedisKeys(): void 'queues:{default}:reserved', 'queues:{default}:notify', 1061 - )->andReturn([]); - $redis->expects('connection')->times(4)->andReturn($redisProxy); + )->returns([]); + $redis->expects('connection')->times(4)->returns($redisProxy); $this->assertNull($queue->pop()); } @@ -1012,7 +925,7 @@ public function testPoppedJobPreservesZeroQueueAndDefaultsEmptyQueue(): void foreach ([['0', '0'], ['', 'default']] as [$requested, $expected]) { $queue = $this->getMockBuilder(RedisQueue::class) ->onlyMethods(['getQueueRedisKey', 'migrate', 'retrieveNextJob']) - ->setConstructorArgs([m::mock(Redis::class), 'default', 'default']) + ->setConstructorArgs([Double::for(Redis::class), 'default', 'default']) ->getMock(); $queue->setContainer(new Container); $queue->setConnectionName('redis'); @@ -1031,7 +944,7 @@ public function testPoppedRawZeroIsNotMistakenForAnEmptyQueue(): void { $queue = $this->getMockBuilder(RedisQueue::class) ->onlyMethods(['getQueueRedisKey', 'migrate', 'retrieveNextJob']) - ->setConstructorArgs([m::mock(Redis::class), 'default', 'default']) + ->setConstructorArgs([Double::for(Redis::class), 'default', 'default']) ->getMock(); $queue->setContainer(new Container); $queue->setConnectionName('redis'); @@ -1048,14 +961,14 @@ public function testPoppedRawZeroIsNotMistakenForAnEmptyQueue(): void public function testDeleteReservedUsesClusterSafeRedisKey(): void { - $queue = new RedisQueue($redis = m::mock(Redis::class), 'default', 'default'); - $job = m::mock(RedisJob::class); - $job->expects('getReservedJob')->andReturn('reserved-payload'); + $queue = new RedisQueue($redis = Double::for(Redis::class), 'default', 'default'); + $job = Double::for(RedisJob::class); + $job->expects('getReservedJob')->returns('reserved-payload'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); - $redisProxy->expects('zrem')->with('queues:{emails}:reserved', 'reserved-payload')->andReturn(1); - $redis->expects('connection')->twice()->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redisProxy->expects('zrem')->with('queues:{emails}:reserved', 'reserved-payload')->returns(1); + $redis->expects('connection')->times(2)->returns($redisProxy); $queue->deleteReserved('emails', $job); } @@ -1064,13 +977,13 @@ public function testDeleteAndReleaseUsesClusterSafeRedisKeys(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); - $queue = new RedisQueue($redis = m::mock(Redis::class), 'default', 'default'); + $queue = new RedisQueue($redis = Double::for(Redis::class), 'default', 'default'); - $job = m::mock(RedisJob::class); - $job->expects('getReservedJob')->andReturn('reserved-payload'); + $job = Double::for(RedisJob::class); + $job->expects('getReservedJob')->returns('reserved-payload'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); $redisProxy->expects('eval')->with( LuaScripts::release(), 2, @@ -1079,17 +992,17 @@ public function testDeleteAndReleaseUsesClusterSafeRedisKeys(): void 'reserved-payload', 1031 ); - $redis->expects('connection')->twice()->andReturn($redisProxy); + $redis->expects('connection')->times(2)->returns($redisProxy); $queue->deleteAndRelease('emails', $job, 30); } public function testClearUsesGetRedisKeyOnCluster(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new RedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); $redisProxy->expects('eval')->with( LuaScripts::clear(), 4, @@ -1097,19 +1010,19 @@ public function testClearUsesGetRedisKeyOnCluster(): void 'queues:{default}:delayed', 'queues:{default}:reserved', 'queues:{default}:notify' - )->andReturn(3); - $redis->expects('connection')->twice()->andReturn($redisProxy); + )->returns(3); + $redis->expects('connection')->times(2)->returns($redisProxy); $this->assertSame(3, $queue->clear('default')); } public function testIsClusterConnectionCachesResult(): void { - $redis = m::mock(Redis::class); + $redis = Double::for(Redis::class); $queue = new TestableRedisQueue($redis, 'default', 'default'); - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->expects('isCluster')->andReturn(true); - $redis->expects('connection')->andReturn($redisProxy); + $redisProxy = Double::for(QueueRedisProxy::class); + $redisProxy->expects('isCluster')->returns(true); + $redis->expects('connection')->returns($redisProxy); $this->assertTrue($queue->testIsClusterConnection()); $this->assertTrue($queue->testIsClusterConnection()); @@ -1118,39 +1031,22 @@ public function testIsClusterConnectionCachesResult(): void public function testSizeResolvesTheQueueNameFromAnEnum(): void { - $redis = m::mock(Redis::class); - $connection = m::mock(RedisProxy::class); - $redis->expects('connection')->twice()->with(null)->andReturn($connection); - $connection->expects('isCluster')->andReturnFalse(); + $redis = Double::for(Redis::class); + $connection = Double::for(QueueRedisProxy::class); + $redis->expects('connection')->times(2)->with(null)->returns($connection); + $connection->expects('isCluster')->returns(false); $connection->expects('eval')->with( LuaScripts::size(), 3, 'queues:emails', 'queues:emails:delayed', 'queues:emails:reserved' - )->andReturn(5); + )->returns(5); $queue = new RedisQueue($redis, 'default'); $this->assertSame(5, $queue->size(RedisQueueName::Emails)); } - public function testPendingJobsResolvesTheQueueNameFromAnEnum(): void - { - $redis = m::mock(Redis::class); - $proxy = m::mock(RedisProxy::class); - $connection = m::mock(RedisConnection::class); - $redis->expects('connection')->with(null)->andReturn($proxy); - $proxy->expects('withConnection')->with(m::type('Closure'), false) - ->andReturnUsing(static fn (callable $callback): Collection => $callback($connection)); - $connection->expects('isCluster')->andReturnFalse(); - $connection->expects('lrange')->with('queues:emails', 0, -1)->andReturn([ - json_encode(['uuid' => 'uuid', 'displayName' => 'foo', 'job' => 'foo', 'data' => []]), - ]); - $queue = new RedisQueue($redis, 'default'); - - $this->assertSame('emails', $queue->pendingJobs(RedisQueueName::Emails)->first()->queue); - } - /** * Fix the UUID used by queue payloads. */ @@ -1162,17 +1058,6 @@ protected function mockUuid(): Uuid return $uuid; } - - /** - * Create a Redis proxy mock with script caching support. - */ - private function mockRedisProxyWithShaCache(): RedisProxy - { - $connection = m::mock(RedisProxy::class); - $connection->shouldAllowMockingMethod('evalWithShaCache'); - - return $connection; - } } enum RedisQueueName: string @@ -1216,3 +1101,34 @@ class RedisBulkOwnedJob class RedisBulkAfterCommitJob implements ShouldQueueAfterCommit { } + +/** + * Declare the dynamic Redis commands exercised by the queue tests for native doubles. + */ +abstract class QueueRedisProxy extends RedisProxy +{ + /** + * Execute a cached Lua script. + */ + abstract public function evalWithShaCache(string $script, array $keys = [], array $arguments = []): mixed; + + /** + * Execute a Lua script with separate keys and arguments. + */ + abstract public function eval(string $script, int $numberOfKeys, mixed ...$arguments): mixed; + + /** + * Get the number of list members. + */ + abstract public function llen(string $key): int; + + /** + * Get the number of sorted-set members. + */ + abstract public function zcard(string $key): int; + + /** + * Remove a sorted-set member. + */ + abstract public function zrem(string $key, string $member): int; +} diff --git a/tests/Queue/QueueSqsJobTest.php b/tests/Queue/QueueSqsJobTest.php index 4a2385519..dcb4afc3f 100644 --- a/tests/Queue/QueueSqsJobTest.php +++ b/tests/Queue/QueueSqsJobTest.php @@ -4,6 +4,8 @@ namespace Hypervel\Tests\Queue; +use Aws\MockHandler; +use Aws\Result; use Aws\Sqs\SqsClient; use Closure; use Exception; @@ -17,7 +19,9 @@ use Hypervel\ObjectPool\PoolOptions; use Hypervel\Queue\Jobs\SqsJob; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -27,6 +31,8 @@ class QueueSqsJobTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $pools = []; @@ -50,6 +56,8 @@ class QueueSqsJobTest extends TestCase protected SqsClient $mockedSqsClient; + protected MockHandler $handler; + protected Container $mockedContainer; protected string $mockedJob; @@ -83,11 +91,16 @@ protected function setUp(): void // This is how the modified getQueue builds the queueUrl $this->queueUrl = $this->baseUrl . '/' . $this->account . '/' . $this->queueName; - // Get a mock of the SqsClient - $this->mockedSqsClient = m::mock(SqsClient::class)->makePartial(); + // A real SqsClient that never leaves the process. + $this->handler = new MockHandler; + $this->mockedSqsClient = new SqsClient([ + 'region' => $this->region, + 'version' => 'latest', + 'credentials' => ['key' => $this->key, 'secret' => $this->secret], + 'handler' => $this->handler, + ]); - // Use Mockery to mock the IoC Container - $this->mockedContainer = m::mock(Container::class); + $this->mockedContainer = new Application; $this->mockedJob = 'foo'; $this->mockedData = ['data']; @@ -112,32 +125,46 @@ protected function tearDownInCoroutine(): void foreach ($this->pools as $pool) { $pool->close(); } + + $this->assertCount(0, $this->handler); } public function testFireProperlyCallsTheJobHandler(): void { $job = $this->getJob(); - $handler = m::mock(stdClass::class); - $job->getContainer()->expects('make')->with('foo')->andReturn($handler); - $handler->expects('fire')->with($job, ['data']); + $handler = new SqsJobTestHandler; + $job->getContainer()->instance('foo', $handler); $job->fire(); + + $this->assertSame([[$job, ['data']]], $handler->fired); } public function testDeleteRemovesTheJobFromSqs(): void { - $this->mockedSqsClient = m::mock(SqsClient::class)->makePartial(); + $this->handler->append(new Result([])); $job = $this->getJob(); - $job->getSqs()->expects('deleteMessage')->with(['QueueUrl' => $this->queueUrl, 'ReceiptHandle' => $this->mockedReceiptHandle]); $job->delete(); + + $this->assertSame('DeleteMessage', $this->handler->getLastCommand()->getName()); + $this->assertSame([ + 'QueueUrl' => $this->queueUrl, + 'ReceiptHandle' => $this->mockedReceiptHandle, + ], json_decode((string) $this->handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR)); } public function testReleaseProperlyReleasesTheJobOntoSqs(): void { - $this->mockedSqsClient = m::mock(SqsClient::class)->makePartial(); + $this->handler->append(new Result([])); $job = $this->getJob(); - $job->getSqs()->expects('changeMessageVisibility')->with(['QueueUrl' => $this->queueUrl, 'ReceiptHandle' => $this->mockedReceiptHandle, 'VisibilityTimeout' => $this->releaseDelay]); $job->release($this->releaseDelay); $this->assertTrue($job->isReleased()); + + $this->assertSame('ChangeMessageVisibility', $this->handler->getLastCommand()->getName()); + $this->assertSame([ + 'QueueUrl' => $this->queueUrl, + 'ReceiptHandle' => $this->mockedReceiptHandle, + 'VisibilityTimeout' => $this->releaseDelay, + ], json_decode((string) $this->handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR)); } public function testGetRawBodyResolvesPointerFromCache(): void @@ -146,17 +173,17 @@ public function testGetRawBodyResolvesPointerFromCache(): void $pointer = 'laravel:sqs-payloads:some-uuid'; $pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('get')->with($pointer)->andReturn($payload); + $store = Double::for(CacheRepository::class); + $store->expects('get')->with($pointer)->returns($payload); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true); + $container->expects('make')->with('cache')->returns($cache); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -180,17 +207,17 @@ public function testGetRawBodyCachesOriginalPointerWhenOverflowPayloadIsUnavaila $pointer = 'laravel:sqs-payloads:missing'; $pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('get')->with($pointer)->andReturn($payload); + $store = Double::for(CacheRepository::class); + $store->expects('get')->with($pointer)->returns($payload); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true); + $container->expects('make')->with('cache')->returns($cache); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -221,11 +248,11 @@ public function testGetRawBodyReturnsPointerBodyWhenExtendedStoreIsDisabled(): v '@pointer' => 'laravel:sqs-payloads:disabled', ], JSON_THROW_ON_ERROR); - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); + $container = Double::for(Container::class, override: true); + $container->expects('make')->never(); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -241,17 +268,17 @@ public function testGetRawBodyCachesResult(): void $pointer = 'laravel:sqs-payloads:some-uuid'; $pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('get')->with($pointer)->andReturn($payload); + $store = Double::for(CacheRepository::class); + $store->expects('get')->with($pointer)->returns($payload); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true); + $container->expects('make')->with('cache')->returns($cache); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -268,31 +295,26 @@ public function testDeleteCleansUpCacheKeyWhenCleanupEnabled(): void { $pointer = 'laravel:sqs-payloads:delete'; $pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR); - $deletedFromSqs = false; - $store = m::mock(CacheRepository::class); - $store->expects('forget')->with($pointer)->andReturnUsing( - function () use (&$deletedFromSqs): bool { - $this->assertTrue($deletedFromSqs); + $store = Double::for(CacheRepository::class); + $store->expects('forget')->with($pointer)->resolves( + function (): bool { + $this->assertSame('DeleteMessage', $this->handler->getLastCommand()->getName()); return true; } ); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true); + $container->expects('make')->with('cache')->returns($cache); - $this->mockedSqsClient->expects('deleteMessage')->andReturnUsing( - function () use (&$deletedFromSqs): void { - $deletedFromSqs = true; - } - ); + $this->handler->append(new Result([])); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -309,12 +331,12 @@ public function testDeleteDoesNotCleanUpWhenCleanupDisabled(): void '@pointer' => 'laravel:sqs-payloads:retained', ], JSON_THROW_ON_ERROR); - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); - $this->mockedSqsClient->expects('deleteMessage'); + $container = Double::for(Container::class, override: true); + $container->expects('make')->never(); + $this->handler->append(new Result([])); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -327,15 +349,12 @@ public function testDeleteDoesNotCleanUpWhenCleanupDisabled(): void public function testDeleteDoesNotCleanUpWhenNoPointer(): void { - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); - $this->mockedSqsClient->expects('deleteMessage')->with([ - 'QueueUrl' => $this->queueUrl, - 'ReceiptHandle' => $this->mockedReceiptHandle, - ]); + $container = Double::for(Container::class, override: true); + $container->expects('make')->never(); + $this->handler->append(new Result([])); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, $this->mockedJobData, 'connection-name', @@ -344,6 +363,11 @@ public function testDeleteDoesNotCleanUpWhenNoPointer(): void ); $job->delete(); + + $this->assertSame([ + 'QueueUrl' => $this->queueUrl, + 'ReceiptHandle' => $this->mockedReceiptHandle, + ], json_decode((string) $this->handler->getLastRequest()->getBody(), true, flags: JSON_THROW_ON_ERROR)); } public function testReleaseNeverCleansOverflowPayload(): void @@ -352,12 +376,12 @@ public function testReleaseNeverCleansOverflowPayload(): void '@pointer' => 'laravel:sqs-payloads:released', ], JSON_THROW_ON_ERROR); - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); - $this->mockedSqsClient->expects('changeMessageVisibility'); + $container = Double::for(Container::class, override: true); + $container->expects('make')->never(); + $this->handler->append(new Result([])); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -375,13 +399,13 @@ public function testDeleteRetainsOverflowPayloadWhenSqsDeletionFails(): void '@pointer' => 'laravel:sqs-payloads:retained', ], JSON_THROW_ON_ERROR); - $container = m::mock(Container::class); - $container->shouldNotReceive('make'); + $container = Double::for(Container::class, override: true); + $container->expects('make')->never(); $expected = new Exception('delete failed'); - $this->mockedSqsClient->expects('deleteMessage')->andThrow($expected); + $this->handler->append($expected); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -408,18 +432,18 @@ public function testDeleteCleansOverflowPayloadAfterLeaseReleaseFails(): void $pointer = 'laravel:sqs-payloads:cleanup'; $pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('forget')->with($pointer)->andReturnTrue(); + $store = Double::for(CacheRepository::class); + $store->expects('forget')->with($pointer)->returns(true); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class); - $container->expects('make')->with('cache')->andReturn($cache); - $this->mockedSqsClient->expects('deleteMessage'); + $container = Double::for(Container::class, override: true); + $container->expects('make')->with('cache')->returns($cache); + $this->handler->append(new Result([])); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -448,14 +472,14 @@ public function testDeleteDoesNotStartOverflowCleanupAfterLeaseReleaseCancellati ); $pointer = 'laravel:sqs-payloads:cleanup'; $pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR); - $store = m::spy(CacheRepository::class); - $cache = m::mock(CacheFactory::class); - $cache->allows('store')->andReturn($store); - $container = m::mock(Container::class); - $container->allows('make')->andReturn($cache); - $this->mockedSqsClient->expects('deleteMessage'); + $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); + $this->handler->append(new Result([])); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -470,7 +494,7 @@ public function testDeleteDoesNotStartOverflowCleanupAfterLeaseReleaseCancellati $this->assertSame($releaseCancellation, $exception); } - $store->shouldNotHaveReceived('forget'); + $store->received('forget')->never(); } public function testDeleteSurfacesOverflowCleanupFailureAfterSuccessfulDeletion(): void @@ -478,18 +502,18 @@ public function testDeleteSurfacesOverflowCleanupFailureAfterSuccessfulDeletion( $pointer = 'laravel:sqs-payloads:cleanup'; $pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('forget')->with($pointer)->andReturnFalse(); + $store = Double::for(CacheRepository::class); + $store->expects('forget')->with($pointer)->returns(false); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class); - $container->expects('make')->with('cache')->andReturn($cache); - $this->mockedSqsClient->expects('deleteMessage'); + $container = Double::for(Container::class, override: true); + $container->expects('make')->with('cache')->returns($cache); + $this->handler->append(new Result([])); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -513,31 +537,31 @@ public function testDeleteReportsCleanupFailureWithoutReplacingLeaseReleaseFailu $pointer = 'laravel:sqs-payloads:cleanup'; $pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('forget')->with($pointer)->andReturnFalse(); + $store = Double::for(CacheRepository::class); + $store->expects('forget')->with($pointer)->returns(false); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class); - $container->expects('make')->with('cache')->andReturn($cache); - $this->mockedSqsClient->expects('deleteMessage'); + $container = Double::for(Container::class, override: true); + $container->expects('make')->with('cache')->returns($cache); + $this->handler->append(new Result([])); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->withArgs( + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with(Argument::satisfies( function (Throwable $exception) use (&$cleanupFailure): bool { $cleanupFailure = $exception; return true; } - ); + )); $application = new Application; $application->instance(ExceptionHandler::class, $handler); Application::setInstance($application); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -570,15 +594,15 @@ public function testOverflowCleanupCancellationSupersedesAnOrdinaryLeaseReleaseF ); $pointer = 'laravel:sqs-payloads:cleanup'; $pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('forget')->with($pointer)->andThrow($cleanupCancellation); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); - $container = m::mock(Container::class); - $container->expects('make')->with('cache')->andReturn($cache); - $this->mockedSqsClient->expects('deleteMessage'); + $store = Double::for(CacheRepository::class); + $store->expects('forget')->with($pointer)->throws($cleanupCancellation); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); + $container = Double::for(Container::class, override: true); + $container->expects('make')->with('cache')->returns($cache); + $this->handler->append(new Result([])); $job = new SqsJob( - $container, + $container->instance(), $this->mockedSqsClient, [...$this->mockedJobData, 'Body' => $pointerBody], 'connection-name', @@ -598,10 +622,11 @@ public function testDeleteReleasesPoolLeaseAfterBackendCall(): void { [$pool, $lease] = $this->lease(); $job = $this->getJob(); - $job->getSqs()->expects('deleteMessage') - ->andReturnUsing(function () use ($pool): void { - $this->assertSame(1, $pool->getBorrowedCount()); - }); + $this->handler->append(function () use ($pool): Result { + $this->assertSame(1, $pool->getBorrowedCount()); + + return new Result([]); + }); $job->withPoolLease($lease)->delete(); @@ -613,10 +638,11 @@ public function testReleaseReleasesPoolLeaseAfterBackendCall(): void { [$pool, $lease] = $this->lease(); $job = $this->getJob(); - $job->getSqs()->expects('changeMessageVisibility') - ->andReturnUsing(function () use ($pool): void { - $this->assertSame(1, $pool->getBorrowedCount()); - }); + $this->handler->append(function () use ($pool): Result { + $this->assertSame(1, $pool->getBorrowedCount()); + + return new Result([]); + }); $job->withPoolLease($lease)->release(5); @@ -632,7 +658,7 @@ public function testBackendFailureDiscardsPoolLeaseAndPreservesTheException(): v }); $job = $this->getJob(); $expected = new Exception('delete failed'); - $job->getSqs()->expects('deleteMessage')->andThrow($expected); + $this->handler->append($expected); try { $job->withPoolLease($lease)->delete(); @@ -654,7 +680,7 @@ public function testDiscardCancellationSupersedesAnOrdinaryBackendFailure(): voi throw $discardCancellation; }); $job = $this->getJob(); - $job->getSqs()->expects('deleteMessage')->andThrow($backendFailure); + $this->handler->append($backendFailure); try { $job->withPoolLease($lease)->delete(); @@ -671,7 +697,7 @@ public function testBackendAccessIsRejectedAfterLeaseFinalization(): void { [$pool, $lease] = $this->lease(); $job = $this->getJob(); - $job->getSqs()->expects('deleteMessage'); + $this->handler->append(new Result([])); $job->withPoolLease($lease)->delete(); $this->assertSame(0, $pool->getBorrowedCount()); @@ -713,3 +739,16 @@ protected function getJob(): SqsJob ); } } + +class SqsJobTestHandler +{ + public array $fired = []; + + /** + * Record the job and its payload. + */ + public function fire(SqsJob $job, array $data): void + { + $this->fired[] = [$job, $data]; + } +} diff --git a/tests/Queue/QueueSqsQueueTest.php b/tests/Queue/QueueSqsQueueTest.php index fde844ce3..41cfeea5b 100644 --- a/tests/Queue/QueueSqsQueueTest.php +++ b/tests/Queue/QueueSqsQueueTest.php @@ -4,9 +4,12 @@ namespace Hypervel\Tests\Queue; +use Aws\CommandInterface; +use Aws\MockHandler; use Aws\Result; use Aws\Sqs\Exception\SqsException; use Aws\Sqs\SqsClient; +use Closure; use Hypervel\Bus\Dispatcher as BusDispatcher; use Hypervel\Bus\DispatchLockContext; use Hypervel\Cache\ArrayStore; @@ -42,9 +45,12 @@ use Hypervel\Tests\Queue\Fixtures\IntegerQueueName; use Hypervel\Tests\Queue\Fixtures\UnitQueueName; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use JMac\Testing\OverriddenDouble; use Laravel\SerializableClosure\SerializableClosure; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -54,6 +60,10 @@ class QueueSqsQueueTest extends TestCase { + use VerifiesDoubles; + + protected MockHandler $handler; + protected SqsClient $sqs; protected string $account; @@ -101,8 +111,14 @@ protected function setUp(): void { parent::setUp(); - // Use Mockery to mock the SqsClient - $this->sqs = m::mock(SqsClient::class); + // A real SqsClient whose requests never leave the process. + $this->handler = new MockHandler; + $this->sqs = new SqsClient([ + 'region' => 'someregion', + 'version' => 'latest', + 'credentials' => ['key' => 'AMAZONSQSKEY', 'secret' => 'AmAz0n+SqSsEcReT+aLpHaNuM3R1CsTr1nG'], + 'handler' => $this->handler, + ]); $this->account = '1234567891011'; $this->queueName = 'emails'; @@ -153,6 +169,70 @@ protected function setUp(): void ]); } + /** + * Queue the next expected SQS command and the response (or exception) to send back. + * + * @param null|array|callable $parameters The exact parameters, or a callback that returns true when they are right. + * An array value that is a closure is called with the actual value instead. + */ + protected function expectSqsCommand(string $name, array|callable|null $parameters = null, Result|Throwable|callable|null $result = null, int $times = 1): void + { + for ($i = 0; $i < $times; ++$i) { + $this->handler->append(function (CommandInterface $command) use ($name, $parameters, $result): Result|Throwable { + $this->assertSame(ucfirst($name), $command->getName()); + + $arguments = array_filter($command->toArray(), fn (string $key): bool => ! str_starts_with($key, '@'), ARRAY_FILTER_USE_KEY); + + if (is_array($parameters)) { + foreach ($parameters as $key => $expected) { + if ($expected instanceof Closure) { + $this->assertTrue($expected($arguments[$key] ?? null), "Unexpected [{$key}] for the [{$name}] command."); + unset($parameters[$key], $arguments[$key]); + } + } + + $this->assertEquals($parameters, $arguments); + } elseif (is_callable($parameters)) { + $this->assertNotFalse($parameters($arguments), "Unexpected parameters for the [{$name}] command."); + } + + if (is_callable($result)) { + $result = $result($arguments); + } + + return $result ?? new Result([]); + }); + } + } + + /** + * Get a callback that checks a message body is the payload SqsQueue creates for a job class or job string. + */ + protected function isPayloadOf(string $job): Closure + { + return function (string $body) use ($job): bool { + $payload = json_decode($body, true); + + return ($payload['displayName'] ?? null) === $job + && (class_exists($job) || $payload['data'] === $this->mockedData); + }; + } + + /** + * Reset fixture factories and verify that every expected request was sent. + */ + protected function tearDown(): void + { + FakeSqsJobWithMessageGroup::createMessageGroupsNormally(); + FakeSqsJobWithDeduplication::createDeduplicationIdsNormally(); + + try { + $this->assertCount(0, $this->handler, 'Not every expected SQS command was sent.'); + } finally { + parent::tearDown(); + } + } + /** * Create the UUID returned by the test resolver. */ @@ -164,72 +244,62 @@ protected function createMockedUuid(string $value): Uuid /** * Create a container spy with real service resolution. */ - protected function createSpyContainer(): Container + protected function createSpyContainer(): OverriddenDouble { - return m::spy(Container::class)->makePartial(); + return Double::for(Container::class, override: true)->passthru(new Container); } public function testPopProperlyPopsJobOffOfSqs(): void { - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer(new Container); $queue->setConnectionName('sqs'); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $this->sqs->expects('receiveMessage')->with(['QueueUrl' => $this->queueUrl, 'MessageSystemAttributeNames' => ['ApproximateReceiveCount']])->andReturn($this->mockedReceiveMessageResponseModel); + $this->expectSqsCommand('receiveMessage', ['QueueUrl' => $this->queueUrl, 'MessageSystemAttributeNames' => ['ApproximateReceiveCount']], $this->mockedReceiveMessageResponseModel); $result = $queue->pop($this->queueName); $this->assertInstanceOf(SqsJob::class, $result); } public function testPopProperlyHandlesEmptyMessage(): void { - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer(new Container); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $this->sqs->expects('receiveMessage')->with(['QueueUrl' => $this->queueUrl, 'MessageSystemAttributeNames' => ['ApproximateReceiveCount']])->andReturn($this->mockedReceiveEmptyMessageResponseModel); + $this->expectSqsCommand('receiveMessage', ['QueueUrl' => $this->queueUrl, 'MessageSystemAttributeNames' => ['ApproximateReceiveCount']], $this->mockedReceiveEmptyMessageResponseModel); $result = $queue->pop($this->queueName); $this->assertNull($result); } public function testDelayedPushWithDateTimeProperlyPushesJobOntoSqs(): void { - $now = CarbonImmutable::now(); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'secondsUntil', 'getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); + CarbonImmutable::setTestNow($now = CarbonImmutable::now()->startOfSecond()); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($this->mockedJob, $this->queueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('secondsUntil')->with($now->addSeconds(5))->willReturn(5); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $this->sqs->expects('sendMessage')->with(['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->mockedPayload, 'DelaySeconds' => 5])->andReturn($this->mockedSendMessageResponseModel); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', ['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->isPayloadOf($this->mockedJob), 'DelaySeconds' => 5], $this->mockedSendMessageResponseModel); $id = $queue->later($now->addSeconds(5), $this->mockedJob, $this->mockedData, $this->queueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testDelayedPushProperlyPushesJobOntoSqs(): void { - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'secondsUntil', 'getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($this->mockedJob, $this->queueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('secondsUntil')->with($this->mockedDelay)->willReturn($this->mockedDelay); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $this->sqs->expects('sendMessage')->with(['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->mockedPayload, 'DelaySeconds' => $this->mockedDelay])->andReturn($this->mockedSendMessageResponseModel); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', ['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->isPayloadOf($this->mockedJob), 'DelaySeconds' => $this->mockedDelay], $this->mockedSendMessageResponseModel); $id = $queue->later($this->mockedDelay, $this->mockedJob, $this->mockedData, $this->queueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobOntoSqs(): void { - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($this->mockedJob, $this->queueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $this->sqs->expects('sendMessage')->with(['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->mockedPayload])->andReturn($this->mockedSendMessageResponseModel); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', ['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->isPayloadOf($this->mockedJob)], $this->mockedSendMessageResponseModel); $id = $queue->push($this->mockedJob, $this->mockedData, $this->queueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } #[DataProvider('queueDefaultingDataProvider')] @@ -240,13 +310,13 @@ public function testPushPreservesZeroQueueAndDefaultsEmptyQueue(string $requeste ->onlyMethods(['createPayload', 'getQueue']) ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) ->getMock(); - $queue->setContainer($this->createSpyContainer()); + $queue->setContainer($this->createSpyContainer()->instance()); $queue->expects($this->once())->method('createPayload')->with($this->mockedJob, $logicalQueue, $this->mockedData)->willReturn($this->mockedPayload); $queue->expects($this->once())->method('getQueue')->with($requestedQueue)->willReturn($queueUrl); - $this->sqs->expects('sendMessage')->with([ + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $queueUrl, 'MessageBody' => $this->mockedPayload, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $this->assertSame( $this->mockedMessageId, @@ -262,15 +332,15 @@ public function testLaterPreservesZeroQueueAndDefaultsEmptyQueue(string $request ->onlyMethods(['createPayload', 'getQueue', 'secondsUntil']) ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) ->getMock(); - $queue->setContainer($this->createSpyContainer()); + $queue->setContainer($this->createSpyContainer()->instance()); $queue->expects($this->once())->method('createPayload')->with($this->mockedJob, $logicalQueue, $this->mockedData, $this->mockedDelay)->willReturn($this->mockedPayload); $queue->expects($this->once())->method('getQueue')->with($requestedQueue)->willReturn($queueUrl); $queue->expects($this->once())->method('secondsUntil')->with($this->mockedDelay)->willReturn($this->mockedDelay); - $this->sqs->expects('sendMessage')->with([ + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $queueUrl, 'MessageBody' => $this->mockedPayload, 'DelaySeconds' => $this->mockedDelay, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $this->assertSame( $this->mockedMessageId, @@ -291,17 +361,16 @@ public static function queueDefaultingDataProvider(): array public function testSizeProperlyReadsSqsQueueSize(): void { - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); - $this->sqs->expects('getQueueAttributes')->with([ + $this->expectSqsCommand('getQueueAttributes', [ 'QueueUrl' => $this->queueUrl, 'AttributeNames' => [ 'ApproximateNumberOfMessages', 'ApproximateNumberOfMessagesDelayed', 'ApproximateNumberOfMessagesNotVisible', ], - ])->andReturn(new Result([ + ], new Result([ 'Attributes' => [ 'ApproximateNumberOfMessages' => 1, 'ApproximateNumberOfMessagesDelayed' => 2, @@ -316,75 +385,78 @@ public function testSizeProperlyReadsSqsQueueSize(): void public function testPendingSizeProperlyReadsSqsQueuePendingSize(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->account]) - ->getMock(); - $queue->expects($this->exactly(2))->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); - $this->sqs->expects('getQueueAttributes')->with([ + $this->expectSqsCommand('getQueueAttributes', [ 'QueueUrl' => $this->queueUrl, 'AttributeNames' => ['ApproximateNumberOfMessages'], - ])->andReturn(new Result([ - 'Attributes' => ['ApproximateNumberOfMessages' => 1], + ], new Result([ + 'Attributes' => [ + 'ApproximateNumberOfMessages' => 1, + ], ])); $this->assertSame(1, $queue->pendingSize($this->queueName)); - $this->sqs->expects('getQueueAttributes')->with([ + // Test missing attribute fallback + $this->expectSqsCommand('getQueueAttributes', [ 'QueueUrl' => $this->queueUrl, 'AttributeNames' => ['ApproximateNumberOfMessages'], - ])->andReturn(new Result(['Attributes' => []])); + ], new Result([ + 'Attributes' => [], + ])); $this->assertSame(0, $queue->pendingSize($this->queueName)); } public function testDelayedSizeProperlyReadsSqsQueueDelayedSize(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->account]) - ->getMock(); - $queue->expects($this->exactly(2))->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); - $this->sqs->expects('getQueueAttributes')->with([ + $this->expectSqsCommand('getQueueAttributes', [ 'QueueUrl' => $this->queueUrl, 'AttributeNames' => ['ApproximateNumberOfMessagesDelayed'], - ])->andReturn(new Result([ - 'Attributes' => ['ApproximateNumberOfMessagesDelayed' => 2], + ], new Result([ + 'Attributes' => [ + 'ApproximateNumberOfMessagesDelayed' => 2, + ], ])); $this->assertSame(2, $queue->delayedSize($this->queueName)); - $this->sqs->expects('getQueueAttributes')->with([ + // Test missing attribute fallback + $this->expectSqsCommand('getQueueAttributes', [ 'QueueUrl' => $this->queueUrl, 'AttributeNames' => ['ApproximateNumberOfMessagesDelayed'], - ])->andReturn(new Result(['Attributes' => []])); + ], new Result([ + 'Attributes' => [], + ])); $this->assertSame(0, $queue->delayedSize($this->queueName)); } public function testReservedSizeProperlyReadsSqsQueueReservedSize(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->account]) - ->getMock(); - $queue->expects($this->exactly(2))->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); - $this->sqs->expects('getQueueAttributes')->with([ + $this->expectSqsCommand('getQueueAttributes', [ 'QueueUrl' => $this->queueUrl, 'AttributeNames' => ['ApproximateNumberOfMessagesNotVisible'], - ])->andReturn(new Result([ - 'Attributes' => ['ApproximateNumberOfMessagesNotVisible' => 3], + ], new Result([ + 'Attributes' => [ + 'ApproximateNumberOfMessagesNotVisible' => 3, + ], ])); $this->assertSame(3, $queue->reservedSize($this->queueName)); - $this->sqs->expects('getQueueAttributes')->with([ + // Test missing attribute fallback + $this->expectSqsCommand('getQueueAttributes', [ 'QueueUrl' => $this->queueUrl, 'AttributeNames' => ['ApproximateNumberOfMessagesNotVisible'], - ])->andReturn(new Result(['Attributes' => []])); + ], new Result([ + 'Attributes' => [], + ])); $this->assertSame(0, $queue->reservedSize($this->queueName)); } @@ -468,10 +540,10 @@ public function testForwardedQueueNameIsUsedWhenPushing(): void $queue = new SqsQueue($this->sqs, 'default', $this->prefix); $queue->setConnectionName('sqs'); - $this->sqs->expects('sendMessage')->with([ + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->prefix . 'processing', 'MessageBody' => 'payload', - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $queue->pushRaw('payload', 'jobs'); } @@ -515,15 +587,13 @@ public function testPushProperlyPushesJobObjectOntoSqs(): void { $job = new FakeSqsJob; - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($job, $this->queueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $this->sqs->expects('sendMessage')->with(['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->mockedPayload])->andReturn($this->mockedSendMessageResponseModel); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', ['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->isPayloadOf(FakeSqsJob::class)], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->queueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testPendingDispatchProperlyPushesJobObjectOntoSqs(): void @@ -531,83 +601,67 @@ public function testPendingDispatchProperlyPushesJobObjectOntoSqs(): void // Job will not be dispatched until the PendingDispatch object is destroyed. $pendingDispatch = FakeSqsJob::dispatch(); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($pendingDispatch->getJob(), $this->queueName, '')->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with(null)->willReturn($this->queueUrl); - $this->sqs->expects('sendMessage')->with(['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->mockedPayload])->andReturn($this->mockedSendMessageResponseModel); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', ['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->isPayloadOf(FakeSqsJob::class)], $this->mockedSendMessageResponseModel); - $dispatcher = new BusDispatcher($container, fn (): SqsQueue => $queue); - $container->shouldReceive('make') - ->with(DispatcherContract::class) - ->andReturn($dispatcher); - Container::setInstance($container); + $dispatcher = new BusDispatcher($container->instance(), fn (): SqsQueue => $queue); + app()->instance(DispatcherContract::class, $dispatcher); // Destroy object to trigger dispatch. unset($pendingDispatch); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobObjectOntoSqsFairQueue(): void { $job = (new FakeSqsJob)->onGroup($this->mockedMessageGroupId); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($job, $this->queueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $this->sqs->expects('sendMessage')->with(['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->mockedPayload, 'MessageGroupId' => $this->mockedMessageGroupId])->andReturn($this->mockedSendMessageResponseModel); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', ['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->isPayloadOf(FakeSqsJob::class), 'MessageGroupId' => $this->mockedMessageGroupId], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->queueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testPendingDispatchProperlyPushesJobObjectOntoSqsFairQueue(): void { $pendingDispatch = FakeSqsJob::dispatch()->onGroup($this->mockedMessageGroupId); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($pendingDispatch->getJob(), $this->queueName, '')->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with(null)->willReturn($this->queueUrl); - $this->sqs->expects('sendMessage')->with(['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->mockedPayload, 'MessageGroupId' => $this->mockedMessageGroupId])->andReturn($this->mockedSendMessageResponseModel); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', ['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->isPayloadOf(FakeSqsJob::class), 'MessageGroupId' => $this->mockedMessageGroupId], $this->mockedSendMessageResponseModel); - $dispatcher = new BusDispatcher($container, fn (): SqsQueue => $queue); - $container->shouldReceive('make') - ->with(DispatcherContract::class) - ->andReturn($dispatcher); - Container::setInstance($container); + $dispatcher = new BusDispatcher($container->instance(), fn (): SqsQueue => $queue); + app()->instance(DispatcherContract::class, $dispatcher); // Destroy object to trigger dispatch. unset($pendingDispatch); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobStringOntoSqsFifoQueue(): void { Str::createUuidsUsing(fn (): Uuid => $this->createMockedUuid($this->mockedDeduplicationId)); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($this->mockedJob, $this->fifoQueueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf($this->mockedJob), 'MessageGroupId' => $this->fifoQueueName, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $id = $queue->push($this->mockedJob, $this->mockedData, $this->fifoQueueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - Str::createUuidsNormally(); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobObjectOntoSqsFifoQueue(): void @@ -616,22 +670,18 @@ public function testPushProperlyPushesJobObjectOntoSqsFifoQueue(): void $job = (new FakeSqsJob)->onGroup($this->mockedMessageGroupId); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($job, $this->fifoQueueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJob::class), 'MessageGroupId' => $this->mockedMessageGroupId, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->fifoQueueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - Str::createUuidsNormally(); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobObjectWithoutMessageGroupOntoSqsFifoQueue(): void @@ -640,151 +690,160 @@ public function testPushProperlyPushesJobObjectWithoutMessageGroupOntoSqsFifoQue $job = new FakeSqsJob; - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($job, $this->fifoQueueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJob::class), 'MessageGroupId' => $this->fifoQueueName, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->fifoQueueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - Str::createUuidsNormally(); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobObjectWithEmptyMessageGroupOntoSqsFifoQueue(): void { Str::createUuidsUsing(fn (): Uuid => $this->createMockedUuid($this->mockedDeduplicationId)); - $job = $this->getMockBuilder(FakeSqsJobWithMessageGroup::class)->onlyMethods(['messageGroup'])->getMock(); - $job->expects($this->once())->method('messageGroup')->willReturn(''); + $calls = 0; + FakeSqsJobWithMessageGroup::createMessageGroupsUsing(function () use (&$calls): string { + ++$calls; + + return ''; + }); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $job = new FakeSqsJobWithMessageGroup; + + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($job, $this->fifoQueueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJobWithMessageGroup::class), 'MessageGroupId' => $this->fifoQueueName, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->fifoQueueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - Str::createUuidsNormally(); + $this->assertSame(1, $calls); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobObjectOntoSqsFifoQueueWithMessageGroupMethod(): void { Str::createUuidsUsing(fn (): Uuid => $this->createMockedUuid($this->mockedDeduplicationId)); - $job = $this->getMockBuilder(FakeSqsJobWithMessageGroup::class)->onlyMethods(['messageGroup'])->getMock(); - $job->expects($this->once())->method('messageGroup')->willReturn($this->mockedMessageGroupId); + $calls = 0; + FakeSqsJobWithMessageGroup::createMessageGroupsUsing(function () use (&$calls): string { + ++$calls; + + return $this->mockedMessageGroupId; + }); + $job = new FakeSqsJobWithMessageGroup; - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($job, $this->fifoQueueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJobWithMessageGroup::class), 'MessageGroupId' => $this->mockedMessageGroupId, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->fifoQueueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - Str::createUuidsNormally(); + $this->assertSame(1, $calls); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobObjectOntoSqsFifoQueueWithMessageGroupPropertyOverridingMethod(): void { Str::createUuidsUsing(fn (): Uuid => $this->createMockedUuid($this->mockedDeduplicationId)); - $job = $this->getMockBuilder(FakeSqsJobWithMessageGroup::class)->onlyMethods(['messageGroup'])->getMock(); - // Ensure the messageGroup method is not called when a messageGroup property is provided. - $job->expects($this->never())->method('messageGroup')->willReturn('this-should-not-be-used'); - $job->onGroup($this->mockedMessageGroupId); + FakeSqsJobWithMessageGroup::createMessageGroupsUsing(function (): never { + $this->fail('The messageGroup method should not be called when a message group is provided.'); + }); + + $job = (new FakeSqsJobWithMessageGroup)->onGroup($this->mockedMessageGroupId); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($job, $this->fifoQueueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJobWithMessageGroup::class), 'MessageGroupId' => $this->mockedMessageGroupId, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->fifoQueueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - Str::createUuidsNormally(); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobObjectOntoSqsFifoQueueWithDeduplicationId(): void { - $job = $this->getMockBuilder(FakeSqsJobWithDeduplication::class)->onlyMethods(['deduplicationId'])->getMock(); - $job->expects($this->once())->method('deduplicationId')->with($this->mockedPayload, $this->fifoQueueName)->willReturn($this->mockedDeduplicationId); - $job->onGroup($this->mockedMessageGroupId); + $calls = []; + FakeSqsJobWithDeduplication::createDeduplicationIdsUsing(function (string $payload, string $queue) use (&$calls): string { + $calls[] = [$payload, $queue]; + + return $this->mockedDeduplicationId; + }); + + $job = (new FakeSqsJobWithDeduplication)->onGroup($this->mockedMessageGroupId); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($job, $this->fifoQueueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJobWithDeduplication::class), 'MessageGroupId' => $this->mockedMessageGroupId, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->fifoQueueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $this->assertCount(1, $calls); + $this->assertTrue($this->isPayloadOf(FakeSqsJobWithDeduplication::class)($calls[0][0])); + $this->assertSame($this->fifoQueueName, $calls[0][1]); + $container->received('bound')->with('events')->times(3); } public function testPushProperlyPushesJobObjectOntoSqsFifoQueueWithDeduplicator(): void { - $job = $this->getMockBuilder(FakeSqsJobWithDeduplication::class)->onlyMethods(['deduplicationId'])->getMock(); - // Ensure the deduplicationId method is not called when a deduplicator callback is provided. - $job->expects($this->never())->method('deduplicationId')->willReturn('this-should-not-be-used'); - $job->onGroup($this->mockedMessageGroupId)->withDeduplicator(function (string $payload, string $queue): string { - $this->assertEquals($this->mockedPayload, $payload); - $this->assertEquals($this->fifoQueueName, $queue); - - return $this->mockedDeduplicationId; + FakeSqsJobWithDeduplication::createDeduplicationIdsUsing(function (): never { + $this->fail('The deduplicationId method should not be called when a deduplicator callback is provided.'); }); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + // Can't reference the test case in a serialized closure. + $deduplicationId = $this->mockedDeduplicationId; + $calls = []; + + $job = (new FakeSqsJobWithDeduplication)->onGroup($this->mockedMessageGroupId)->withDeduplicator( + static function (string $payload, string $queue) use (&$calls, $deduplicationId): string { + $calls[] = [$payload, $queue]; + + return $deduplicationId; + } + ); + + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($job, $this->fifoQueueName, $this->mockedData)->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJobWithDeduplication::class), 'MessageGroupId' => $this->mockedMessageGroupId, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->fifoQueueName); $this->assertEquals($this->mockedMessageId, $id); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $this->assertSame([[$this->handler->getLastCommand()['MessageBody'], $this->fifoQueueName]], $calls); + $container->received('bound')->with('events')->times(3); } public function testPendingDispatchProperlyPushesJobObjectOntoSqsFifoQueue(): void @@ -793,30 +852,23 @@ public function testPendingDispatchProperlyPushesJobObjectOntoSqsFifoQueue(): vo $pendingDispatch = FakeSqsJob::dispatch()->onGroup($this->mockedMessageGroupId); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($pendingDispatch->getJob(), $this->fifoQueueName, '')->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with(null)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJob::class), 'MessageGroupId' => $this->mockedMessageGroupId, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); - $dispatcher = new BusDispatcher($container, fn (): SqsQueue => $queue); - $container->shouldReceive('make') - ->with(DispatcherContract::class) - ->andReturn($dispatcher); - Container::setInstance($container); + $dispatcher = new BusDispatcher($container->instance(), fn (): SqsQueue => $queue); + app()->instance(DispatcherContract::class, $dispatcher); // Destroy object to trigger dispatch. unset($pendingDispatch); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - Str::createUuidsNormally(); + $container->received('bound')->with('events')->times(3); } public function testPendingDispatchProperlyPushesJobObjectOntoSqsFifoQueueWithDeduplicationId(): void @@ -825,30 +877,23 @@ public function testPendingDispatchProperlyPushesJobObjectOntoSqsFifoQueueWithDe $pendingDispatch = FakeSqsJobWithDeduplication::dispatch()->onGroup($this->mockedMessageGroupId); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($pendingDispatch->getJob(), $this->fifoQueueName, '')->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with(null)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJobWithDeduplication::class), 'MessageGroupId' => $this->mockedMessageGroupId, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); - $dispatcher = new BusDispatcher($container, fn (): SqsQueue => $queue); - $container->shouldReceive('make') - ->with(DispatcherContract::class) - ->andReturn($dispatcher); - Container::setInstance($container); + $dispatcher = new BusDispatcher($container->instance(), fn (): SqsQueue => $queue); + app()->instance(DispatcherContract::class, $dispatcher); // Destroy object to trigger dispatch. unset($pendingDispatch); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - FakeSqsJobWithDeduplication::createDeduplicationIdsNormally(); + $container->received('bound')->with('events')->times(3); } public function testPendingDispatchProperlyPushesJobObjectOntoSqsFifoQueueWithDeduplicator(): void @@ -857,37 +902,36 @@ public function testPendingDispatchProperlyPushesJobObjectOntoSqsFifoQueueWithDe $this->fail('The deduplicationId method should not be called when a deduplicator callback is provided.'); }); - $pendingDispatch = FakeSqsJobWithDeduplication::dispatch()->onGroup($this->mockedMessageGroupId)->withDeduplicator(function (string $payload, string $queue): string { - $this->assertEquals($this->mockedPayload, $payload); - $this->assertEquals($this->fifoQueueName, $queue); + // Can't reference the test case in a serialized closure. + $deduplicationId = $this->mockedDeduplicationId; + $calls = []; - return $this->mockedDeduplicationId; - }); + $pendingDispatch = FakeSqsJobWithDeduplication::dispatch()->onGroup($this->mockedMessageGroupId)->withDeduplicator( + static function (string $payload, string $queue) use (&$calls, $deduplicationId): string { + $calls[] = [$payload, $queue]; + + return $deduplicationId; + } + ); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['createPayload', 'getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->with($pendingDispatch->getJob(), $this->fifoQueueName, '')->willReturn($this->mockedPayload); - $queue->expects($this->once())->method('getQueue')->with(null)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, - 'MessageBody' => $this->mockedPayload, + 'MessageBody' => $this->isPayloadOf(FakeSqsJobWithDeduplication::class), 'MessageGroupId' => $this->mockedMessageGroupId, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); - $dispatcher = new BusDispatcher($container, fn (): SqsQueue => $queue); - $container->shouldReceive('make') - ->with(DispatcherContract::class) - ->andReturn($dispatcher); - Container::setInstance($container); + $dispatcher = new BusDispatcher($container->instance(), fn (): SqsQueue => $queue); + app()->instance(DispatcherContract::class, $dispatcher); // Destroy object to trigger dispatch. unset($pendingDispatch); - $container->shouldHaveReceived('bound')->with('events')->times(3); - - FakeSqsJobWithDeduplication::createDeduplicationIdsNormally(); + $this->assertSame([[$this->handler->getLastCommand()['MessageBody'], $this->fifoQueueName]], $calls); + $container->received('bound')->with('events')->times(3); } public function testJobObjectCanBeSerializedOntoSqsFifoQueueWithDeduplicator(): void @@ -899,11 +943,10 @@ public function testJobObjectCanBeSerializedOntoSqsFifoQueueWithDeduplicator(): return $deduplicationId; }); - $queue = $this->getMockBuilder(SqsQueue::class)->onlyMethods(['getQueue'])->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account])->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $container = $this->createSpyContainer(); - $queue->setContainer($container); - $queue->expects($this->once())->method('getQueue')->with(null)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->withArgs(function (array $args): bool { + $queue->setContainer($container->instance()); + $this->expectSqsCommand('sendMessage', function (array $args): bool { $this->assertIsArray($args); $this->assertEqualsCanonicalizing(['QueueUrl', 'MessageBody', 'MessageGroupId', 'MessageDeduplicationId'], array_keys($args)); $this->assertEquals($this->fifoQueueUrl, $args['QueueUrl']); @@ -916,18 +959,18 @@ public function testJobObjectCanBeSerializedOntoSqsFifoQueueWithDeduplicator(): $this->assertInstanceOf(SerializableClosure::class, $command->deduplicator); return true; - })->andReturn($this->mockedSendMessageResponseModel); + }, $this->mockedSendMessageResponseModel); - $dispatcher = new BusDispatcher($container, fn (): SqsQueue => $queue); - $container->shouldReceive('make') + $dispatcher = new BusDispatcher($container->instance(), fn (): SqsQueue => $queue); + $container->allows('make') ->with(DispatcherContract::class) - ->andReturn($dispatcher); - Container::setInstance($container); + ->returns($dispatcher); + Container::setInstance($container->instance()); // Destroy object to trigger dispatch. unset($pendingDispatch); - $container->shouldHaveReceived('bound')->with('events')->times(3); + $container->received('bound')->with('events')->times(3); } // REMOVED: Laravel's three delayed FIFO tests silently omit positive delays; @@ -939,9 +982,8 @@ public function testDelayedPushRejectsPositiveDelayForStringJobOnSqsFifoQueue(): ->onlyMethods(['createPayload']) ->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account]) ->getMock(); - $queue->setContainer($this->createSpyContainer()); + $queue->setContainer($this->createSpyContainer()->instance()); $queue->expects($this->never())->method('createPayload'); - $this->sqs->shouldNotReceive('sendMessage'); $this->expectException(LogicException::class); $this->expectExceptionMessageIs('SQS FIFO queues do not support per-message delays.'); @@ -957,9 +999,8 @@ public function testDelayedPushRejectsPositiveDelayForObjectJobOnSqsFifoQueue(): ->onlyMethods(['createPayload']) ->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account]) ->getMock(); - $queue->setContainer($this->createSpyContainer()); + $queue->setContainer($this->createSpyContainer()->instance()); $queue->expects($this->never())->method('createPayload'); - $this->sqs->shouldNotReceive('sendMessage'); $this->expectException(LogicException::class); @@ -975,15 +1016,14 @@ public function testDelayedPendingDispatchRejectsPositiveDelayOnSqsFifoQueue(): ->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account]) ->getMock(); $container = $this->createSpyContainer(); - $queue->setContainer($container); + $queue->setContainer($container->instance()); $queue->expects($this->never())->method('createPayload'); - $this->sqs->shouldNotReceive('sendMessage'); - $dispatcher = new BusDispatcher($container, fn (): SqsQueue => $queue); - $container->shouldReceive('make') + $dispatcher = new BusDispatcher($container->instance(), fn (): SqsQueue => $queue); + $container->allows('make') ->with(DispatcherContract::class) - ->andReturn($dispatcher); - Container::setInstance($container); + ->returns($dispatcher); + Container::setInstance($container->instance()); $this->expectException(LogicException::class); @@ -1000,7 +1040,7 @@ public function testNonPositiveAndElapsedDelaysRemainImmediateOnSqsFifoQueue(int ->onlyMethods(['createPayload', 'getQueue']) ->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->account]) ->getMock(); - $queue->setContainer($this->createSpyContainer()); + $queue->setContainer($this->createSpyContainer()->instance()); $queue->expects($this->once())->method('createPayload')->with( $this->mockedJob, $this->fifoQueueName, @@ -1008,19 +1048,17 @@ public function testNonPositiveAndElapsedDelaysRemainImmediateOnSqsFifoQueue(int $delay, )->willReturn($this->mockedPayload); $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $this->sqs->expects('sendMessage')->with([ + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->fifoQueueUrl, 'MessageBody' => $this->mockedPayload, 'MessageGroupId' => $this->fifoQueueName, 'MessageDeduplicationId' => $this->mockedDeduplicationId, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $this->assertSame( $this->mockedMessageId, $queue->later($delay, $this->mockedJob, $this->mockedData, $this->fifoQueueName), ); - - Str::createUuidsNormally(); } /** @@ -1047,8 +1085,8 @@ 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 = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->times($phase === 'queued' ? 1 : 0)->with($earlierFailure); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->times($phase === 'queued' ? 1 : 0)->with($earlierFailure); $container->instance(ExceptionHandler::class, $handler); $notified = []; $canceled = null; @@ -1063,16 +1101,13 @@ public function testPushCancellationPublishesTheKnownOutcome(string $phase): voi }); } - $queue = m::mock(SqsQueue::class, [$this->sqs, $this->queueName, $this->prefix]) - ->makePartial()->shouldAllowMockingProtectedMethods(); + $queue = Double::for(SqsQueue::class)->passthru(new SqsQueue($this->sqs, $this->queueName, $this->prefix)); $queue->setContainer($container); $queue->setConnectionName('sqs'); if (in_array($phase, ['stored', 'queued'], true)) { - $this->sqs->expects('sendMessage')->andReturn($this->mockedSendMessageResponseModel); - $queue->expects('handlePayloadPushed')->andThrow($phase === 'stored' ? $cancellation : $earlierFailure); - } else { - $this->sqs->shouldNotReceive('sendMessage'); + $this->expectSqsCommand('sendMessage', null, $this->mockedSendMessageResponseModel); + $queue->expects('handlePayloadPushed')->throws($phase === 'stored' ? $cancellation : $earlierFailure); } try { @@ -1107,14 +1142,15 @@ public function testPushRawStoresPayloadToCacheWhenExceedingThreshold(): void $path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . $uuid; $pointer = json_encode(['@pointer' => $path], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($path, $payload)->andReturnTrue(); + $store = Double::for(CacheRepository::class); + $store->expects('put')->with($path, $payload)->returns(true); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class)->makePartial(); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); $queue = new SqsQueue( $this->sqs, @@ -1122,12 +1158,12 @@ public function testPushRawStoresPayloadToCacheWhenExceedingThreshold(): void $this->prefix, overflowStorage: ['enabled' => true, 'store' => 'database'], ); - $queue->setContainer($container); + $queue->setContainer($container->instance()); - $this->sqs->expects('sendMessage')->with([ + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->queueUrl, 'MessageBody' => $pointer, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $this->assertSame($this->mockedMessageId, $queue->pushRaw($payload, $this->queueName)); } @@ -1140,8 +1176,9 @@ public function testPushRawDoesNotStoreToCacheWhenBelowThreshold(): void 'data' => 'small', ], JSON_THROW_ON_ERROR); - $container = m::mock(Container::class)->makePartial(); - $container->shouldNotReceive('make')->with('cache'); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->never()->with('cache'); $queue = new SqsQueue( $this->sqs, @@ -1149,12 +1186,12 @@ public function testPushRawDoesNotStoreToCacheWhenBelowThreshold(): void $this->prefix, overflowStorage: ['enabled' => true, 'store' => 'database'], ); - $queue->setContainer($container); + $queue->setContainer($container->instance()); - $this->sqs->expects('sendMessage')->with([ + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->queueUrl, 'MessageBody' => $payload, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $this->assertSame($this->mockedMessageId, $queue->pushRaw($payload, $this->queueName)); } @@ -1169,14 +1206,15 @@ public function testPushRawAlwaysStoresToCacheWhenAlwaysIsTrue(): void $path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'always-overflow'; $pointer = json_encode(['@pointer' => $path], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($path, $payload)->andReturnTrue(); + $store = Double::for(CacheRepository::class); + $store->expects('put')->with($path, $payload)->returns(true); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class)->makePartial(); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); $queue = new SqsQueue( $this->sqs, @@ -1184,12 +1222,12 @@ public function testPushRawAlwaysStoresToCacheWhenAlwaysIsTrue(): void $this->prefix, overflowStorage: ['enabled' => true, 'always' => true, 'store' => 'database'], ); - $queue->setContainer($container); + $queue->setContainer($container->instance()); - $this->sqs->expects('sendMessage')->with([ + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->queueUrl, 'MessageBody' => $pointer, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $queue->pushRaw($payload, $this->queueName); } @@ -1202,16 +1240,17 @@ public function testPushRawDoesNotStoreToCacheWhenNotEnabled(): void 'data' => str_repeat('x', SqsQueue::MAX_SQS_PAYLOAD_SIZE), ], JSON_THROW_ON_ERROR); - $container = m::mock(Container::class)->makePartial(); - $container->shouldNotReceive('make')->with('cache'); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->never()->with('cache'); $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); - $queue->setContainer($container); + $queue->setContainer($container->instance()); - $this->sqs->expects('sendMessage')->with([ + $this->expectSqsCommand('sendMessage', [ 'QueueUrl' => $this->queueUrl, 'MessageBody' => $payload, - ])->andReturn($this->mockedSendMessageResponseModel); + ], $this->mockedSendMessageResponseModel); $this->assertSame($this->mockedMessageId, $queue->pushRaw($payload, $this->queueName)); } @@ -1226,20 +1265,15 @@ public function testPushRawGeneratesOverflowPathForEveryNonStringOrEmptyUuid(mix ], JSON_THROW_ON_ERROR); $path = null; - $store = m::mock(CacheRepository::class); - $store->expects('put')->withArgs( - function (string $candidate, string $stored) use (&$path, $payload): bool { - $path = $candidate; + $store = Double::for(CacheRepository::class); + $store->expects('put')->with(Argument::capture($path), $payload)->returns(true); - return $stored === $payload; - } - )->andReturnTrue(); - - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class)->makePartial(); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); $queue = new SqsQueue( $this->sqs, @@ -1247,15 +1281,13 @@ function (string $candidate, string $stored) use (&$path, $payload): bool { $this->prefix, overflowStorage: ['enabled' => true, 'always' => true, 'store' => 'database'], ); - $queue->setContainer($container); + $queue->setContainer($container->instance()); - $this->sqs->expects('sendMessage')->withArgs( - function (array $arguments) use (&$path): bool { - $pointer = json_decode($arguments['MessageBody'], true, flags: JSON_THROW_ON_ERROR); + $this->expectSqsCommand('sendMessage', function (array $arguments) use (&$path): bool { + $pointer = json_decode($arguments['MessageBody'], true, flags: JSON_THROW_ON_ERROR); - return $pointer['@pointer'] === $path; - } - )->andReturn($this->mockedSendMessageResponseModel); + return $pointer['@pointer'] === $path; + }, $this->mockedSendMessageResponseModel); $queue->pushRaw($payload, $this->queueName); @@ -1290,19 +1322,20 @@ public function testPushRawFailsBeforeSendingWhenOverflowStorageReturnsFalse(?bo $cancellation = new RuntimeException('Delete cleanup failed.', previous: $cancellation); } - $store = m::mock(CacheRepository::class); - $store->expects('put')->andReturnFalse(); + $store = Double::for(CacheRepository::class); + $store->expects('put')->returns(false); if ($cleanupThrows === null) { - $store->expects('forget')->with($path)->andReturnTrue(); + $store->expects('forget')->with($path)->returns(true); } else { - $store->expects('forget')->with($path)->andThrow($cancellation); + $store->expects('forget')->with($path)->throws($cancellation); } - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(ContainerContract::class); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(ContainerContract::class, override: true); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); $queue = new SqsQueue( $this->sqs, @@ -1310,9 +1343,7 @@ public function testPushRawFailsBeforeSendingWhenOverflowStorageReturnsFalse(?bo $this->prefix, overflowStorage: ['enabled' => true, 'always' => true, 'store' => 'database'], ); - $queue->setContainer($container); - - $this->sqs->shouldNotReceive('sendMessage'); + $queue->setContainer($container->instance()); try { $queue->pushRaw($payload, $this->queueName); @@ -1341,23 +1372,24 @@ public function testPushRawPreservesCancellationAndCleansTheAttemptedOverflowPay $cleanupCancellation = new RuntimeException('delete cleanup failed', previous: $cleanupCancellation); } - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->with($cleanupCancellation)->times($deleteCleanupThrows ? 1 : 0); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with($cleanupCancellation)->times($deleteCleanupThrows ? 1 : 0); Container::getInstance()->instance(ExceptionHandler::class, $handler); - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($path, $payload)->andThrow($cancellation); + $store = Double::for(CacheRepository::class); + $store->expects('put')->with($path, $payload)->throws($cancellation); if ($deleteCleanupThrows === null) { - $store->expects('forget')->with($path)->andReturnTrue(); + $store->expects('forget')->with($path)->returns(true); } else { - $store->expects('forget')->with($path)->andThrow($cleanupCancellation); + $store->expects('forget')->with($path)->throws($cleanupCancellation); } - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(ContainerContract::class); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(ContainerContract::class, override: true); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); $queue = new SqsQueue( $this->sqs, @@ -1365,9 +1397,7 @@ public function testPushRawPreservesCancellationAndCleansTheAttemptedOverflowPay $this->prefix, overflowStorage: ['enabled' => true, 'always' => true, 'store' => 'database'], ); - $queue->setContainer($container); - - $this->sqs->shouldNotReceive('sendMessage'); + $queue->setContainer($container->instance()); try { $queue->pushRaw($payload, $this->queueName); @@ -1395,15 +1425,16 @@ public function testPushRawRetainsOverflowPayloadWhenSqsDeliveryIsAmbiguous(): v { $payload = json_encode(['uuid' => 'ambiguous'], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('put')->andReturnTrue(); - $store->shouldNotReceive('forget'); + $store = Double::for(CacheRepository::class); + $store->expects('put')->returns(true); + $store->expects('forget')->never(); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class)->makePartial(); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); $queue = new SqsQueue( $this->sqs, @@ -1411,9 +1442,9 @@ public function testPushRawRetainsOverflowPayloadWhenSqsDeliveryIsAmbiguous(): v $this->prefix, overflowStorage: ['enabled' => true, 'always' => true, 'store' => 'database'], ); - $queue->setContainer($container); + $queue->setContainer($container->instance()); - $this->sqs->expects('sendMessage')->andThrow(new RuntimeException('transport failed')); + $this->expectSqsCommand('sendMessage', null, new RuntimeException('transport failed')); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('transport failed'); @@ -1426,15 +1457,16 @@ public function testPushRawRetainsOverflowPayloadWhenSqsDeliveryIsCanceled(): vo $payload = json_encode(['uuid' => 'canceled-delivery'], JSON_THROW_ON_ERROR); $cancellation = new CanceledException; - $store = m::mock(CacheRepository::class); - $store->expects('put')->andReturnTrue(); - $store->shouldNotReceive('forget'); + $store = Double::for(CacheRepository::class); + $store->expects('put')->returns(true); + $store->expects('forget')->never(); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $container = m::mock(Container::class)->makePartial(); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true)->passthru(new Container); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); $queue = new SqsQueue( $this->sqs, @@ -1442,9 +1474,9 @@ public function testPushRawRetainsOverflowPayloadWhenSqsDeliveryIsCanceled(): vo $this->prefix, overflowStorage: ['enabled' => true, 'always' => true, 'store' => 'database'], ); - $queue->setContainer($container); + $queue->setContainer($container->instance()); - $this->sqs->expects('sendMessage')->andThrow($cancellation); + $this->expectSqsCommand('sendMessage', null, $cancellation); try { $queue->pushRaw($payload, $this->queueName); @@ -1459,28 +1491,31 @@ public function testClearFlushesOverflowStoreWhenFlushOnClearEnabled(): void $store = new Repository(new ArrayStore); $store->put('foo', 'bar'); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); - - $container = m::mock(ContainerContract::class); - $container->expects('make')->with('cache')->andReturn($cache); - - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'size']) - ->setConstructorArgs([ - $this->sqs, - $this->queueName, - $this->prefix, - '', - false, - ['enabled' => true, 'flush_on_clear' => true, 'store' => 'database'], - ]) - ->getMock(); - $queue->setContainer($container); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $queue->expects($this->once())->method('size')->with($this->queueName)->willReturn(5); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $this->sqs->expects('purgeQueue')->with(['QueueUrl' => $this->queueUrl]); + $container = $this->createSpyContainer(); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); + + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix, '', false, [ + 'enabled' => true, + 'store' => 'database', + 'always' => false, + 'delete_after_processing' => true, + 'flush_on_clear' => true, + ]); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('getQueueAttributes', ['QueueUrl' => $this->queueUrl, 'AttributeNames' => [ + 'ApproximateNumberOfMessages', + 'ApproximateNumberOfMessagesDelayed', + 'ApproximateNumberOfMessagesNotVisible', + ]], new Result(['Attributes' => [ + 'ApproximateNumberOfMessages' => 3, + 'ApproximateNumberOfMessagesDelayed' => 1, + 'ApproximateNumberOfMessagesNotVisible' => 1, + ]])); + $this->expectSqsCommand('purgeQueue', ['QueueUrl' => $this->queueUrl]); $this->assertSame(5, $queue->clear($this->queueName)); @@ -1489,17 +1524,18 @@ public function testClearFlushesOverflowStoreWhenFlushOnClearEnabled(): void public function testClearFailsWhenTheOverflowStoreCannotBeFlushed(): void { - $store = m::mock(CacheStore::class); - $store->expects('flush')->andReturnFalse(); + $store = Double::for(CacheStore::class); + $store->expects('flush')->returns(false); - $repository = m::mock(CacheRepository::class); - $repository->expects('getStore')->andReturn($store); + $repository = Double::for(CacheRepository::class); + $repository->expects('getStore')->returns($store); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($repository); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($repository); - $container = m::mock(ContainerContract::class); - $container->expects('make')->with('cache')->andReturn($cache); + $container = Double::for(ContainerContract::class, override: true); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); $queue = $this->getMockBuilder(SqsQueue::class) ->onlyMethods(['getQueue', 'size']) @@ -1512,11 +1548,11 @@ public function testClearFailsWhenTheOverflowStoreCannotBeFlushed(): void ['enabled' => true, 'flush_on_clear' => true, 'store' => 'database'], ]) ->getMock(); - $queue->setContainer($container); + $queue->setContainer($container->instance()); $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); $queue->expects($this->once())->method('size')->with($this->queueName)->willReturn(5); - $this->sqs->expects('purgeQueue')->with(['QueueUrl' => $this->queueUrl]); + $this->expectSqsCommand('purgeQueue', ['QueueUrl' => $this->queueUrl], null); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Unable to clear the SQS overflow payload store.'); @@ -1526,50 +1562,56 @@ public function testClearFailsWhenTheOverflowStoreCannotBeFlushed(): void public function testClearDoesNotFlushOverflowStoreWhenFlushOnClearDisabled(): void { - $container = m::mock(ContainerContract::class); - $container->shouldNotReceive('make'); - - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'size']) - ->setConstructorArgs([ - $this->sqs, - $this->queueName, - $this->prefix, - '', - false, - ['enabled' => true, 'flush_on_clear' => false, 'store' => 'database'], - ]) - ->getMock(); - $queue->setContainer($container); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $queue->expects($this->once())->method('size')->with($this->queueName)->willReturn(5); - - $this->sqs->expects('purgeQueue')->with(['QueueUrl' => $this->queueUrl]); + $container = $this->createSpyContainer(); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->never(); + + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix, '', false, [ + 'enabled' => true, + 'store' => 'database', + 'always' => false, + 'delete_after_processing' => true, + 'flush_on_clear' => false, + ]); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('getQueueAttributes', ['QueueUrl' => $this->queueUrl, 'AttributeNames' => [ + 'ApproximateNumberOfMessages', + 'ApproximateNumberOfMessagesDelayed', + 'ApproximateNumberOfMessagesNotVisible', + ]], new Result(['Attributes' => [ + 'ApproximateNumberOfMessages' => 3, + 'ApproximateNumberOfMessagesDelayed' => 1, + 'ApproximateNumberOfMessagesNotVisible' => 1, + ]])); + $this->expectSqsCommand('purgeQueue', ['QueueUrl' => $this->queueUrl]); $this->assertSame(5, $queue->clear($this->queueName)); } public function testClearDoesNotFlushOverflowStoreWhenOverflowDisabled(): void { - $container = m::mock(ContainerContract::class); - $container->shouldNotReceive('make'); - - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'size']) - ->setConstructorArgs([ - $this->sqs, - $this->queueName, - $this->prefix, - '', - false, - ['enabled' => false, 'flush_on_clear' => true, 'store' => 'database'], - ]) - ->getMock(); - $queue->setContainer($container); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $queue->expects($this->once())->method('size')->with($this->queueName)->willReturn(5); - - $this->sqs->expects('purgeQueue')->with(['QueueUrl' => $this->queueUrl]); + $container = $this->createSpyContainer(); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->never(); + + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix, '', false, [ + 'enabled' => false, + 'store' => 'database', + 'always' => false, + 'delete_after_processing' => true, + 'flush_on_clear' => true, + ]); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('getQueueAttributes', ['QueueUrl' => $this->queueUrl, 'AttributeNames' => [ + 'ApproximateNumberOfMessages', + 'ApproximateNumberOfMessagesDelayed', + 'ApproximateNumberOfMessagesNotVisible', + ]], new Result(['Attributes' => [ + 'ApproximateNumberOfMessages' => 3, + 'ApproximateNumberOfMessagesDelayed' => 1, + 'ApproximateNumberOfMessagesNotVisible' => 1, + ]])); + $this->expectSqsCommand('purgeQueue', ['QueueUrl' => $this->queueUrl]); $this->assertSame(5, $queue->clear($this->queueName)); } @@ -1579,28 +1621,31 @@ public function testClearForwardsConfiguredStoreNameToFactory(): void $store = new Repository(new ArrayStore); $store->put('foo', 'bar'); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('redis')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('redis')->returns($store); - $container = m::mock(ContainerContract::class); - $container->expects('make')->with('cache')->andReturn($cache); - - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'size']) - ->setConstructorArgs([ - $this->sqs, - $this->queueName, - $this->prefix, - '', - false, - ['enabled' => true, 'flush_on_clear' => true, 'store' => 'redis'], - ]) - ->getMock(); - $queue->setContainer($container); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $queue->expects($this->once())->method('size')->with($this->queueName)->willReturn(5); - - $this->sqs->expects('purgeQueue')->with(['QueueUrl' => $this->queueUrl]); + $container = $this->createSpyContainer(); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('make')->with('cache')->returns($cache); + + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix, '', false, [ + 'enabled' => true, + 'store' => 'redis', + 'always' => false, + 'delete_after_processing' => true, + 'flush_on_clear' => true, + ]); + $queue->setContainer($container->instance()); + $this->expectSqsCommand('getQueueAttributes', ['QueueUrl' => $this->queueUrl, 'AttributeNames' => [ + 'ApproximateNumberOfMessages', + 'ApproximateNumberOfMessagesDelayed', + 'ApproximateNumberOfMessagesNotVisible', + ]], new Result(['Attributes' => [ + 'ApproximateNumberOfMessages' => 3, + 'ApproximateNumberOfMessagesDelayed' => 1, + 'ApproximateNumberOfMessagesNotVisible' => 1, + ]])); + $this->expectSqsCommand('purgeQueue', ['QueueUrl' => $this->queueUrl]); $this->assertSame(5, $queue->clear($this->queueName)); @@ -1615,7 +1660,6 @@ public function testBulkRejectsDelayAttributeOnFifoBeforePayloadCreation(): void ->getMock(); $queue->setContainer(new Container); $queue->expects($this->never())->method('createPayload'); - $this->sqs->shouldNotReceive('sendMessageBatch'); $this->expectException(LogicException::class); @@ -1626,16 +1670,16 @@ public function testMixedBulkRejectsPositiveFifoDelayBeforeTransactionLookupOrPa { $immediate = new FakeSqsJob; $afterCommit = (new FakeSqsJob)->afterCommit()->delay(10); - $container = m::mock(ContainerContract::class); - $container->shouldNotReceive('has'); + $container = Double::for(ContainerContract::class, override: true); + $container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes); + $container->expects('has')->never(); $queue = $this->getMockBuilder(SqsQueue::class) ->onlyMethods(['createPayload']) ->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->prefix]) ->getMock(); - $queue->setContainer($container); + $queue->setContainer($container->instance()); $queue->expects($this->never())->method('createPayload'); - $this->sqs->shouldNotReceive('sendMessageBatch'); $this->expectException(LogicException::class); @@ -1644,22 +1688,15 @@ public function testMixedBulkRejectsPositiveFifoDelayBeforeTransactionLookupOrPa public function testBulkSendsAllJobsInASingleBatchRequest(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer(new Container); - $queue->expects($this->once())->method('getQueue')->with($this->queueName)->willReturn($this->queueUrl); - $queue->expects($this->exactly(3))->method('createPayload')->willReturnOnConsecutiveCalls('p1', 'p2', 'p3'); $captured = null; - $this->sqs->expects('sendMessageBatch')->withArgs( - function (array $arguments) use (&$captured): bool { - $captured = $arguments; + $this->expectSqsCommand('sendMessageBatch', function (array $arguments) use (&$captured): bool { + $captured = $arguments; - return true; - } - )->andReturn(new Result([ + return true; + }, new Result([ 'Successful' => [ ['Id' => '0', 'MessageId' => 'm1'], ['Id' => '1', 'MessageId' => 'm2'], @@ -1672,27 +1709,23 @@ function (array $arguments) use (&$captured): bool { $this->assertSame($this->queueUrl, $captured['QueueUrl']); $this->assertSame(['0', '1', '2'], array_column($captured['Entries'], 'Id')); - $this->assertSame(['p1', 'p2', 'p3'], array_column($captured['Entries'], 'MessageBody')); + $this->assertSame(['a', 'b', 'c'], array_map( + static fn (string $body): string => json_decode($body, true, flags: JSON_THROW_ON_ERROR)['job'], + array_column($captured['Entries'], 'MessageBody'), + )); } public function testBulkChunksAtTenMessagesPerBatch(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer(new Container); - $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); - $queue->method('createPayload')->willReturnCallback(static fn (string $job): string => "payload-{$job}"); $batchSizes = []; - $this->sqs->expects('sendMessageBatch')->times(2)->withArgs( - function (array $arguments) use (&$batchSizes): bool { - $batchSizes[] = count($arguments['Entries']); + $this->expectSqsCommand('sendMessageBatch', function (array $arguments) use (&$batchSizes): bool { + $batchSizes[] = count($arguments['Entries']); - return true; - } - )->andReturn(new Result(['Successful' => [], 'Failed' => []])); + return true; + }, new Result(['Successful' => [], 'Failed' => []]), 2); $queue->bulk(array_map('strval', range(1, 15)), 'data', $this->queueName); @@ -1701,54 +1734,40 @@ function (array $arguments) use (&$batchSizes): bool { public function testBulkChunksWhenCumulativePayloadSizeExceedsLimit(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer(new Container); - $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); - $queue->method('createPayload')->willReturn( - str_repeat('x', (int) (SqsQueue::MAX_SQS_PAYLOAD_SIZE * 0.6)) - ); $batchSizes = []; - $this->sqs->expects('sendMessageBatch')->times(2)->withArgs( - function (array $arguments) use (&$batchSizes): bool { - $batchSizes[] = count($arguments['Entries']); + $this->expectSqsCommand('sendMessageBatch', function (array $arguments) use (&$batchSizes): bool { + $batchSizes[] = count($arguments['Entries']); - return true; - } - )->andReturn(new Result(['Successful' => [], 'Failed' => []])); + return true; + }, new Result(['Successful' => [], 'Failed' => []]), 2); - $queue->bulk(['a', 'b'], 'data', $this->queueName); + $queue->bulk(['a', 'b'], str_repeat('x', (int) (SqsQueue::MAX_SQS_PAYLOAD_SIZE * 0.6)), $this->queueName); $this->assertSame([1, 1], $batchSizes); } public function testBulkRaisesQueueingAndQueuedEventsForEachJob(): void { - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->with(JobQueueing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueued::class)->andReturnTrue(); + $events = Double::for(EventDispatcher::class); + $events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false); + $events->allows('hasListeners')->with(JobQueueing::class)->returns(true); + $events->allows('hasListeners')->with(JobQueued::class)->returns(true); $dispatched = []; - $events->expects('dispatch')->times(4)->andReturnUsing(function (object $event) use (&$dispatched): void { + $events->expects('dispatch')->times(4)->resolves(function (object $event) use (&$dispatched): void { $dispatched[] = $event; }); $container = new Container; $container->instance('events', $events); - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer($container); $queue->setConnectionName('sqs'); - $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); - $queue->method('createPayload')->willReturnCallback(fn (string $job): string => "payload-{$job}"); - $this->sqs->expects('sendMessageBatch')->andReturnUsing(function (array $args): Result { + $this->expectSqsCommand('sendMessageBatch', null, function (array $args): Result { $successful = array_map( fn (array $entry, int $i): array => ['Id' => $entry['Id'], 'MessageId' => 'mid-' . $i], $args['Entries'], @@ -1782,7 +1801,7 @@ public function testBulkNormalizesEnumQueueNameInEvents(): void $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer($container); $queue->setConnectionName('sqs'); - $this->sqs->expects('sendMessageBatch')->andReturn(new Result([ + $this->expectSqsCommand('sendMessageBatch', null, new Result([ 'Successful' => [['Id' => '0', 'MessageId' => 'mid-0']], 'Failed' => [], ])); @@ -1799,24 +1818,16 @@ public function testBulkHonoursPerJobDelay(): void $jobB = new FakeSqsJob; - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload', 'secondsUntil']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer(new Container); - $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); - $queue->method('createPayload')->willReturnCallback( - fn (FakeSqsJob $job, ?string $queue, mixed $data, ?int $delay): string => 'payload-' . ($delay ?? 'none') - ); - $queue->expects($this->once())->method('secondsUntil')->with(30)->willReturn(30); $captured = null; - $this->sqs->expects('sendMessageBatch')->with(m::on(function (array $args) use (&$captured): bool { + $this->expectSqsCommand('sendMessageBatch', function (array $args) use (&$captured): bool { $captured = $args; return true; - }))->andReturn(new Result(['Successful' => [], 'Failed' => []])); + }, new Result(['Successful' => [], 'Failed' => []])); $queue->bulk([$jobA, $jobB], 'data', $this->queueName); @@ -1834,18 +1845,16 @@ public function testBulkHonoursDelayAttribute(): void // Convert for the payload and DelaySeconds; standard queues need no FIFO preflight conversion. $queue->expects($this->exactly(2))->method('secondsUntil')->with(15)->willReturn(15); - $this->sqs->expects('sendMessageBatch')->withArgs( - function (array $arguments): bool { - $entry = $arguments['Entries'][0]; - $payload = json_decode($entry['MessageBody'], true, flags: JSON_THROW_ON_ERROR); + $this->expectSqsCommand('sendMessageBatch', function (array $arguments): bool { + $entry = $arguments['Entries'][0]; + $payload = json_decode($entry['MessageBody'], true, flags: JSON_THROW_ON_ERROR); - $this->assertSame(15, $entry['DelaySeconds']); - $this->assertSame(15, $payload['delay']); - $this->assertArrayNotHasKey('DelaySeconds', $arguments['Entries'][1]); + $this->assertSame(15, $entry['DelaySeconds']); + $this->assertSame(15, $payload['delay']); + $this->assertArrayNotHasKey('DelaySeconds', $arguments['Entries'][1]); - return true; - } - )->andReturn(new Result([ + return true; + }, new Result([ 'Successful' => [['Id' => '0', 'MessageId' => 'm1']], 'Failed' => [], ])); @@ -1855,15 +1864,10 @@ function (array $arguments): bool { public function testBulkThrowsWhenSqsReportsFailedEntries(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer(new Container); - $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); - $queue->expects($this->once())->method('createPayload')->willReturn('payload-a'); - $this->sqs->expects('sendMessageBatch')->andReturnUsing(function (array $args): Result { + $this->expectSqsCommand('sendMessageBatch', null, function (array $args): Result { return new Result([ 'Successful' => [], 'Failed' => [ @@ -1907,13 +1911,11 @@ public function testBulkFinalizesPayloadsBeforeSizeBasedChunking(): void static fn (string $job): string => json_encode(['uuid' => $job], JSON_THROW_ON_ERROR), ); $batchSizes = []; - $this->sqs->expects('sendMessageBatch')->times(2)->withArgs( - function (array $arguments) use (&$batchSizes): bool { - $batchSizes[] = count($arguments['Entries']); + $this->expectSqsCommand('sendMessageBatch', function (array $arguments) use (&$batchSizes): bool { + $batchSizes[] = count($arguments['Entries']); - return true; - }, - )->andReturn(new Result(['Successful' => [], 'Failed' => []])); + return true; + }, new Result(['Successful' => [], 'Failed' => []]), 2); $queue->bulk(['a', 'b'], 'data', $this->queueName); @@ -1954,13 +1956,13 @@ public static function defaultFifoQueueNames(): array public function testBulkRaisesExactEventsForSuccessfulAndRejectedEntries(): void { - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->with(JobPayloadFinalizing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueueing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueued::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueueingFailed::class)->andReturnTrue(); + $events = Double::for(EventDispatcher::class); + $events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(true); + $events->allows('hasListeners')->with(JobQueueing::class)->returns(true); + $events->allows('hasListeners')->with(JobQueued::class)->returns(true); + $events->allows('hasListeners')->with(JobQueueingFailed::class)->returns(true); $dispatched = []; - $events->shouldReceive('dispatch')->andReturnUsing( + $events->allows('dispatch')->resolves( function (object $event) use (&$dispatched): object { if ($event instanceof JobPayloadFinalizing) { $event->payload .= '-final'; @@ -1984,9 +1986,7 @@ function (object $event) use (&$dispatched): object { $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); $queue->expects($this->exactly(2))->method('createPayload')->willReturnOnConsecutiveCalls('p1', 'p2'); - $this->sqs->expects('sendMessageBatch')->withArgs( - static fn (array $arguments): bool => array_column($arguments['Entries'], 'MessageBody') === ['p1-final', 'p2-final'], - )->andReturn(new Result([ + $this->expectSqsCommand('sendMessageBatch', static fn (array $arguments): bool => array_column($arguments['Entries'], 'MessageBody') === ['p1-final', 'p2-final'], new Result([ 'Successful' => [['Id' => '0', 'MessageId' => 'successful-id']], 'Failed' => [['Id' => '1', 'Code' => 'InternalError', 'Message' => 'failed']], ])); @@ -2022,14 +2022,14 @@ public function testBulkCleansOnlyRejectedOverflowPointers(): void $acceptedPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'accepted'; $rejectedPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'rejected'; - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($acceptedPath, $firstPayload)->andReturnTrue(); - $store->expects('put')->with($rejectedPath, $secondPayload)->andReturnTrue(); - $store->expects('forget')->with($rejectedPath)->andReturnTrue(); - $store->shouldNotReceive('forget')->with($acceptedPath); + $store = Double::for(CacheRepository::class); + $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 = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); $container = new Container; $container->instance('cache', $cache); @@ -2052,7 +2052,7 @@ public function testBulkCleansOnlyRejectedOverflowPointers(): void $secondPayload, ); - $this->sqs->expects('sendMessageBatch')->andReturn(new Result([ + $this->expectSqsCommand('sendMessageBatch', null, new Result([ 'Successful' => [['Id' => '0', 'MessageId' => 'accepted-id']], 'Failed' => [['Id' => '1', 'Code' => 'Rejected', 'Message' => 'invalid', 'SenderFault' => true]], ])); @@ -2067,12 +2067,12 @@ public function testBulkRetainsOverflowPointersForServerFaultRejections(): void $payload = json_encode(['uuid' => 'ambiguous'], JSON_THROW_ON_ERROR); $path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'ambiguous'; - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($path, $payload)->andReturnTrue(); - $store->shouldNotReceive('forget'); + $store = Double::for(CacheRepository::class); + $store->expects('put')->with($path, $payload)->returns(true); + $store->expects('forget')->never(); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); $container = new Container; $container->instance('cache', $cache); @@ -2093,7 +2093,7 @@ public function testBulkRetainsOverflowPointersForServerFaultRejections(): void $queue->expects($this->once())->method('createPayload')->willReturn($payload); // An SDK retry may have resent an entry SQS already accepted before the final server fault. - $this->sqs->expects('sendMessageBatch')->andReturn(new Result([ + $this->expectSqsCommand('sendMessageBatch', null, new Result([ 'Successful' => [], 'Failed' => [['Id' => '0', 'Code' => 'InternalError', 'Message' => 'failed', 'SenderFault' => false]], ])); @@ -2110,21 +2110,21 @@ public function testBulkCleansEarlierWritesWhenAWriteFailsBeforeSending(): void $firstPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'job-1'; $secondPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'job-2'; - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($firstPath, $firstPayload)->ordered()->andReturnTrue(); - $store->expects('put')->with($secondPath, $secondPayload)->ordered()->andReturnFalse(); - $store->expects('forget')->with($firstPath)->ordered()->andReturnTrue(); - $store->expects('forget')->with($secondPath)->ordered()->andReturnTrue(); + $store = Double::for(CacheRepository::class); + $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 = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->with(JobQueueing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueueingFailed::class)->andReturnTrue(); + $events = Double::for(EventDispatcher::class); + $events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false); + $events->allows('hasListeners')->with(JobQueueing::class)->returns(true); + $events->allows('hasListeners')->with(JobQueueingFailed::class)->returns(true); $dispatched = []; - $events->shouldReceive('dispatch')->andReturnUsing( + $events->allows('dispatch')->resolves( static function (object $event) use (&$dispatched): object { $dispatched[] = $event; @@ -2154,8 +2154,6 @@ static function (object $event) use (&$dispatched): object { static fn (string $job): string => json_encode(['uuid' => "job-{$job}"], JSON_THROW_ON_ERROR), ); - $this->sqs->shouldNotReceive('sendMessageBatch'); - try { $queue->bulk(array_map('strval', range(1, 11)), 'data', $this->queueName); $this->fail('Expected overflow storage to fail.'); @@ -2187,30 +2185,30 @@ public function testBulkPreservesWriteCancellationWhileDrainingAttemptedPointers $cleanupCancellation = new RuntimeException('delete cleanup failed', previous: $cleanupCancellation); } - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->with($cleanupCancellation)->times($deleteCleanupThrows ? 1 : 0); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with($cleanupCancellation)->times($deleteCleanupThrows ? 1 : 0); Container::getInstance()->instance(ExceptionHandler::class, $handler); - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($firstPath, $firstPayload)->ordered()->andReturnTrue(); - $store->expects('put')->with($secondPath, $secondPayload)->ordered()->andThrow($cancellation); + $store = Double::for(CacheRepository::class); + $store->expects('put')->with($firstPath, $firstPayload)->ordered()->returns(true); + $store->expects('put')->with($secondPath, $secondPayload)->ordered()->throws($cancellation); if ($deleteCleanupThrows === null) { - $store->expects('forget')->with($firstPath)->ordered()->andReturnTrue(); + $store->expects('forget')->with($firstPath)->ordered()->returns(true); } else { - $store->expects('forget')->with($firstPath)->ordered()->andThrow($cleanupCancellation); + $store->expects('forget')->with($firstPath)->ordered()->throws($cleanupCancellation); } - $store->expects('forget')->with($secondPath)->ordered()->andReturnTrue(); + $store->expects('forget')->with($secondPath)->ordered()->returns(true); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->with(JobQueueing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueueingFailed::class)->never(); - $events->shouldReceive('hasListeners')->with(JobQueueingCanceled::class)->andReturnTrue(); + $events = Double::for(EventDispatcher::class); + $events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false); + $events->allows('hasListeners')->with(JobQueueing::class)->returns(true); + $events->expects('hasListeners')->with(JobQueueingFailed::class)->never(); + $events->allows('hasListeners')->with(JobQueueingCanceled::class)->returns(true); $dispatched = []; - $events->shouldReceive('dispatch')->andReturnUsing( + $events->allows('dispatch')->resolves( static function (object $event) use (&$dispatched): object { $dispatched[] = $event; @@ -2241,8 +2239,6 @@ static function (object $event) use (&$dispatched): object { $secondPayload, ); - $this->sqs->shouldNotReceive('sendMessageBatch'); - try { $queue->bulk(['a', 'b'], 'data', $this->queueName); $this->fail('Expected the overflow write cancellation to be rethrown.'); @@ -2273,14 +2269,14 @@ public function testBulkCleanupCancellationSupersedesAnOrdinaryWriteFailure(bool $cleanupCancellation = new RuntimeException('delete cleanup failed', previous: $cleanupCancellation); } - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($firstPath, $firstPayload)->ordered()->andReturnTrue(); - $store->expects('put')->with($secondPath, $secondPayload)->ordered()->andReturnFalse(); - $store->expects('forget')->with($firstPath)->ordered()->andThrow($cleanupCancellation); - $store->expects('forget')->with($secondPath)->ordered()->andReturnTrue(); + $store = Double::for(CacheRepository::class); + $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 = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); $container = new Container; $container->instance('cache', $cache); @@ -2303,8 +2299,6 @@ public function testBulkCleanupCancellationSupersedesAnOrdinaryWriteFailure(bool $secondPayload, ); - $this->sqs->shouldNotReceive('sendMessageBatch'); - try { $queue->bulk(['a', 'b'], 'data', $this->queueName); $this->fail('Expected cleanup cancellation to supersede the write failure.'); @@ -2324,20 +2318,20 @@ public function testBulkRetainsPointersAndPublishesCancellationInsteadOfFailureW $cancellation = new RuntimeException('transport cleanup failed', previous: $cancellation); } - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($path, $payload)->andReturnTrue(); - $store->shouldNotReceive('forget'); + $store = Double::for(CacheRepository::class); + $store->expects('put')->with($path, $payload)->returns(true); + $store->expects('forget')->never(); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->with(JobQueueing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueueingFailed::class)->never(); - $events->shouldReceive('hasListeners')->with(JobQueueingCanceled::class)->andReturnTrue(); + $events = Double::for(EventDispatcher::class); + $events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false); + $events->allows('hasListeners')->with(JobQueueing::class)->returns(true); + $events->expects('hasListeners')->with(JobQueueingFailed::class)->never(); + $events->allows('hasListeners')->with(JobQueueingCanceled::class)->returns(true); $dispatched = []; - $events->shouldReceive('dispatch')->andReturnUsing( + $events->allows('dispatch')->resolves( static function (object $event) use (&$dispatched): object { $dispatched[] = $event; @@ -2365,7 +2359,7 @@ static function (object $event) use (&$dispatched): object { $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); $queue->expects($this->once())->method('createPayload')->willReturn($payload); - $this->sqs->expects('sendMessageBatch')->andThrow($cancellation); + $this->expectSqsCommand('sendMessageBatch', null, $cancellation); try { $queue->bulk(['a'], 'data', $this->queueName); @@ -2388,8 +2382,8 @@ public function testBulkCleansOnlyTheCurrentChunkWhenItsOverflowWriteIsCanceled( $currentPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'job-11'; $writes = 0; - $store = m::mock(CacheRepository::class); - $store->expects('put')->times(11)->andReturnUsing( + $store = Double::for(CacheRepository::class); + $store->expects('put')->times(11)->resolves( function () use (&$writes, $cancellation): bool { if (++$writes === 11) { throw $cancellation; @@ -2398,10 +2392,10 @@ function () use (&$writes, $cancellation): bool { return true; } ); - $store->expects('forget')->with($currentPath)->andReturnTrue(); + $store->expects('forget')->with($currentPath)->returns(true); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); $container = new Container; $container->instance('cache', $cache); @@ -2423,9 +2417,7 @@ function () use (&$writes, $cancellation): bool { static fn (string $job): string => json_encode(['uuid' => "job-{$job}"], JSON_THROW_ON_ERROR) ); - $this->sqs->expects('sendMessageBatch')->andReturn( - new Result(['Successful' => [], 'Failed' => []]) - ); + $this->expectSqsCommand('sendMessageBatch', null, new Result(['Successful' => [], 'Failed' => []])); try { $queue->bulk(array_map('strval', range(1, 11)), 'data', $this->queueName); @@ -2440,19 +2432,19 @@ public function testBulkPreservesQueueingListenerCancellationBeforeWritingOverfl $payload = json_encode(['uuid' => 'listener-canceled'], JSON_THROW_ON_ERROR); $cancellation = new CanceledException; - $store = m::mock(CacheRepository::class); - $store->shouldNotReceive('put'); - $store->shouldNotReceive('forget'); + $store = Double::for(CacheRepository::class); + $store->expects('put')->never(); + $store->expects('forget')->never(); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $events = m::mock(EventDispatcher::class); - $events->expects('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse(); - $events->expects('hasListeners')->with(JobQueueing::class)->andReturnTrue(); - $events->expects('dispatch')->with(m::type(JobQueueing::class))->andThrow($cancellation); - $events->expects('hasListeners')->with(JobQueueingCanceled::class)->andReturnTrue(); - $events->expects('dispatch')->with(m::on( + $events = Double::for(EventDispatcher::class); + $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); + $events->expects('hasListeners')->with(JobQueueingCanceled::class)->returns(true); + $events->expects('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobQueueingCanceled && $event->cancellation === $cancellation && ! $event->sendAttempted, @@ -2478,8 +2470,6 @@ public function testBulkPreservesQueueingListenerCancellationBeforeWritingOverfl $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); $queue->expects($this->once())->method('createPayload')->willReturn($payload); - $this->sqs->shouldNotReceive('sendMessageBatch'); - try { $queue->bulk(['a'], 'data', $this->queueName); $this->fail('Expected the queueing listener cancellation to be rethrown.'); @@ -2490,19 +2480,19 @@ public function testBulkPreservesQueueingListenerCancellationBeforeWritingOverfl public function testBulkRetainsAmbiguousChunkPointersAndNeverWritesLaterChunks(): void { - $store = m::mock(CacheRepository::class); - $store->expects('put')->times(10)->andReturnTrue(); - $store->shouldNotReceive('forget'); + $store = Double::for(CacheRepository::class); + $store->expects('put')->times(10)->returns(true); + $store->expects('forget')->never(); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->with(JobQueueing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueueingFailed::class)->andReturnTrue(); + $events = Double::for(EventDispatcher::class); + $events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false); + $events->allows('hasListeners')->with(JobQueueing::class)->returns(true); + $events->allows('hasListeners')->with(JobQueueingFailed::class)->returns(true); $dispatched = []; - $events->shouldReceive('dispatch')->andReturnUsing( + $events->allows('dispatch')->resolves( static function (object $event) use (&$dispatched): object { $dispatched[] = $event; @@ -2532,7 +2522,7 @@ static function (object $event) use (&$dispatched): object { static fn (string $job): string => json_encode(['uuid' => "job-{$job}"], JSON_THROW_ON_ERROR) ); - $this->sqs->expects('sendMessageBatch')->andThrow(new RuntimeException('transport failed')); + $this->expectSqsCommand('sendMessageBatch', null, new RuntimeException('transport failed')); try { $queue->bulk(array_map('strval', range(1, 11)), 'data', $this->queueName); @@ -2551,21 +2541,16 @@ static function (object $event) use (&$dispatched): object { public function testBulkSendsFifoBatchesSequentiallyUsingTheQueueNameForMessageGroups(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $queue->setContainer(new Container); - $queue->expects($this->once())->method('getQueue')->with($this->fifoQueueName)->willReturn($this->fifoQueueUrl); - $queue->method('createPayload')->willReturnCallback(fn (string $job): string => "payload-{$job}"); $captured = []; - $this->sqs->expects('sendMessageBatch')->times(2)->with(m::on(function (array $args) use (&$captured): bool { + $this->expectSqsCommand('sendMessageBatch', function (array $args) use (&$captured): bool { $captured[] = $args; return true; - }))->andReturn(new Result(['Successful' => [], 'Failed' => []])); + }, new Result(['Successful' => [], 'Failed' => []]), 2); $queue->bulk(array_map('strval', range(1, 15)), 'data', $this->fifoQueueName); @@ -2577,16 +2562,11 @@ public function testBulkSendsFifoBatchesSequentiallyUsingTheQueueNameForMessageG public function testBulkStopsSendingFifoBatchesAfterAFailedRequest(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->fifoQueueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->fifoQueueName, $this->prefix); $queue->setContainer(new Container); - $queue->expects($this->once())->method('getQueue')->willReturn($this->fifoQueueUrl); - $queue->method('createPayload')->willReturnCallback(fn (string $job): string => "payload-{$job}"); // Only the first chunk is attempted; its exception propagates untouched and later chunks are not sent. - $this->sqs->expects('sendMessageBatch')->andThrow(new RuntimeException('SQS is down')); + $this->expectSqsCommand('sendMessageBatch', null, new RuntimeException('SQS is down')); $this->expectExceptionObject(new RuntimeException('SQS is down')); @@ -2603,22 +2583,15 @@ public function testBulkDefersAfterCommitJobsUntilTheTransactionCommits(): void $container = new Container; $container->instance('db.transactions', $transactions); - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer($container); - $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); - $queue->expects($this->exactly(2))->method('createPayload')->willReturnOnConsecutiveCalls('p1', 'p2'); $sent = false; - $this->sqs->expects('sendMessageBatch')->andReturnUsing( - function () use (&$sent): Result { - $sent = true; + $this->expectSqsCommand('sendMessageBatch', null, function () use (&$sent): Result { + $sent = true; - return new Result(['Successful' => [], 'Failed' => []]); - } - ); + return new Result(['Successful' => [], 'Failed' => []]); + }); $queue->bulk([$jobA, $jobB], 'data', $this->queueName); @@ -2631,26 +2604,22 @@ function () use (&$sent): Result { public function testBulkRegistersRollbackCallbacksForUniqueAfterCommitJobs(): void { - $job = new class implements ShouldQueue, ShouldBeUnique { - use Queueable; - }; + $job = new SqsQueueTestUniqueJob; $job->afterCommit = true; - DispatchLockContext::registerUnique($job, m::mock(CacheRepository::class), null, 'unique-key', 'owner'); + DispatchLockContext::registerUnique($job, Double::for(CacheRepository::class), null, 'unique-key', 'owner'); - $transactions = m::mock(DatabaseTransactionsManager::class)->makePartial(); + $transactions = Double::for(DatabaseTransactionsManager::class)->passthru(new DatabaseTransactionsManager); $transactions->begin('default', 1); $transactions->expects('addCallbackForRollback'); $transactions->expects('addCallback'); $container = new Container; $container->instance('db.transactions', $transactions); + $container->instance(EventDispatcher::class, new ConcreteEventDispatcher($container)); + Container::setInstance($container); - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer($container); - $queue->expects($this->once())->method('createPayload')->willReturn('payload-a'); $queue->bulk([$job], 'data', $this->queueName); } @@ -2660,15 +2629,15 @@ public function testBulkComputesQueueableOptionsBeforeApplyingOverflow(): void $job = (new FakeSqsJob)->onGroup('0')->withDeduplicator( static fn (string $payload): string => 'dedupe-' . $payload ); - $payload = json_encode(['uuid' => 'fifo-overflow'], JSON_THROW_ON_ERROR); - $finalPayload = json_encode(['uuid' => 'fifo-overflow', 'telemetry' => 'final'], JSON_THROW_ON_ERROR); - $path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'fifo-overflow'; + Str::createUuidsUsing(fn (): Uuid => $this->createMockedUuid($this->mockedDeduplicationId)); + $path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . $this->mockedDeduplicationId; + $finalPayload = null; - $store = m::mock(CacheRepository::class); - $store->expects('put')->with($path, $finalPayload)->andReturnTrue(); + $store = Double::for(CacheRepository::class); + $store->expects('put')->with($path, Argument::capture($finalPayload))->returns(true); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('database')->returns($store); $dispatcher = new ConcreteEventDispatcher($container = new Container); $container->instance('cache', $cache); @@ -2679,33 +2648,26 @@ public function testBulkComputesQueueableOptionsBeforeApplyingOverflow(): void $event->payload = json_encode($payload, JSON_THROW_ON_ERROR); }); - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([ - $this->sqs, - $this->fifoQueueName, - $this->prefix, - '', - false, - ['enabled' => true, 'always' => true, 'store' => 'database'], - ]) - ->getMock(); + $queue = new SqsQueue( + $this->sqs, + $this->fifoQueueName, + $this->prefix, + overflowStorage: ['enabled' => true, 'always' => true, 'store' => 'database'], + ); $queue->setContainer($container); $queue->setConnectionName('sqs'); - $queue->expects($this->once())->method('getQueue')->willReturn($this->fifoQueueUrl); - $queue->expects($this->once())->method('createPayload')->willReturn($payload); $captured = null; - $this->sqs->expects('sendMessageBatch')->withArgs( - function (array $arguments) use (&$captured): bool { - $captured = $arguments; + $this->expectSqsCommand('sendMessageBatch', function (array $arguments) use (&$captured): bool { + $captured = $arguments; - return true; - } - )->andReturn(new Result(['Successful' => [], 'Failed' => []])); + return true; + }, new Result(['Successful' => [], 'Failed' => []])); $queue->bulk([$job], 'data', $this->fifoQueueName); + $this->assertTrue($this->isPayloadOf(FakeSqsJob::class)($finalPayload)); + $this->assertSame('final', json_decode($finalPayload, true, flags: JSON_THROW_ON_ERROR)['telemetry']); $this->assertSame('0', $captured['Entries'][0]['MessageGroupId']); $this->assertSame('dedupe-' . $finalPayload, $captured['Entries'][0]['MessageDeduplicationId']); $this->assertSame( @@ -2716,31 +2678,26 @@ function (array $arguments) use (&$captured): bool { public function testBulkFiresQueuedEventsForSuccessfulChunksWhenAnotherChunkFails(): void { - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->with(JobPayloadFinalizing::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->with(JobQueueing::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueued::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobQueueingFailed::class)->andReturnFalse(); + $events = Double::for(EventDispatcher::class); + $events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false); + $events->allows('hasListeners')->with(JobQueueing::class)->returns(true); + $events->allows('hasListeners')->with(JobQueued::class)->returns(true); + $events->allows('hasListeners')->with(JobQueueingFailed::class)->returns(false); $dispatched = []; - $events->expects('dispatch')->times(25)->andReturnUsing(function (object $event) use (&$dispatched): void { + $events->expects('dispatch')->times(25)->resolves(function (object $event) use (&$dispatched): void { $dispatched[] = $event; }); $container = new Container; $container->instance('events', $events); - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer($container); $queue->setConnectionName('sqs'); - $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); - $queue->method('createPayload')->willReturnCallback(fn (string $job): string => "payload-{$job}"); $calls = 0; - $this->sqs->expects('sendMessageBatch')->times(2)->andReturnUsing(function (array $args) use (&$calls): Result { + $this->expectSqsCommand('sendMessageBatch', null, function (array $args) use (&$calls): Result { if ($calls++ === 0) { return new Result([ 'Successful' => array_map( @@ -2753,7 +2710,7 @@ public function testBulkFiresQueuedEventsForSuccessfulChunksWhenAnotherChunkFail } throw new RuntimeException('chunk failed'); - }); + }, 2); try { $queue->bulk(array_map('strval', range(1, 15)), 'data', $this->queueName); @@ -2771,15 +2728,10 @@ public function testBulkFiresQueuedEventsForSuccessfulChunksWhenAnotherChunkFail public function testBulkRethrowsTheOriginalExceptionWhenASingleBatchRequestFails(): void { - $queue = $this->getMockBuilder(SqsQueue::class) - ->onlyMethods(['getQueue', 'createPayload']) - ->setConstructorArgs([$this->sqs, $this->queueName, $this->prefix]) - ->getMock(); + $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer(new Container); - $queue->expects($this->once())->method('getQueue')->willReturn($this->queueUrl); - $queue->expects($this->once())->method('createPayload')->willReturn('payload-a'); - $this->sqs->expects('sendMessageBatch')->andThrow(new RuntimeException('SQS is down')); + $this->expectSqsCommand('sendMessageBatch', null, new RuntimeException('SQS is down')); $this->expectExceptionObject(new RuntimeException('SQS is down')); @@ -2791,8 +2743,6 @@ public function testBulkDoesNothingWithEmptyInput(): void $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix); $queue->setContainer(new Container); - $this->sqs->shouldNotReceive('sendMessageBatch'); - $this->assertNull($queue->bulk([], 'data', $this->queueName)); } @@ -2802,12 +2752,13 @@ public function testPopPassesOverflowStorageOptionsToJob(): void $path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'popped-job'; $pointer = json_encode(['@pointer' => $path], JSON_THROW_ON_ERROR); - $store = m::mock(CacheRepository::class); - $store->expects('get')->with($path)->andReturn($payload); - $cache = m::mock(CacheFactory::class); - $cache->expects('store')->with('database')->andReturn($store); - $container = m::mock(Container::class)->makePartial(); - $container->expects('make')->with('cache')->andReturn($cache); + $store = Double::for(CacheRepository::class); + $store->expects('get')->with($path)->returns($payload); + $cache = Double::for(CacheFactory::class); + $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); + $container->expects('make')->with('cache')->returns($cache); $queue = new SqsQueue( $this->sqs, @@ -2815,13 +2766,13 @@ public function testPopPassesOverflowStorageOptionsToJob(): void $this->prefix, overflowStorage: ['enabled' => true, 'store' => 'database', 'delete_after_processing' => true], ); - $queue->setContainer($container); + $queue->setContainer($container->instance()); $queue->setConnectionName('sqs'); - $this->sqs->expects('receiveMessage')->with([ + $this->expectSqsCommand('receiveMessage', [ 'QueueUrl' => $this->queueUrl, 'MessageSystemAttributeNames' => ['ApproximateReceiveCount'], - ])->andReturn(new Result([ + ], new Result([ 'Messages' => [[ 'Body' => $pointer, 'ReceiptHandle' => $this->mockedReceiptHandle, @@ -2845,3 +2796,8 @@ enum SqsQueueName: string { case Emails = 'emails'; } + +class SqsQueueTestUniqueJob implements ShouldQueue, ShouldBeUnique +{ + use Queueable; +} diff --git a/tests/Queue/QueueSyncQueueTest.php b/tests/Queue/QueueSyncQueueTest.php index 1f78dbbaf..07072a86f 100644 --- a/tests/Queue/QueueSyncQueueTest.php +++ b/tests/Queue/QueueSyncQueueTest.php @@ -33,8 +33,10 @@ use Hypervel\Queue\Jobs\SyncJob; use Hypervel\Queue\SyncQueue; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -42,6 +44,8 @@ class QueueSyncQueueTest extends TestCase { + use VerifiesDoubles; + public function testInspectionReturnsEmptyCollections(): void { $queue = new SyncQueue; @@ -135,11 +139,11 @@ public function testLifecycleEventsAreNotDispatchedWithoutListeners(): void $sync = new SyncQueue; $sync->setConnectionName('sync'); $container = $this->getContainer(); - $events = m::mock(EventDispatcher::class); - $events->expects('hasListeners')->with(JobProcessing::class)->andReturnFalse(); - $events->expects('hasListeners')->with(JobProcessed::class)->andReturnFalse(); - $events->expects('hasListeners')->with(JobAttempted::class)->andReturnFalse(); - $events->shouldReceive('dispatch')->never(); + $events = Double::for(EventDispatcher::class); + $events->expects('hasListeners')->with(JobProcessing::class)->returns(false); + $events->expects('hasListeners')->with(JobProcessed::class)->returns(false); + $events->expects('hasListeners')->with(JobAttempted::class)->returns(false); + $events->expects('dispatch')->never(); $container->instance('events', $events); $container->instance(EventDispatcher::class, $events); $sync->setContainer($container); @@ -186,7 +190,7 @@ public function testDurationIsPassedToJobEvents(): void $container = $this->getContainer(); $events = new EventsDispatcher($container); $dispatched = []; - $events->listen([JobProcessed::class, JobAttempted::class], function ($event) use (&$dispatched) { + $events->listen([JobProcessed::class, JobAttempted::class], function (JobProcessed|JobAttempted $event) use (&$dispatched): void { $dispatched[$event::class] = $event; }); $container->instance('events', $events); @@ -328,7 +332,7 @@ public function testCanceledAttemptListenerFailureIsReportedWithoutReplacingTheC throw $listenerFailure; }); $container->instance('events', $events); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class); $handler->expects('report')->with($listenerFailure); $container->instance(ExceptionHandler::class, $handler); $sync->setContainer($container); @@ -347,11 +351,11 @@ public function testWrappedCancellationDuringFailureObservationSkipsFailureAndPu $cleanupException = new RuntimeException('Failure observer cleanup failed.'); $jobFailure = new RuntimeException('Job failed.'); $gate = $this->armCurrentCoroutineCancellation(); - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->with(JobProcessing::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->with(JobExceptionOccurred::class)->andReturnTrue(); - $events->shouldReceive('hasListeners')->with(JobAttempted::class)->andReturnTrue(); - $events->expects('dispatch')->with(m::type(JobExceptionOccurred::class))->andReturnUsing(static function () use ($gate, $cleanupException): never { + $events = Double::for(EventDispatcher::class); + $events->allows('hasListeners')->with(JobProcessing::class)->returns(false); + $events->allows('hasListeners')->with(JobExceptionOccurred::class)->returns(true); + $events->allows('hasListeners')->with(JobAttempted::class)->returns(true); + $events->expects('dispatch')->with(Argument::type(JobExceptionOccurred::class))->resolves(static function () use ($gate, $cleanupException): never { try { $gate->push(true); throw new RuntimeException('Cancellation was not delivered.'); @@ -360,16 +364,16 @@ public function testWrappedCancellationDuringFailureObservationSkipsFailureAndPu throw $cleanupException; } }); - $events->expects('dispatch')->with(m::on( + $events->expects('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobAttempted && $event->canceled && $event->exception === $jobFailure, )); $container = $this->getContainer(); $container->instance('events', $events); - $job = m::mock(SyncJob::class); - $job->expects('fire')->andThrow($jobFailure); - $job->shouldNotReceive('fail'); - $sync = m::mock(SyncQueue::class)->makePartial()->shouldAllowMockingProtectedMethods(); - $sync->shouldReceive('resolveJob')->andReturn($job); + $job = Double::for(SyncJob::class); + $job->expects('fire')->throws($jobFailure); + $job->expects('fail')->never(); + $sync = Double::for(SyncQueue::class)->passthru(new SyncQueue); + $sync->allows('resolveJob')->returns($job); $sync->setConnectionName('sync'); $sync->setContainer($container); @@ -452,10 +456,10 @@ public function testItAddsATransactionCallbackForAfterCommitJobs(): void $sync = new SyncQueue; $sync->setConnectionName('sync'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->expects('addCallback')->andReturn(null); - $transactionManager->shouldNotReceive('addCallbackForRollback'); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->never(); $container->instance('db.transactions', $transactionManager); $sync->setContainer($container); @@ -467,10 +471,10 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitJobs() $sync = new SyncQueue; $sync->setConnectionName('sync'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->expects('addCallback')->andReturn(null); - $transactionManager->shouldNotReceive('addCallbackForRollback'); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->never(); $container->instance('db.transactions', $transactionManager); $sync->setContainer($container); @@ -482,10 +486,10 @@ public function testItAddsATransactionCallbackForAfterCommitUniqueJobs(): void $sync = new SyncQueue; $sync->setConnectionName('sync'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->expects('addCallback')->andReturn(null); - $transactionManager->expects('addCallbackForRollback')->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new SyncQueueAfterCommitUniqueJob; @@ -500,10 +504,10 @@ public function testItAddsATransactionRollbackCallbackForAfterCommitDebouncedJob $sync = new SyncQueue; $sync->setConnectionName('sync'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->expects('addCallback')->andReturn(null); - $transactionManager->expects('addCallbackForRollback')->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new SyncQueueAfterCommitDebouncedJob; @@ -518,10 +522,10 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitUnique $sync = new SyncQueue; $sync->setConnectionName('sync'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->expects('addCallback')->andReturn(null); - $transactionManager->expects('addCallbackForRollback')->andReturn(null); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $job = new SyncQueueAfterCommitInterfaceUniqueJob; @@ -536,10 +540,10 @@ public function testAfterCommitUniqueJobWithoutDispatchOwnershipDoesNotAddRollba $sync = new SyncQueue; $sync->setConnectionName('sync'); $container = $this->getContainer(); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->expects('addCallback')->andReturnNull(); - $transactionManager->shouldReceive('addCallbackForRollback')->never(); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback')->returns(null); + $transactionManager->expects('addCallbackForRollback')->never(); $container->instance('db.transactions', $transactionManager); $sync->setContainer($container); @@ -569,7 +573,7 @@ private function armCurrentCoroutineCancellation(): Channel protected function getContainer(): Container { $container = new Container; - $container->instance(Cache::class, m::mock(Cache::class)); + $container->instance(Cache::class, Double::for(Cache::class)); $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 ec26bdaf6..fad4c70c7 100644 --- a/tests/Queue/QueueWorkerTest.php +++ b/tests/Queue/QueueWorkerTest.php @@ -80,8 +80,10 @@ use Hypervel\Support\Testing\Fakes\ExceptionHandlerFake; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PDOException; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; @@ -99,6 +101,8 @@ class QueueWorkerTest extends TestCase { + use VerifiesDoubles; + protected EventDispatcher $events; protected ExceptionHandlerContract $exceptionHandler; @@ -162,7 +166,7 @@ public function testJobCanBeFired(): void public function testJobLifecycleEventsAreNotDispatchedWithoutListeners(): void { $this->spyEvents(); - $this->events->shouldReceive('hasListeners')->andReturnFalse(); + $this->events->allows('hasListeners')->returns(false); $job = new WorkerFakeJob(static function (WorkerFakeJob $job): void { $job->release(10); }); @@ -170,11 +174,11 @@ public function testJobLifecycleEventsAreNotDispatchedWithoutListeners(): void $this->getWorker()->process('default', $job, new WorkerOptions); $this->assertTrue($job->fired); - $this->events->shouldHaveReceived('hasListeners')->with(JobProcessing::class)->once(); - $this->events->shouldHaveReceived('hasListeners')->with(JobProcessed::class)->once(); - $this->events->shouldHaveReceived('hasListeners')->with(JobReleased::class)->once(); - $this->events->shouldHaveReceived('hasListeners')->with(JobAttempted::class)->once(); - $this->events->shouldNotHaveReceived('dispatch'); + $this->events->received('hasListeners')->with(JobProcessing::class)->times(1); + $this->events->received('hasListeners')->with(JobProcessed::class)->times(1); + $this->events->received('hasListeners')->with(JobReleased::class)->times(1); + $this->events->received('hasListeners')->with(JobAttempted::class)->times(1); + $this->events->received('dispatch')->never(); } public function testProcessingAndAttemptedEventsSurroundSuccessfulJobExecution(): void @@ -182,7 +186,7 @@ public function testProcessingAndAttemptedEventsSurroundSuccessfulJobExecution() $this->spyEvents(); $order = []; $attemptedEvent = null; - $this->events->shouldReceive('dispatch')->times(3)->andReturnUsing( + $this->events->expects('dispatch')->times(3)->resolves( function (object $event) use (&$order, &$attemptedEvent): void { if ($event instanceof JobProcessing) { $order[] = 'processing'; @@ -213,7 +217,7 @@ public function testAttemptedEventRunsAfterThrownJobExecution(): void $order = []; $attemptedEvent = null; $exception = new RuntimeException('Job failed.'); - $this->events->shouldReceive('dispatch')->times(4)->andReturnUsing( + $this->events->expects('dispatch')->times(4)->resolves( function (object $event) use (&$order, &$attemptedEvent): void { if ($event instanceof JobProcessing) { $order[] = 'processing'; @@ -303,12 +307,15 @@ public function testCancellationDuringJobExecutionEscapesWithACanceledAttemptAnd public function testCancellationDuringFailureObservationStopsReleaseAndPublishesACanceledAttempt(bool $cleanupThrows): void { $this->spyEvents(); + $this->events->allows('dispatch')->with(Argument::satisfies( + static fn (object $event): bool => ! $event instanceof JobExceptionOccurred, + )); $gate = $this->armCurrentCoroutineCancellation(); $cleanupException = new RuntimeException('Observer cleanup failed.'); - $this->events->shouldReceive('dispatch') - ->with(m::type(JobExceptionOccurred::class)) - ->once() - ->andReturnUsing(static function () use ($gate, $cleanupThrows, $cleanupException): never { + $this->events->expects('dispatch') + ->with(Argument::type(JobExceptionOccurred::class)) + ->times(1) + ->resolves(static function () use ($gate, $cleanupThrows, $cleanupException): never { try { $gate->push(true); @@ -344,20 +351,20 @@ public function testCancellationDuringFailureObservationStopsReleaseAndPublishes $this->assertInstanceOf(CanceledException::class, $caught); } $this->exceptionHandler->assertNothingReported(); - $this->events->shouldNotHaveReceived('dispatch', [m::type(JobReleasedAfterException::class)]); - $this->events->shouldHaveReceived('dispatch', [m::on( + $this->events->received('dispatch')->with(Argument::type(JobReleasedAfterException::class))->never(); + $this->events->received('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobAttempted && $event->canceled && $event->exception === $jobFailure, - )])->once(); + ))->times(1); } public function testInvalidPayloadTerminatesBeforeProcessingAndIsReportedOnce(): void { $this->spyEvents(); - $this->exceptionHandler = m::spy(ExceptionHandlerContract::class); + $this->exceptionHandler = Double::for(ExceptionHandlerContract::class); $order = []; $attemptedEvent = null; $exception = new InvalidPayloadException('Invalid queue payload.', '{invalid'); - $this->events->shouldReceive('dispatch')->times(4)->andReturnUsing( + $this->events->expects('dispatch')->times(4)->resolves( function (object $event) use (&$order, &$attemptedEvent): void { if ($event instanceof JobExceptionOccurred) { $order[] = 'exception'; @@ -369,10 +376,10 @@ function (object $event) use (&$order, &$attemptedEvent): void { } } ); - $this->exceptionHandler->shouldReceive('report') - ->once() + $this->exceptionHandler->expects('report') + ->times(1) ->with($exception) - ->andReturnUsing(function () use (&$order): void { + ->resolves(function () use (&$order): void { $order[] = 'reported'; }); @@ -388,8 +395,8 @@ function (object $event) use (&$order, &$attemptedEvent): void { $this->assertFalse($job->isReleased()); $this->assertSame($exception, $job->failedWith); $this->assertSame($exception, $attemptedEvent->exception); - $this->events->shouldNotHaveReceived('dispatch', [m::type(JobProcessing::class)]); - $this->events->shouldNotHaveReceived('dispatch', [m::type(JobProcessed::class)]); + $this->events->received('dispatch')->with(Argument::type(JobProcessing::class))->never(); + $this->events->received('dispatch')->with(Argument::type(JobProcessed::class))->never(); } public function testInvalidPayloadIsNotReportedWhenJobExceptionReportingIsDisabled(): void @@ -420,7 +427,7 @@ public function testWorkerOptionsCoroutineContextIsScopedToJob(): void ]; $seenDuringPop = []; - $this->events->shouldReceive('dispatch')->andReturnUsing(function (object $event) use (&$seenDuringPop): void { + $this->events->allows('dispatch')->resolves(function (object $event) use (&$seenDuringPop): void { if ($event instanceof JobPopping || $event instanceof JobPopped) { $seenDuringPop[$event::class] = [ CoroutineContext::get('queue.worker.test.previous'), @@ -458,10 +465,10 @@ public function testDaemonLifecycleCallbacksRunInOwnedCoroutinesWithConfiguredCo $options->coroutineContext = ['queue.worker.test' => 'configured']; CoroutineContext::set('queue.worker.test', 'owner'); - $this->events->shouldReceive('until') - ->once() - ->with(m::type(Looping::class)) - ->andReturnUsing(function () use (&$seen): null { + $this->events->expects('until') + ->times(1) + ->with(Argument::type(Looping::class)) + ->resolves(function () use (&$seen): null { $seen[Looping::class] = [ EngineCoroutine::id(), CoroutineContext::get('queue.worker.test'), @@ -469,7 +476,7 @@ public function testDaemonLifecycleCallbacksRunInOwnedCoroutinesWithConfiguredCo return null; }); - $this->events->shouldReceive('dispatch')->andReturnUsing( + $this->events->allows('dispatch')->resolves( function (object $event) use (&$seen): void { if (in_array($event::class, [ WorkerStarting::class, @@ -546,17 +553,17 @@ public function testJobPoppingEvent(): void public function testJobPopEventsAreSkippedWhenNoListenersAreRegistered(): void { $this->spyEvents(); - $this->events->shouldReceive('hasListeners')->with(JobPopping::class)->andReturn(false); - $this->events->shouldReceive('hasListeners')->with(JobPopped::class)->andReturn(false); + $this->events->allows('hasListeners')->with(JobPopping::class)->returns(false); + $this->events->allows('hasListeners')->with(JobPopped::class)->returns(false); $worker = $this->getWorker('default', ['queue' => [$job = new WorkerFakeJob]]); $worker->runNextJob('default', 'queue', new WorkerOptions); $this->assertTrue($job->fired); - $this->events->shouldNotHaveReceived('dispatch', [m::type(JobPopping::class)]); - $this->events->shouldNotHaveReceived('dispatch', [m::type(JobPopped::class)]); - $this->events->shouldHaveReceived('dispatch')->with(m::type(JobProcessing::class))->once(); - $this->events->shouldHaveReceived('dispatch')->with(m::type(JobProcessed::class))->once(); + $this->events->received('dispatch')->with(Argument::type(JobPopping::class))->never(); + $this->events->received('dispatch')->with(Argument::type(JobPopped::class))->never(); + $this->events->received('dispatch')->with(Argument::type(JobProcessing::class))->times(1); + $this->events->received('dispatch')->with(Argument::type(JobProcessed::class))->times(1); } public function testWorkerCanMonitorTimeoutJobs(): void @@ -631,8 +638,8 @@ public function testTimeoutMonitorUsesTheDefaultErrorExitAndTimedOutReason(?int $worker = new KillTestWorker(...$this->workerDependencies(timer: $timer)); $worker->currentTime = 100; $options = new WorkerOptions(timeout: 5); - $job = m::mock(WorkerContractOnlyJob::class)->makePartial(); - $job->shouldReceive('timeout')->andReturn($jobTimeout); + $job = Double::for(WorkerContractOnlyJob::class)->passthru(new WorkerContractOnlyJob); + $job->allows('timeout')->returns($jobTimeout); $this->registerRunningJob($worker, $job, $options); $worker->startMonitorForTest($options); $worker->currentTime = 100 + $expectedTimeout; @@ -673,7 +680,7 @@ public function testNonKillingTimeoutUnwindsAndRetriesOnlyTheExpiredJob(bool $li $otherGate = new Channel(1); $unwound = false; $cancellation = null; - $expired = m::mock(WorkerFakeJob::class, [static function () use ($expiredGate, &$unwound, &$cancellation, $catchCancellation): void { + $expired = Double::for(WorkerFakeJob::class)->passthru(new WorkerFakeJob(static function () use ($expiredGate, &$unwound, &$cancellation, $catchCancellation): void { try { $expiredGate->pop(); } catch (CanceledException $exception) { @@ -685,13 +692,13 @@ public function testNonKillingTimeoutUnwindsAndRetriesOnlyTheExpiredJob(bool $li } finally { $unwound = true; } - }])->makePartial(); - $expired->shouldReceive('timeout')->andReturn(5); + })); + $expired->allows('timeout')->returns(5); $expired->maxExceptions = 2; $expired->payload = ['countCrashesAsExceptions' => true]; $expired->backoff = 7; - $other = m::mock(WorkerFakeJob::class, [static fn (): mixed => $otherGate->pop()])->makePartial(); - $other->shouldReceive('timeout')->andReturn(0); + $other = Double::for(WorkerFakeJob::class)->passthru(new WorkerFakeJob(static fn (): mixed => $otherGate->pop())); + $other->allows('timeout')->returns(0); $worker = new KillTestWorker(...$this->workerDependencies('default', ['queue' => [$expired, $other]], timer: $timer)); $worker->setCache($cache = new Repository(new WorkerArrayStore)); $worker->currentTime = 100; @@ -700,7 +707,7 @@ public function testNonKillingTimeoutUnwindsAndRetriesOnlyTheExpiredJob(bool $li $listenerException = new RuntimeException('Timeout listener failed.'); if ($listenerThrows) { - $this->events->shouldReceive('dispatch')->with(m::type(JobTimedOut::class))->andThrow($listenerException); + $this->events->allows('dispatch')->with(Argument::type(JobTimedOut::class))->throws($listenerException); } $coroutines = []; @@ -734,14 +741,14 @@ public function testNonKillingTimeoutUnwindsAndRetriesOnlyTheExpiredJob(bool $li Coroutine::join($coroutines, 5); $this->assertSame([], $worker->runningJobsForTest()); - $this->events->shouldHaveReceived('dispatch')->with(m::on( + $this->events->received('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobAttempted && $event->job === $expired && $event->exception instanceof TimeoutExceededException - ))->once(); - $this->events->shouldHaveReceived('dispatch')->with(m::on( + ))->times(1); + $this->events->received('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobProcessed && $event->job === $other - ))->once(); - $this->events->shouldNotHaveReceived('dispatch', [m::type(WorkerStopping::class)]); + ))->times(1); + $this->events->received('dispatch')->with(Argument::type(WorkerStopping::class))->never(); $this->exceptionHandler->assertReportedCount($listenerThrows ? 2 : 1); $this->exceptionHandler->assertReported(TimeoutExceededException::class); if ($listenerThrows) { @@ -761,16 +768,19 @@ public function testKilledAttemptListenerFailurePropagatesOnlyWhenNothingIsUnwin Worker::$killOnTimeout = true; Worker::$pausable = false; $this->spyEvents(); + $this->events->allows('dispatch')->with(Argument::satisfies( + static fn (object $event): bool => ! $event instanceof JobAttempted, + )); $listenerFailure = new RuntimeException('Attempt listener failed.'); - $this->events->shouldReceive('dispatch') - ->with(m::on(static fn (object $event): bool => $event instanceof JobAttempted + $this->events->expects('dispatch') + ->with(Argument::satisfies(static fn (object $event): bool => $event instanceof JobAttempted && $event->canceled && $event->exception instanceof TimeoutExceededException)) - ->once() - ->andThrow($listenerFailure); + ->times(1) + ->throws($listenerFailure); $timer = new QueueWorkerTimer; $gate = new Channel(1); - $job = m::mock(WorkerFakeJob::class, [static function () use ($gate, $bodyReturns): void { + $job = Double::for(WorkerFakeJob::class)->passthru(new WorkerFakeJob(static function () use ($gate, $bodyReturns): void { try { $gate->pop(5); } catch (CanceledException $cancellation) { @@ -778,8 +788,8 @@ public function testKilledAttemptListenerFailurePropagatesOnlyWhenNothingIsUnwin throw $cancellation; } } - }])->makePartial(); - $job->shouldReceive('timeout')->andReturn(5); + })); + $job->allows('timeout')->returns(5); $worker = new KillTestWorker(...$this->workerDependencies('default', ['queue' => [$job]], timer: $timer)); $worker->setCache(new Repository(new WorkerArrayStore)); $worker->currentTime = 100; @@ -836,10 +846,10 @@ public function testNonKillingTimeoutHandlesCleanupAndReportingFailures(bool $re $errorLog = null; if ($reportingMode !== 'normal') { $errorLog = $this->captureErrorLog(); - $this->exceptionHandler = m::mock(ExceptionHandlerContract::class); + $this->exceptionHandler = Double::for(ExceptionHandlerContract::class); $report = $this->exceptionHandler->expects('report')->with($cleanupException); if ($reportingMode === 'cancellation') { - $report->andReturnUsing(function () use ($reportingFailure): never { + $report->resolves(function () use ($reportingFailure): never { try { $this->armCurrentCoroutineCancellation()->push(true); @@ -849,20 +859,21 @@ public function testNonKillingTimeoutHandlesCleanupAndReportingFailures(bool $re } }); } else { - $report->andThrow($reportingMode === 'original' ? $cleanupException : $reportingFailure); - $this->exceptionHandler->expects('report')->with(m::type(TimeoutExceededException::class)); + $report->throws($reportingMode === 'original' ? $cleanupException : $reportingFailure); + $this->exceptionHandler->expects('report')->with(Argument::type(TimeoutExceededException::class)); } } $command = new class { use InteractsWithQueue; }; - $limiter = m::mock(Limiter::class); - $limiter->expects('inspect')->with(m::type(Limit::class))->andReturn(new LimitResult(true, 10, 10, 0, 0)); - $limiter->shouldNotReceive('consume', 'clear'); - $rateLimiter = m::mock(RateLimiter::class); - $rateLimiter->expects('store')->with(null)->andReturn($limiter); - $this->container->instance(RateLimiter::class, $rateLimiter); - $job = m::mock(WorkerFakeJob::class, [static function () use ($command, $gate, $cleanupException): void { + $limiter = Double::for(Limiter::class); + $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->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 { (new ThrottlesExceptions)->handle($command, static function () use ($gate, $cleanupException): void { try { $gate->pop(5); @@ -871,9 +882,9 @@ public function testNonKillingTimeoutHandlesCleanupAndReportingFailures(bool $re throw $cleanupException; } }); - }])->makePartial(); + })); $command->setJob($job); - $job->shouldReceive('timeout')->andReturn(5); + $job->allows('timeout')->returns(5); $job->shouldFailOnTimeout = true; $job->maxExceptions = 3; $worker = new KillTestWorker(...$this->workerDependencies('default', ['queue' => [$job]], timer: $timer)); @@ -966,12 +977,12 @@ public function testNonKillingTimeoutDoesNotInterruptPostExecutionListeners(bool $events->listen(JobTimedOut::class, static function (JobTimedOut $event) use (&$timedOut): void { $timedOut[] = $event; }); - $job = m::mock(WorkerFakeJob::class, [static function () use ($throws, $failure): void { + $job = Double::for(WorkerFakeJob::class)->passthru(new WorkerFakeJob(static function () use ($throws, $failure): void { if ($throws) { throw $failure; } - }])->makePartial(); - $job->shouldReceive('timeout')->andReturn(5); + })); + $job->allows('timeout')->returns(5); $job->shouldFailOnTimeout = $failOnTimeout; $job->attempts = 1; $job->maxExceptions = 3; @@ -1024,7 +1035,7 @@ public function testTimeoutScanDoesNotCancelCompletedCleanupOrTimeoutAnotherFini $cleanupGate = new Channel(1); $cleanupStarted = false; $cleanupFinished = false; - $first = m::mock(WorkerFakeJob::class, [static function (WorkerFakeJob $job) use ($firstGate, $cleanupGate, &$cleanupStarted, &$cleanupFinished): void { + $first = Double::for(WorkerFakeJob::class)->passthru(new WorkerFakeJob(static function (WorkerFakeJob $job) use ($firstGate, $cleanupGate, &$cleanupStarted, &$cleanupFinished): void { Coroutine::defer(static function () use ($cleanupGate, &$cleanupStarted, &$cleanupFinished): void { $cleanupStarted = true; $cleanupGate->pop(); @@ -1032,23 +1043,23 @@ public function testTimeoutScanDoesNotCancelCompletedCleanupOrTimeoutAnotherFini }); $firstGate->pop(); $job->delete(); - }])->makePartial(); - $first->shouldReceive('timeout')->andReturn(5); - $second = m::mock(WorkerFakeJob::class, [static fn (): mixed => $secondGate->pop()])->makePartial(); - $second->shouldReceive('timeout')->andReturn(5); + })); + $first->allows('timeout')->returns(5); + $second = Double::for(WorkerFakeJob::class)->passthru(new WorkerFakeJob(static fn (): mixed => $secondGate->pop())); + $second->allows('timeout')->returns(5); $worker = new KillTestWorker(...$this->workerDependencies('default', ['queue' => [$first, $second]], timer: $timer)); $worker->currentTime = 100; $options = new WorkerOptions; $worker->startMonitorForTest($options); - $interruptible = m::mock(Interruptible::class); - $interruptible->expects('interrupted')->with(SIGALRM)->andReturnUsing( + $interruptible = Double::for(Interruptible::class); + $interruptible->expects('interrupted')->with(SIGALRM)->resolves( static function () use ($firstGate, $secondGate): void { $firstGate->push(true); $secondGate->push(true); } ); - $handler = m::mock(CallQueuedHandler::class); - $handler->expects('getRunningCommand')->andReturn($interruptible); + $handler = Double::for(CallQueuedHandler::class); + $handler->expects('getRunningCommand')->returns($interruptible); $first->resolvedJob = $handler; $coroutines = []; @@ -1068,17 +1079,17 @@ static function () use ($firstGate, $secondGate): void { $cleanupGate->push(true); Coroutine::join($coroutines, 5); $this->assertTrue($cleanupFinished); - $this->events->shouldHaveReceived('dispatch')->with(m::on( + $this->events->received('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobProcessed && $event->job === $second - ))->once(); - $this->events->shouldHaveReceived('dispatch')->with(m::on( + ))->times(1); + $this->events->received('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobAttempted && $event->job === $first && $event->exception instanceof TimeoutExceededException && ! $event->successful() - ))->once(); - $this->events->shouldHaveReceived('dispatch')->with(m::on( + ))->times(1); + $this->events->received('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof JobAttempted && $event->job === $second && $event->successful() - ))->once(); + ))->times(1); $this->exceptionHandler->assertNothingReported(); } finally { $firstGate->close(); @@ -1095,8 +1106,8 @@ public function testTimeoutMonitorRunsInAnOwnedCoroutineWithWorkerContextAndStop $callbackCoroutineIds = []; $contextValues = []; $completed = new Channel(1); - $logger = m::mock(LoggerInterface::class); - $logger->shouldReceive('error')->once()->andReturnUsing( + $logger = Double::for(LoggerInterface::class); + $logger->expects('error')->times(1)->resolves( static fn (string $message): bool => $completed->push($message), ); $timer = new Timer($logger); @@ -1107,7 +1118,7 @@ public function testTimeoutMonitorRunsInAnOwnedCoroutineWithWorkerContextAndStop $this->registerRunningJob($worker, new WorkerContractOnlyJob, $options); $worker->currentTime = 105; - $this->events->shouldReceive('dispatch')->andReturnUsing( + $this->events->allows('dispatch')->resolves( function (object $event) use (&$callbackCoroutineIds, &$contextValues): void { if ($event instanceof JobTimedOut || $event instanceof WorkerStopping) { $callbackCoroutineIds[] = EngineCoroutine::id(); @@ -1129,19 +1140,19 @@ function (object $event) use (&$callbackCoroutineIds, &$contextValues): void { $this->assertSame($callbackCoroutineIds[0], $callbackCoroutineIds[1]); $this->assertNotSame($ownerCoroutineId, $callbackCoroutineIds[0]); $this->assertSame(['configured', 'configured'], $contextValues); - $this->events->shouldHaveReceived('dispatch')->with(m::on( + $this->events->received('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof WorkerStopping && $event->connectionName === 'default' && $event->queue === 'queue' && $event->status === Worker::EXIT_ERROR && $event->terminatesImmediately - ))->once(); + ))->times(1); } public function testTimeoutLifecycleEventsAreNotDispatchedWithoutListeners(): void { $this->spyEvents(); - $this->events->shouldReceive('hasListeners')->andReturnFalse(); + $this->events->allows('hasListeners')->returns(false); $timer = new QueueWorkerTimer; $worker = new KillTestWorker(...$this->workerDependencies(timer: $timer)); $worker->currentTime = 100; @@ -1157,9 +1168,9 @@ public function testTimeoutLifecycleEventsAreNotDispatchedWithoutListeners(): vo $this->assertSame(Worker::EXIT_ERROR, $exception->status); } - $this->events->shouldHaveReceived('hasListeners')->with(JobTimedOut::class)->once(); - $this->events->shouldHaveReceived('hasListeners')->with(WorkerStopping::class)->once(); - $this->events->shouldNotHaveReceived('dispatch'); + $this->events->received('hasListeners')->with(JobTimedOut::class)->times(1); + $this->events->received('hasListeners')->with(WorkerStopping::class)->times(1); + $this->events->received('dispatch')->never(); } #[TestWith(['failed callback', false])] @@ -1182,8 +1193,8 @@ public function testTimeoutHandlingErrorsDoNotAbandonOtherAttempts(string $failu $errorLog = null; if ($reportingThrows) { $errorLog = $this->captureErrorLog(); - $this->exceptionHandler = m::mock(ExceptionHandlerContract::class); - $this->exceptionHandler->expects('report')->with($error)->andThrow(new RuntimeException('Reporting failed.')); + $this->exceptionHandler = Double::for(ExceptionHandlerContract::class); + $this->exceptionHandler->expects('report')->with($error)->throws(new RuntimeException('Reporting failed.')); } $timer = new QueueWorkerTimer; $worker = new KillTestWorker(...$this->workerDependencies(timer: $timer)); @@ -1207,14 +1218,16 @@ public function testTimeoutHandlingErrorsDoNotAbandonOtherAttempts(string $failu try { foreach (['first', 'second'] as $name) { $gates[] = $gate = new Channel(1); - $job = m::mock(WorkerLifecycleJob::class, [ - $this->container, static fn (): mixed => $gate->pop(5), 5, - ])->makePartial(); - $job->shouldReceive('uuid')->andReturn($name); - $job->shouldReceive('getResolvedJob')->andReturnNull(); - $job->shouldReceive('shouldFailOnTimeout')->andReturn($name === 'second' || $failurePhase === 'failed callback'); + $job = Double::for(WorkerLifecycleJob::class)->passthru(new WorkerLifecycleJob( + $this->container, + static fn (): mixed => $gate->pop(5), + 5, + )); + $job->allows('uuid')->returns($name); + $job->allows('getResolvedJob')->returns(null); + $job->allows('shouldFailOnTimeout')->returns($name === 'second' || $failurePhase === 'failed callback'); if ($name === 'first' && $failurePhase === 'failed callback') { - $job->shouldAllowMockingProtectedMethods()->expects('failed')->andThrow($error); + $job->expects('failed')->throws($error); } $jobs[] = $job; $coroutines[] = Coroutine::create(static function () use ($worker, $job, $options, &$unexpected): void { @@ -1533,11 +1546,11 @@ public function testTimeoutWaitsWithoutPollingAndWinsOverNormalShutdown(): void $timer = new QueueWorkerTimer; $gate = new Channel(1); $started = new Channel(1); - $job = m::mock(WorkerFakeJob::class, [static function () use ($gate, $started): void { + $job = Double::for(WorkerFakeJob::class)->passthru(new WorkerFakeJob(static function () use ($gate, $started): void { $started->push(true); $gate->pop(5); - }])->makePartial(); - $job->shouldReceive('timeout')->andReturn(1); + })); + $job->allows('timeout')->returns(1); $worker = new class(...$this->workerDependencies('default', ['queue' => [$job]], timer: $timer)) extends KillTestWorker { /** * Keep real yielding waits while recording the pending-timeout delay. @@ -1691,9 +1704,9 @@ protected function currentMemoryUsage(): float public function testDaemonShouldRunSkipsLoopingEventWhenNoListenersAreRegistered(): void { - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(Looping::class)->andReturn(false); - $events->shouldNotReceive('until'); + $events = Double::for(EventDispatcher::class); + $events->expects('hasListeners')->times(1)->with(Looping::class)->returns(false); + $events->expects('until')->never(); $worker = new LoopAwareWorker( new WorkerFakeManager('default', new WorkerFakeConnection('default', [])), @@ -1708,14 +1721,14 @@ public function testDaemonShouldRunSkipsLoopingEventWhenNoListenersAreRegistered public function testLoopingEventCarriesWorkerOptions(): void { $options = new WorkerOptions; - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(Looping::class)->andReturn(true); - $events->shouldReceive('until')->once()->with(m::on( + $events = Double::for(EventDispatcher::class); + $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 && $event->connectionName === 'default' && $event->queue === 'queue' && $event->workerOptions === $options - ))->andReturnFalse(); + ))->returns(false); $worker = new LoopAwareWorker( new WorkerFakeManager('default', new WorkerFakeConnection('default', [])), @@ -1729,8 +1742,8 @@ public function testLoopingEventCarriesWorkerOptions(): void public function testForcedWorkerDoesNotCheckMaintenanceMode(): void { - $events = m::mock(EventDispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(Looping::class)->andReturn(false); + $events = Double::for(EventDispatcher::class); + $events->expects('hasListeners')->times(1)->with(Looping::class)->returns(false); $worker = new LoopAwareWorker( new WorkerFakeManager('default', new WorkerFakeConnection('default', [])), @@ -1746,14 +1759,14 @@ public function testQueuePauseEventsTrackOnlyTheCurrentSelection(): void { $this->spyEvents(); $paused = ['emails']; - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->with('first')->andReturn( + $manager = Double::for(QueueManager::class); + $manager->allows('connection')->with('first')->returns( new WorkerFakeConnection('first', ['emails' => [], 'default' => []]), ); - $manager->shouldReceive('connection')->with('second')->andReturn( + $manager->allows('connection')->with('second')->returns( new WorkerFakeConnection('second', ['emails' => []]), ); - $manager->shouldReceive('getPausedQueues')->andReturnUsing( + $manager->allows('getPausedQueues')->resolves( static function (array $queues, string $connection) use (&$paused): array { return $connection === 'first' ? array_values(array_intersect($queues, $paused)) @@ -1761,10 +1774,10 @@ static function (array $queues, string $connection) use (&$paused): array { }, ); $worker = new InsomniacWorker($manager, $this->events, $this->exceptionHandler, static fn (): bool => false); - $worker->setCache(m::mock(CacheContract::class)); + $worker->setCache(Double::for(CacheContract::class)); $options = new WorkerOptions(sleep: 0); $observed = []; - $this->events->shouldReceive('dispatch')->andReturnUsing(function (object $event) use (&$observed): void { + $this->events->allows('dispatch')->resolves(function (object $event) use (&$observed): void { if ($event instanceof WorkerQueuePaused || $event instanceof WorkerQueueResumed) { $observed[] = [$event::class, $event->connectionName, $event->queue]; } @@ -1795,42 +1808,46 @@ static function (array $queues, string $connection) use (&$paused): array { public function testPauseHistoryIsRetainedWithoutEventListeners(): void { $this->spyEvents(); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->with('default')->andReturn( + $manager = Double::for(QueueManager::class); + $manager->allows('connection')->with('default')->returns( new WorkerFakeConnection('default', ['queue' => []]), ); - $manager->shouldReceive('getPausedQueues')->with(['queue'], 'default')->andReturn(['queue'], []); + $manager->allows('getPausedQueues')->with(['queue'], 'default')->returns(['queue'], []); $listening = false; - $this->events->shouldReceive('hasListeners')->andReturnUsing( + $dispatched = []; + $this->events->allows('dispatch')->resolves(static function (object $event) use (&$dispatched): void { + $dispatched[] = $event; + }); + $this->events->allows('hasListeners')->resolves( static function (string $event) use (&$listening): bool { return $listening && $event === WorkerQueueResumed::class; }, ); $worker = new InsomniacWorker($manager, $this->events, $this->exceptionHandler, static fn (): bool => false); - $worker->setCache(m::mock(CacheContract::class)); + $worker->setCache(Double::for(CacheContract::class)); $worker->runNextJob('default', 'queue', new WorkerOptions(sleep: 0)); - $this->events->shouldNotHaveReceived('dispatch'); + $this->assertSame([], $dispatched); $listening = true; $worker->runNextJob('default', 'queue', new WorkerOptions(sleep: 0)); - $this->events->shouldHaveReceived('dispatch')->with(m::on( + $this->events->received('dispatch')->with(Argument::satisfies( static fn (object $event): bool => $event instanceof WorkerQueueResumed && $event->connectionName === 'default' && $event->queue === 'queue', - ))->once(); + ))->times(1); } public function testEachDaemonRunReportsInitiallyPausedQueues(): void { - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->with('default')->andReturn( + $manager = Double::for(QueueManager::class); + $manager->allows('connection')->with('default')->returns( new WorkerFakeConnection('default', ['queue' => []]), ); - $manager->shouldReceive('getPausedQueues')->with(['queue'], 'default')->andReturn(['queue']); - $cache = m::mock(CacheContract::class); - $cache->shouldReceive('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY)->andReturn(null); + $manager->allows('getPausedQueues')->with(['queue'], 'default')->returns(['queue']); + $cache = Double::for(CacheContract::class); + $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); $options = new WorkerOptions(sleep: 0, stopWhenEmpty: true, memory: 1024); @@ -1894,8 +1911,8 @@ public function testExceptionIsReportedIfConnectionThrowsExceptionOnJobPop(bool $e = new RuntimeException('Pop failed.'); if ($reportingThrows) { $this->captureErrorLog(); - $this->exceptionHandler = m::mock(ExceptionHandlerContract::class); - $this->exceptionHandler->expects('report')->with($e)->andThrow(new RuntimeException('Reporting failed.')); + $this->exceptionHandler = Double::for(ExceptionHandlerContract::class); + $this->exceptionHandler->expects('report')->with($e)->throws(new RuntimeException('Reporting failed.')); } $worker = new InsomniacWorker( new WorkerFakeManager('default', new BrokenQueueConnection('default', $e)), @@ -2035,9 +2052,9 @@ public function testReleasedAttemptReportsItsErrorWithoutAnotherOutcome(string $ } }; if ($scenario === 'do not retry') { - $this->exceptionHandler = m::mock(ShouldntRetryExceptionHandler::class)->makePartial(); + $this->exceptionHandler = Double::for(ShouldntRetryExceptionHandler::class)->passthru(new ShouldntRetryExceptionHandler); $this->exceptionHandler->expects('report')->with($exception); - $this->exceptionHandler->shouldNotReceive('shouldStopRetries'); + $this->exceptionHandler->expects('shouldStopRetries')->never(); } $worker = $this->getWorker('default', ['queue' => [$job]]); $cache = new Repository(new WorkerArrayStore); @@ -2417,27 +2434,26 @@ public function testTimeoutPoliciesWaitForTheInterruptionHandlerOutcome(bool $bo $bodyFailure = new RuntimeException('Body failed during notification.'); $caught = null; $notificationStarted = false; - $job = m::mock(WorkerFakeJob::class, [static function () use ($bodyGate, $bodyThrows, $bodyFailure): void { + $job = Double::for(WorkerFakeJob::class)->passthru(new WorkerFakeJob(static function () use ($bodyGate, $bodyThrows, $bodyFailure): void { $bodyGate->pop(); if ($bodyThrows) { throw $bodyFailure; } - }])->makePartial(); - $job->shouldReceive('timeout')->andReturn(5); - $job->shouldReceive($outcome)->once()->passthru(); - $job->shouldNotReceive($outcome === 'release' ? 'delete' : 'release'); + })); + $job->allows('timeout')->returns(5); + $job->expects($outcome === 'release' ? 'delete' : 'release')->never(); $job->shouldFailOnTimeout = true; $job->maxExceptions = 2; - $interruptible = m::mock(Interruptible::class); - $interruptible->expects('interrupted')->with(SIGALRM)->andReturnUsing( + $interruptible = Double::for(Interruptible::class); + $interruptible->expects('interrupted')->with(SIGALRM)->resolves( static function () use ($notificationGate, &$notificationStarted, $job, $outcome): void { $notificationStarted = true; $notificationGate->pop(); $job->{$outcome}(); } ); - $handler = m::mock(CallQueuedHandler::class); - $handler->expects('getRunningCommand')->andReturn($interruptible); + $handler = Double::for(CallQueuedHandler::class); + $handler->expects('getRunningCommand')->returns($interruptible); $job->resolvedJob = $handler; $worker = new KillTestWorker(...$this->workerDependencies('default', ['queue' => [$job]], timer: $timer)); $worker->setCache($cache = new Repository(new WorkerArrayStore)); @@ -2476,6 +2492,7 @@ static function () use ($notificationGate, &$notificationStarted, $job, $outcome $notificationGate->push(true); Coroutine::join([$bodyId, $monitorId], 5); + $job->received($outcome)->times(1); $this->assertSame($outcome === 'release', $job->isReleased()); $this->assertSame($outcome === 'delete', $job->isDeleted()); $this->assertFalse($job->hasFailed()); @@ -2534,17 +2551,17 @@ public function testInterruptedReleaseSerializesMarkerCleanupWithTheFinishingBod throw new RuntimeException('The next attempt was not allowed to finish.'); } }); - $first = m::mock(WorkerLifecycleJob::class, [$this->container, static function () use ($releaseGate, $releaseStarted): void { + $first = Double::for(WorkerLifecycleJob::class)->passthru(new WorkerLifecycleJob($this->container, static function () use ($releaseGate, $releaseStarted): void { if (! $releaseGate->pop(5)) { throw new RuntimeException('The first attempt was not allowed to release.'); } $releaseStarted->push(true); - }, 5])->makePartial(); - $interruptible = m::mock(Interruptible::class); - $interruptible->expects('interrupted')->with(SIGALRM)->andReturnUsing(static fn (): mixed => $first->release()); - $handler = m::mock(CallQueuedHandler::class); - $handler->expects('getRunningCommand')->andReturn($interruptible); - $first->shouldReceive('getResolvedJob')->andReturn($handler); + }, 5)); + $interruptible = Double::for(Interruptible::class); + $interruptible->expects('interrupted')->with(SIGALRM)->resolves(static fn (): mixed => $first->release()); + $handler = Double::for(CallQueuedHandler::class); + $handler->expects('getRunningCommand')->returns($interruptible); + $first->allows('getResolvedJob')->returns($handler); $first->onReleased = static function () use (&$handedOff, &$coroutines, &$failures, $worker, $next): void { $handedOff = true; $coroutines[] = Coroutine::create(static function () use ($worker, $next, &$failures): void { @@ -2600,15 +2617,15 @@ public function testInterruptedReleaseSerializesMarkerCleanupWithTheFinishingBod public function testCrashCountingRejectsJobsWithoutLifecycleCallbacksBeforeExecution(): void { - $job = m::mock(WorkerContractOnlyJob::class)->makePartial(); - $job->shouldReceive('payload')->andReturn(['countCrashesAsExceptions' => true]); - $job->shouldReceive('uuid')->andReturn('unsupported'); - $job->shouldReceive('maxExceptions')->andReturn(2); - $job->expects('fail')->with(m::on(static fn (Throwable $exception): bool => $exception instanceof LogicException + $job = Double::for(WorkerContractOnlyJob::class)->passthru(new WorkerContractOnlyJob); + $job->allows('payload')->returns(['countCrashesAsExceptions' => true]); + $job->allows('uuid')->returns('unsupported'); + $job->allows('maxExceptions')->returns(2); + $job->expects('fail')->with(Argument::satisfies(static fn (Throwable $exception): bool => $exception instanceof LogicException && str_contains($exception->getMessage(), JobLifecycleCallbacks::class))); - $job->shouldReceive('hasFailed')->andReturnTrue(); - $job->shouldNotReceive('fire'); - $job->shouldNotReceive('release'); + $job->allows('hasFailed')->returns(true); + $job->expects('fire')->never(); + $job->expects('release')->never(); $worker = $this->getWorker()->setCache($cache = new Repository(new WorkerArrayStore)); @@ -2652,10 +2669,10 @@ public function testJobIsFailedWhenTheMaxExceptionsCounterReachesTheLimit(): voi $exception = new RuntimeException('Job failed.'); $job = new WorkerFakeJob; $job->maxExceptions = 3; - $cache = m::mock(CacheContract::class); - $cache->expects('get')->with('job-exceptions:' . $job->uuid)->andReturnTrue(); - $cache->expects('increment')->with('job-exceptions:' . $job->uuid)->andReturn(3); - $cache->expects('forget')->with('job-exceptions:' . $job->uuid)->andReturnTrue(); + $cache = Double::for(CacheContract::class); + $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); $worker = $this->getWorker()->setCache($cache); $worker->markJobAsFailedIfWillExceedMaxExceptionsForTest($job, $exception); @@ -2669,10 +2686,10 @@ public function testBooleanMaxExceptionsCounterResultsDoNotFailTheJob(): void $exception = new RuntimeException('Job failed.'); $job = new WorkerFakeJob; $job->maxExceptions = 0; - $cache = m::mock(CacheContract::class); - $cache->expects('get')->with('job-exceptions:' . $job->uuid)->andReturnTrue(); - $cache->expects('increment')->with('job-exceptions:' . $job->uuid)->andReturn($counterResult); - $cache->shouldNotReceive('forget'); + $cache = Double::for(CacheContract::class); + $cache->expects('get')->with('job-exceptions:' . $job->uuid)->returns(true); + $cache->expects('increment')->with('job-exceptions:' . $job->uuid)->returns($counterResult); + $cache->expects('forget')->never(); $worker = $this->getWorker()->setCache($cache); $worker->markJobAsFailedIfWillExceedMaxExceptionsForTest($job, $exception); @@ -2889,12 +2906,12 @@ public function testStoppingListenerFailureCannotPreventTheKillCallbackOrTermina { $failure = new RuntimeException('The stopping listener failed.'); $this->spyEvents(); - $this->events->shouldReceive('dispatch')->once()->with(m::type(WorkerStopping::class))->andThrow($failure); - $this->exceptionHandler = m::mock(ExceptionHandlerContract::class); - $report = $this->exceptionHandler->shouldReceive('report')->once()->with($failure); + $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); if ($reportingThrows) { $this->captureErrorLog(); - $report->andThrow(new RuntimeException('Reporting failed.')); + $report->throws(new RuntimeException('Reporting failed.')); } $callbackStatus = null; @@ -2979,8 +2996,8 @@ public function testWorkerStopsWithLostConnectionReason(Throwable $failure, bool { if ($reportingThrows) { $this->captureErrorLog(); - $this->exceptionHandler = m::mock(ExceptionHandlerContract::class); - $this->exceptionHandler->expects('report')->with($failure)->andThrow(new RuntimeException('Reporting failed.')); + $this->exceptionHandler = Double::for(ExceptionHandlerContract::class); + $this->exceptionHandler->expects('report')->with($failure)->throws(new RuntimeException('Reporting failed.')); } $workerOptions = new WorkerOptions(stopWhenEmpty: true); $worker = $this->getWorker('default', ['queue' => [ @@ -3127,8 +3144,8 @@ public function interrupted(int $signal): void } }; - $handler = m::mock(CallQueuedHandler::class); - $handler->expects('getRunningCommand')->andReturn($interruptible); + $handler = Double::for(CallQueuedHandler::class); + $handler->expects('getRunningCommand')->returns($interruptible); $job = new WorkerFakeJob; $job->resolvedJob = $handler; @@ -3180,8 +3197,8 @@ public function interrupted(int $signal): void $this->releaseJob->push(true); } }; - $handler = m::mock(CallQueuedHandler::class); - $handler->expects('getRunningCommand')->andReturn($interruptible); + $handler = Double::for(CallQueuedHandler::class); + $handler->expects('getRunningCommand')->returns($interruptible); $job = new WorkerFakeJob(function () use (&$worker, $options, $releaseJob): void { $worker->handleInterruptionSignalForTest(SIGTERM, 'default', 'queue', $options); $releaseJob->pop(); @@ -3191,7 +3208,7 @@ public function interrupted(int $signal): void $job->resolvedJob = $handler; $worker = $this->getWorker('default', ['queue' => [$job]]); - $this->events->shouldReceive('dispatch')->andReturnUsing( + $this->events->allows('dispatch')->resolves( function (object $event) use ($order): void { if ($event instanceof WorkerInterrupted) { $order[] = 'worker-interrupted'; @@ -3220,7 +3237,7 @@ function (object $event) use ($order): void { public function testSignalAndStopEventsAreNotDispatchedWithoutListeners(): void { $this->spyEvents(); - $this->events->shouldReceive('hasListeners')->andReturnFalse(); + $this->events->allows('hasListeners')->returns(false); $workerOptions = new WorkerOptions; $worker = $this->getWorker('default', ['queue' => []]); @@ -3233,11 +3250,11 @@ public function testSignalAndStopEventsAreNotDispatchedWithoutListeners(): void $this->assertSame(7, $status); $this->assertFalse($worker->paused); $this->assertTrue($worker->shouldQuit); - $this->events->shouldHaveReceived('hasListeners')->with(WorkerPausing::class)->once(); - $this->events->shouldHaveReceived('hasListeners')->with(WorkerResuming::class)->once(); - $this->events->shouldHaveReceived('hasListeners')->with(WorkerInterrupted::class)->once(); - $this->events->shouldHaveReceived('hasListeners')->with(WorkerStopping::class)->once(); - $this->events->shouldNotHaveReceived('dispatch'); + $this->events->received('hasListeners')->with(WorkerPausing::class)->times(1); + $this->events->received('hasListeners')->with(WorkerResuming::class)->times(1); + $this->events->received('hasListeners')->with(WorkerInterrupted::class)->times(1); + $this->events->received('hasListeners')->with(WorkerStopping::class)->times(1); + $this->events->received('dispatch')->never(); } public function testInterruptibleJobIsNotifiedOnSignal(): void @@ -3317,7 +3334,7 @@ public function interrupted(int $signal): void public function testJobInterruptedEventIsSkippedWithoutListenersButTheJobIsStillNotified(): void { $this->spyEvents(); - $this->events->shouldReceive('hasListeners')->andReturnFalse(); + $this->events->allows('hasListeners')->returns(false); $interruptible = new WorkerInterruptibleJob; $worker = $this->getWorker('default', ['queue' => []]); $worker->registerCoroutineJobForTest( @@ -3328,8 +3345,8 @@ public function testJobInterruptedEventIsSkippedWithoutListenersButTheJobIsStill $worker->notifyJobsOfSignalForTest(SIGINT); $this->assertSame([SIGINT], $interruptible->signals); - $this->events->shouldHaveReceived('hasListeners')->with(JobInterrupted::class)->once(); - $this->events->shouldNotHaveReceived('dispatch'); + $this->events->received('hasListeners')->with(JobInterrupted::class)->times(1); + $this->events->received('dispatch')->never(); } public function testNotifyJobsOfSignalIgnoresNonInterruptibleCommandsAndOtherHandlers(): void @@ -3417,7 +3434,7 @@ public function testJobReleasedEvent(): void public function testFailureLifecycleEventsAreNotDispatchedWithoutListeners(): void { $this->spyEvents(); - $this->events->shouldReceive('hasListeners')->andReturnFalse(); + $this->events->allows('hasListeners')->returns(false); $exception = new RuntimeException; $job = new WorkerFakeJob(static function () use ($exception): never { throw $exception; @@ -3428,10 +3445,10 @@ public function testFailureLifecycleEventsAreNotDispatchedWithoutListeners(): vo $this->assertTrue($job->released); $this->assertSame(10, $job->releaseAfter); - $this->events->shouldHaveReceived('hasListeners')->with(JobExceptionOccurred::class)->once(); - $this->events->shouldHaveReceived('hasListeners')->with(JobReleasedAfterException::class)->once(); - $this->events->shouldHaveReceived('hasListeners')->with(JobAttempted::class)->once(); - $this->events->shouldNotHaveReceived('dispatch'); + $this->events->received('hasListeners')->with(JobExceptionOccurred::class)->times(1); + $this->events->received('hasListeners')->with(JobReleasedAfterException::class)->times(1); + $this->events->received('hasListeners')->with(JobAttempted::class)->times(1); + $this->events->received('dispatch')->never(); } /** @@ -3486,8 +3503,8 @@ private function captureErrorLog(): string */ private function spyEvents(): void { - $this->events = m::spy(EventDispatcher::class); - $this->events->shouldReceive('hasListeners')->byDefault()->andReturn(true); + $this->events = Double::for(EventDispatcher::class); + $this->events->allows('hasListeners')->returns(true); } /** @@ -3545,8 +3562,8 @@ private function registerRunningJob(InsomniacWorker $worker, Job $job, WorkerOpt private function workerJobWithRunningCommand(object $command): WorkerFakeJob { - $handler = m::mock(CallQueuedHandler::class); - $handler->expects('getRunningCommand')->andReturn($command); + $handler = Double::for(CallQueuedHandler::class); + $handler->expects('getRunningCommand')->returns($command); $job = new WorkerFakeJob; $job->resolvedJob = $handler; diff --git a/tests/Redis/ConcurrencyLimiterTest.php b/tests/Redis/ConcurrencyLimiterTest.php index 6de14191f..c4c20b3b5 100644 --- a/tests/Redis/ConcurrencyLimiterTest.php +++ b/tests/Redis/ConcurrencyLimiterTest.php @@ -11,7 +11,9 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -20,6 +22,8 @@ class ConcurrencyLimiterTest extends TestCase { + use VerifiesDoubles; + public function testBlockExecutesCallbackOnSuccessfulAcquisition(): void { $redis = $this->mockRedis(); @@ -29,14 +33,8 @@ public function testBlockExecutesCallbackOnSuccessfulAcquisition(): void // release() calls eval with the release script $redis->expects('eval') - ->withArgs(function (string $script, int $numKeys, string $key, string $id): bool { - $this->assertSame(1, $numKeys); - $this->assertSame('test-lock1', $key); - $this->assertNotEmpty($id); - - return true; - }) - ->andReturn(1); + ->with(Argument::type('string'), 1, 'test-lock1', Argument::satisfies(static fn (string $id): bool => $id !== '')) + ->returns(1); $limiter = new ConcurrencyLimiter($redis, 'test-lock', 3, 60); @@ -70,13 +68,8 @@ public function testBlockReleasesLockWhenCallbackThrows(): void // release() should still be called $redis->expects('eval') - ->withArgs(function (string $script, int $numKeys, string $key, string $id): bool { - $this->assertSame(1, $numKeys); - $this->assertSame('test-lock1', $key); - - return true; - }) - ->andReturn(1); + ->with(Argument::type('string'), 1, 'test-lock1', Argument::type('string')) + ->returns(1); $limiter = new ConcurrencyLimiter($redis, 'test-lock', 3, 60); @@ -95,7 +88,7 @@ public function testBlockPropagatesReleaseFailureAfterSuccessfulCallback(): void $this->expectSlotClaim($redis, 'test-lock1'); $redis->expects('eval') - ->andThrow($releaseException); + ->throws($releaseException); $limiter = new ConcurrencyLimiter($redis, 'test-lock', 3, 60); @@ -123,7 +116,7 @@ public function testBlockPreservesCallbackFailureWhenReleaseAlsoFails(string $ki $this->expectSlotClaim($redis, 'test-lock1'); $redis->expects('eval') - ->andThrow($releaseException); + ->throws($releaseException); $limiter = new ConcurrencyLimiter($redis, 'test-lock', 3, 60); @@ -143,13 +136,13 @@ public function testBlockPreservesCallbackFailureWhenReleaseAlsoFails(string $ki public function testBlockThrowsTimeoutExceptionWhenCannotAcquire(): void { $redis = $this->mockRedis(); - $connection = m::mock(RedisConnection::class); + $connection = Double::for(RedisConnection::class); // acquire() always fails (returns falsy) - $redis->shouldReceive('withConnection') - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); - $connection->shouldReceive('evalWithShaCache') - ->andReturn(false); + $redis->allows('withConnection') + ->resolves(fn (callable $callback): mixed => $callback($connection)); + $connection->allows('evalWithShaCache') + ->returns(false); $limiter = new ConcurrencyLimiter($redis, 'test-lock', 3, 60); @@ -164,11 +157,11 @@ public function testBlockCanAcquireAtTheDeadlineWithAShorterFinalSleep(): void Sleep::fake(syncWithCarbon: true); CarbonImmutable::setTestNow(CarbonImmutable::now()); $redis = $this->mockRedis(); - $connection = m::mock(RedisConnection::class); - $redis->shouldReceive('withConnection') - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); - $connection->shouldReceive('evalWithShaCache')->times(4) - ->andReturn(false, false, false, 'test-lock1'); + $connection = Double::for(RedisConnection::class); + $redis->allows('withConnection') + ->resolves(fn (callable $callback): mixed => $callback($connection)); + $connection->expects('evalWithShaCache')->times(4) + ->returns(false, false, false, 'test-lock1'); $limiter = new ConcurrencyLimiter($redis, 'test-lock', 1, 10); @@ -187,7 +180,7 @@ public function testBlockWithZeroLimitDoesNotCallEvalAndTimesOut(): void // limit(0) means no slots — acquire must short-circuit before evaluating Lua, // otherwise Lua hits redis.call('mget') with no args and errors. - $redis->shouldNotReceive('withConnection'); + $redis->expects('withConnection')->never(); $this->expectException(LimiterTimeoutException::class); @@ -198,7 +191,7 @@ public function testBlockWithNegativeLimitDoesNotCallEvalAndTimesOut(): void { $redis = $this->mockRedis(); - $redis->shouldNotReceive('withConnection'); + $redis->expects('withConnection')->never(); $this->expectException(LimiterTimeoutException::class); @@ -224,14 +217,8 @@ public function testLeaseCanReleaseSlot(): void $this->expectSlotClaim($redis, 'test-lock1'); $redis->expects('eval') - ->withArgs(function (string $script, int $numKeys, string $key, string $id): bool { - $this->assertSame(1, $numKeys); - $this->assertSame('test-lock1', $key); - $this->assertNotEmpty($id); - - return true; - }) - ->andReturn(1); + ->with(Argument::type('string'), 1, 'test-lock1', Argument::satisfies(static fn (string $id): bool => $id !== '')) + ->returns(1); $lease = (new ConcurrencyLimiter($redis, 'test-lock', 3, 60))->acquire(5); @@ -244,15 +231,8 @@ public function testLeaseCanRefreshSlot(): void $this->expectSlotClaim($redis, 'test-lock1'); $redis->expects('eval') - ->withArgs(function (string $script, int $numKeys, string $key, string $id, int $seconds): bool { - $this->assertSame(1, $numKeys); - $this->assertSame('test-lock1', $key); - $this->assertNotEmpty($id); - $this->assertSame(60, $seconds); - - return true; - }) - ->andReturn(1); + ->with(Argument::type('string'), 1, 'test-lock1', Argument::satisfies(static fn (string $id): bool => $id !== ''), 60) + ->returns(1); $lease = (new ConcurrencyLimiter($redis, 'test-lock', 3, 60))->acquire(5); @@ -266,7 +246,7 @@ public function testLeaseReturnsRemainingLifetime(): void $this->expectSlotClaim($redis, 'test-lock1'); $redis->expects('ttl') ->with('test-lock1') - ->andReturn(5); + ->returns(5); $lease = (new ConcurrencyLimiter($redis, 'test-lock', 3, 60))->acquire(5); @@ -276,7 +256,7 @@ public function testLeaseReturnsRemainingLifetime(): void public function testAcquireUsesHashTagsOnPhpRedisClusterConnection(): void { $redis = $this->mockRedis(); - $redis->expects('isCluster')->andReturnTrue(); + $redis->expects('isCluster')->returns(true); $this->expectSlotClaim( $redis, @@ -300,7 +280,7 @@ function (string $script, array $keys, array $arguments): bool { public function testAcquireUsesPlainKeysOnNonClusterConnection(): void { $redis = $this->mockRedis(); - $redis->expects('isCluster')->andReturnFalse(); + $redis->expects('isCluster')->returns(false); $this->expectSlotClaim( $redis, @@ -327,7 +307,7 @@ function (string $script, array $keys, array $arguments): bool { public function testReleaseKeyMatchesAcquireKeyOnCluster(): void { $redis = $this->mockRedis(); - $redis->expects('isCluster')->andReturnTrue(); + $redis->expects('isCluster')->returns(true); // Acquire returns the slot key. $this->expectSlotClaim($redis, '{mykey}2'); @@ -344,7 +324,7 @@ public function testReleaseKeyMatchesAcquireKeyOnCluster(): void public function testAcquireDoesNotDoubleWrapPreExistingHashTags(string $name): void { $redis = $this->mockRedis(); - $redis->expects('isCluster')->andReturnTrue(); + $redis->expects('isCluster')->returns(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 { @@ -372,7 +352,7 @@ public static function existingHashTags(): array public function testAcquireWrapsUnmatchedBraceOnCluster(): void { $redis = $this->mockRedis(); - $redis->expects('isCluster')->andReturnTrue(); + $redis->expects('isCluster')->returns(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 { @@ -392,7 +372,7 @@ public function testAcquireWrapsUnmatchedBraceOnCluster(): void public function testAcquireWrapsEmptyBracesOnCluster(): void { $redis = $this->mockRedis(); - $redis->expects('isCluster')->andReturnTrue(); + $redis->expects('isCluster')->returns(true); // Empty braces are not a valid hash tag. $this->expectSlotClaim($redis, '{my{}lock}1', function (string $script, array $keys, array $arguments): bool { @@ -412,43 +392,56 @@ public function testAcquireWrapsEmptyBracesOnCluster(): void /** * Create a mock RedisProxy. */ - private function mockRedis(): m\MockInterface|RedisProxy + private function mockRedis(): ConcurrencyLimiterRedisProxy { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('isCluster')->byDefault()->andReturnFalse(); - - return $redis; + return Double::for(ConcurrencyLimiterRedisProxy::class); } /** * Expect a slot-claim script evaluation on one held Redis connection. */ private function expectSlotClaim( - m\MockInterface|RedisProxy $redis, + ConcurrencyLimiterRedisProxy $redis, false|string $result, ?callable $assertion = null, ): void { - $connection = m::mock(RedisConnection::class); + $connection = Double::for(RedisConnection::class); $redis->expects('withConnection') - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); + ->resolves(fn (callable $callback): mixed => $callback($connection)); - $expectation = $connection->expects('evalWithShaCache'); + $connection->expects('evalWithShaCache')->resolves( + function (string $script, array $keys, array $arguments) use ($assertion, $result): false|string { + if ($assertion !== null) { + $this->assertTrue($assertion($script, $keys, $arguments)); + } - if ($assertion !== null) { - $expectation->withArgs($assertion); - } - - $expectation->andReturn($result); + return $result; + } + ); } /** * Expect a release script evaluation for the acquired slot. */ - private function expectRelease(m\MockInterface|RedisProxy $redis, string $key): void + private function expectRelease(ConcurrencyLimiterRedisProxy $redis, string $key): void { $redis->expects('eval') - ->with(m::on(static fn (string $script): bool => str_contains($script, 'del')), 1, $key, m::type('string')) - ->andReturn(1); + ->with(Argument::satisfies(static fn (string $script): bool => str_contains($script, 'del')), 1, $key, Argument::type('string')) + ->returns(1); } } + +// Declare the dynamic proxy commands so Double can generate native methods. +abstract class ConcurrencyLimiterRedisProxy extends RedisProxy +{ + /** + * Execute a Lua script. + */ + abstract public function eval(string $script, int $numberOfKeys, mixed ...$arguments): mixed; + + /** + * Get the remaining key lifetime. + */ + abstract public function ttl(string $key): int; +} diff --git a/tests/Redis/Fixtures/FakeRedisClusterClient.php b/tests/Redis/Fixtures/FakeRedisClusterClient.php index 65b16ba14..ebbf00328 100644 --- a/tests/Redis/Fixtures/FakeRedisClusterClient.php +++ b/tests/Redis/Fixtures/FakeRedisClusterClient.php @@ -11,10 +11,13 @@ * Fake RedisCluster client for testing cluster-specific operations. * * Extends RedisCluster to satisfy type hints while providing controlled - * test behavior. Does NOT connect to any real Redis Cluster. + * test behavior without connecting to a real Redis Cluster. A concrete fake + * preserves SCAN's by-reference cursor, which Double cannot update. */ class FakeRedisClusterClient extends RedisCluster { + public int $mastersRequested = 0; + /** * Configured master nodes. * @@ -25,7 +28,7 @@ class FakeRedisClusterClient extends RedisCluster /** * Configured scan results per node. * - * @var array, iterator: int}>> + * @var array|false, iterator: int|string}>> */ private array $scanResults; @@ -39,7 +42,7 @@ class FakeRedisClusterClient extends RedisCluster /** * Recorded scan calls for assertions. * - * @var array + * @var array */ private array $scanCalls = []; @@ -65,10 +68,8 @@ class FakeRedisClusterClient extends RedisCluster /** * Create a new fake RedisCluster client. * - * Does NOT call parent::__construct() to avoid real connection attempts. - * * @param array $masters Configured master nodes - * @param array, iterator: int}>> $scanResults Scan results per node key + * @param array|false, iterator: int|string}>> $scanResults Scan results per node key * @param string $optPrefix Configured OPT_PREFIX value */ public function __construct( @@ -76,8 +77,7 @@ public function __construct( array $scanResults = [], string $optPrefix = '', ) { - // Intentionally do NOT call parent::__construct() to avoid - // any connection attempts. This fake client never connects. + // Skip the native constructor so tests never connect to Redis. $this->masters = $masters; $this->scanResults = $scanResults; $this->optPrefix = $optPrefix; @@ -90,9 +90,21 @@ public function __construct( */ public function _masters(): array { + ++$this->mastersRequested; + return $this->masters; } + /** + * Replace the Cluster topology between scans. + * + * @param array $masters + */ + public function setMasters(array $masters): void + { + $this->masters = $masters; + } + /** * Simulate RedisCluster SCAN with node parameter. * @@ -106,7 +118,7 @@ public function scan(int|string|null &$iterator, string|array|null $node = null, { $nodeKey = is_array($node) ? implode(':', $node) : (string) $node; - $this->scanCalls[] = ['node' => $node, 'pattern' => $pattern, 'count' => $count]; + $this->scanCalls[] = ['iterator' => $iterator, 'node' => $node, 'pattern' => $pattern, 'count' => $count]; if (! isset($this->scanCallIndex[$nodeKey])) { $this->scanCallIndex[$nodeKey] = 0; @@ -159,7 +171,7 @@ public function getOption(int $option): mixed /** * Get recorded scan calls for test assertions. * - * @return array + * @return array */ public function getScanCalls(): array { diff --git a/tests/Redis/PhpRedisClusterConnectionTest.php b/tests/Redis/PhpRedisClusterConnectionTest.php index 905d57a8d..34f656357 100644 --- a/tests/Redis/PhpRedisClusterConnectionTest.php +++ b/tests/Redis/PhpRedisClusterConnectionTest.php @@ -17,8 +17,10 @@ use Hypervel\Tests\Redis\Fixtures\RespServer; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestWith; use Redis; use RedisCluster; use RedisException; @@ -28,6 +30,8 @@ class PhpRedisClusterConnectionTest extends TestCase { + use VerifiesDoubles; + public function testClusterCreationPreservesExactCancellation(): void { $cancellation = new CanceledException('cluster creation canceled'); @@ -95,12 +99,11 @@ public function testTransformFiresInAtomicMode(): void $connection = new PhpRedisClusterConnectionStub; // In atomic mode, isQueueingMode() returns false, so transforms fire - $client = m::mock(RedisCluster::class); - $client->shouldReceive('getMode')->andReturn(Redis::ATOMIC); - $client->shouldReceive('setNx') - ->once() + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects('setNx') ->with('key', 'value') - ->andReturn(true); + ->returns(true); $connection->setActiveConnection($client); $connection->shouldTransform(true); @@ -116,12 +119,11 @@ 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 = m::mock(RedisCluster::class); - $client->shouldReceive('getMode')->andReturn(Redis::MULTI); - $client->shouldReceive('setnx') - ->once() + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::MULTI); + $client->expects('setnx') ->with('key', 'value') - ->andReturn($client); // multi() returns self for chaining + ->returns($client); // multi() returns self for chaining $connection->setActiveConnection($client); $connection->shouldTransform(true); @@ -184,12 +186,12 @@ 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 = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->expects('_masters')->once()->andReturn($masters); - $client->expects('flushdb')->with($masters[0])->andReturnTrue(); - $client->expects('flushdb')->with($masters[1])->andReturnFalse(); - $client->expects('flushdb')->with($masters[2])->andReturnTrue(); + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects('_masters')->returns($masters); + $client->expects('flushdb')->with($masters[0])->returns(true); + $client->expects('flushdb')->with($masters[1])->returns(false); + $client->expects('flushdb')->with($masters[2])->returns(true); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client); @@ -198,9 +200,14 @@ public function testFlushdbAttemptsEveryMasterAndAggregatesFailures(): void $this->assertFalse($connection->__call('flushdb', [])); } - public function testItScansStartingFromTheFirstMaster(): void + #[TestWith([false])] + #[TestWith([true])] + public function testItScansStartingFromTheFirstMaster(bool $hasNextMaster): void { - $masters = [['127.0.0.1', 6379], ['127.0.0.1', 6380]]; + $masters = [['127.0.0.1', 6379]]; + if ($hasNextMaster) { + $masters[] = ['127.0.0.1', 6380]; + } $nodeKey = '127.0.0.1:6379'; $client = new FakeRedisClusterClient( masters: $masters, @@ -220,17 +227,21 @@ public function testItScansStartingFromTheFirstMaster(): void $this->assertSame(['key1', 'key2'], $result[1]); $this->assertSame($cursor, $result[0]); - $this->assertStringStartsWith('hypervel:', $cursor); + if ($hasNextMaster) { + $this->assertStringStartsWith('hypervel:', $cursor); + } else { + $this->assertSame(0, $cursor); + } $scanCalls = $client->getScanCalls(); - $this->assertCount(1, $scanCalls); - $this->assertSame(['127.0.0.1', 6379], $scanCalls[0]['node']); + $this->assertSame([['iterator' => null, 'node' => $masters[0], 'pattern' => '*', 'count' => 10]], $scanCalls); } - public function testItScansUsingOptionNode(): void + #[TestWith([['127.0.0.1', 6380]])] + #[TestWith(['option-node'])] + public function testItScansUsingOptionNode(array|string $explicitNode): void { - $explicitNode = ['127.0.0.1', 6380]; - $nodeKey = '127.0.0.1:6380'; + $nodeKey = is_array($explicitNode) ? implode(':', $explicitNode) : $explicitNode; $client = new FakeRedisClusterClient( masters: [['127.0.0.1', 6379], ['127.0.0.1', 6380]], scanResults: [ @@ -250,58 +261,50 @@ public function testItScansUsingOptionNode(): void $this->assertSame([0, ['key3']], $result); $scanCalls = $client->getScanCalls(); - $this->assertCount(1, $scanCalls); - $this->assertSame($explicitNode, $scanCalls[0]['node']); + $this->assertSame([['iterator' => null, 'node' => $explicitNode, 'pattern' => '*', 'count' => 10]], $scanCalls); + $this->assertSame(0, $client->mastersRequested); } public function testItThrowsExceptionWithoutNodes(): void { - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->expects('_masters')->andReturn([]); - $client->shouldNotReceive('scan'); + $client = new FakeRedisClusterClient(masters: []); + $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client)->shouldTransform(); $this->expectExceptionObject(new InvalidArgumentException('No master nodes found in the cluster.')); $cursor = null; - $connection->scan($cursor); + try { + $connection->scan($cursor); + } finally { + $this->assertSame([], $client->getScanCalls()); + } } public function testItReturnsFalseWhenCursorIsZeroAndResultIsEmpty(): void { $master = ['127.0.0.1', 6379]; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->expects('_masters')->andReturn([$master]); - $client->expects('scan')->with(0, $master, '*', 10)->andReturnFalse(); + $client = new FakeRedisClusterClient(masters: [$master]); + $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client)->shouldTransform(); $cursor = 0; $this->assertFalse($connection->scan($cursor)); $this->assertSame(0, $cursor); + $this->assertSame([['iterator' => 0, 'node' => $master, 'pattern' => '*', 'count' => 10]], $client->getScanCalls()); } public function testItScansEveryMasterInTurn(): void { $masters = [['127.0.0.1', 6379], ['127.0.0.2', 6379], ['127.0.0.3', 6379]]; $keys = ['a', 'b', 'c']; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->allows('_masters')->andReturn($masters); - - foreach ($masters as $index => $master) { - $key = $keys[$index]; - $client->expects('scan')->with(null, $master, '*', 10) - ->andReturnUsing(function (&$cursor) use ($key): array { - $cursor = 0; - - return [$key]; - }); - $client->expects('scan')->with(0, $master, '*', 10)->andReturnFalse(); - } + $client = new FakeRedisClusterClient(masters: $masters, scanResults: [ + '127.0.0.1:6379' => [['keys' => ['a'], 'iterator' => 0]], + '127.0.0.2:6379' => [['keys' => ['b'], 'iterator' => 0]], + '127.0.0.3:6379' => [['keys' => ['c'], 'iterator' => 0]], + ]); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client)->shouldTransform(); @@ -315,29 +318,27 @@ public function testItScansEveryMasterInTurn(): void $this->assertSame([$key], $page[1]); } + $this->assertSame(array_map( + fn (array $master): array => ['iterator' => null, 'node' => $master, 'pattern' => '*', 'count' => 10], + $masters, + ), $client->getScanCalls()); $this->assertSame(0, $cursor); $this->assertFalse($connection->scan($cursor)); + $this->assertSame([null, null, null, 0, 0, 0], array_column($client->getScanCalls(), 'iterator')); + $this->assertSame([...$masters, ...$masters], array_column($client->getScanCalls(), 'node')); } #[DataProvider('firstScanPages')] public function testItResumesAMasterFromTheEncodedCursor(array $firstPage): void { $master = ['127.0.0.1', 6379]; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->allows('_masters')->andReturn([$master]); - $client->expects('scan')->with(null, $master, '*', 10) - ->andReturnUsing(function (&$cursor) use ($firstPage): array { - $cursor = 42; - - return $firstPage; - }); - $client->expects('scan')->with(42, $master, '*', 10) - ->andReturnUsing(function (&$cursor): array { - $cursor = 0; - - return ['last']; - }); + $client = new FakeRedisClusterClient(masters: [$master], scanResults: [ + '127.0.0.1:6379' => [ + ['keys' => $firstPage, 'iterator' => 42], + ['keys' => ['last'], 'iterator' => 0], + ], + ]); + $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client)->shouldTransform(); $cursor = null; @@ -348,6 +349,11 @@ public function testItResumesAMasterFromTheEncodedCursor(array $firstPage): void $this->assertSame($reportedCursor, $cursor); $this->assertSame($firstPage, $keys); $this->assertSame([0, ['last']], $connection->scan($cursor)); + + $this->assertSame([ + ['iterator' => null, 'node' => $master, 'pattern' => '*', 'count' => 10], + ['iterator' => 42, 'node' => $master, 'pattern' => '*', 'count' => 10], + ], $client->getScanCalls()); } /** @@ -366,114 +372,100 @@ public static function firstScanPages(): array public function testItKeepsScanningWhenAMasterReturnsNoKeys(): void { $masters = [['127.0.0.1', 6379], ['127.0.0.2', 6379]]; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->allows('_masters')->andReturn($masters); - $client->expects('scan')->with(null, $masters[0], '*', 10) - ->andReturnUsing(function (&$cursor): array { - $cursor = 0; - - return []; - }); - $client->expects('scan')->with(null, $masters[1], '*', 10) - ->andReturnUsing(function (&$cursor): array { - $cursor = 0; - - return ['key']; - }); + $client = new FakeRedisClusterClient(masters: $masters, scanResults: [ + '127.0.0.1:6379' => [['keys' => [], 'iterator' => 0]], + '127.0.0.2:6379' => [['keys' => ['key'], 'iterator' => 0]], + ]); + $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client)->shouldTransform(); $cursor = null; $this->assertSame([0, ['key']], $connection->scan($cursor)); + + $this->assertSame([ + ['iterator' => null, 'node' => $masters[0], 'pattern' => '*', 'count' => 10], + ['iterator' => null, 'node' => $masters[1], 'pattern' => '*', 'count' => 10], + ], $client->getScanCalls()); } public function testItPreservesLargeStringCursors(): void { $master = ['127.0.0.1', 6379]; $largeCursor = '18446744073709551615'; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->allows('_masters')->andReturn([$master]); - $client->expects('scan')->with(null, $master, '*', 10) - ->andReturnUsing(function (&$cursor) use ($largeCursor): array { - $cursor = $largeCursor; - - return ['first']; - }); - $client->expects('scan')->with($largeCursor, $master, '*', 10) - ->andReturnUsing(function (&$cursor): array { - $cursor = 0; - - return ['last']; - }); + $client = new FakeRedisClusterClient(masters: [$master], scanResults: [ + '127.0.0.1:6379' => [ + ['keys' => ['first'], 'iterator' => $largeCursor], + ['keys' => ['last'], 'iterator' => 0], + ], + ]); + $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client)->shouldTransform(); $cursor = null; [$cursor] = $connection->scan($cursor); $this->assertSame([0, ['last']], $connection->scan($cursor)); + + $this->assertSame([ + ['iterator' => null, 'node' => $master, 'pattern' => '*', 'count' => 10], + ['iterator' => $largeCursor, 'node' => $master, 'pattern' => '*', 'count' => 10], + ], $client->getScanCalls()); } public function testItKeepsNodeAffinityWhenMastersAreReordered(): void { $masters = [['127.0.0.1', 6379], ['127.0.0.2', 6379]]; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->expects('_masters')->twice()->andReturn($masters, array_reverse($masters)); - - foreach ($masters as $index => $master) { - $client->expects('scan')->with(null, $master, '*', 10) - ->andReturnUsing(function (&$cursor) use ($index): array { - $cursor = 0; - - return [$index === 0 ? 'a' : 'b']; - }); - } + $client = new FakeRedisClusterClient(masters: $masters, scanResults: [ + '127.0.0.1:6379' => [['keys' => ['a'], 'iterator' => 0]], + '127.0.0.2:6379' => [['keys' => ['b'], 'iterator' => 0]], + ]); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client)->shouldTransform(); $cursor = null; [$cursor] = $connection->scan($cursor); + $client->setMasters(array_reverse($masters)); $this->assertSame([0, ['b']], $connection->scan($cursor)); + $this->assertSame(2, $client->mastersRequested); + $this->assertSame([ + ['iterator' => null, 'node' => $masters[0], 'pattern' => '*', 'count' => 10], + ['iterator' => null, 'node' => $masters[1], 'pattern' => '*', 'count' => 10], + ], $client->getScanCalls()); } public function testItContinuesWithAnotherMasterWhenTheCurrentMasterDisappears(): void { $masters = [['127.0.0.1', 6379], ['127.0.0.2', 6379]]; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->expects('_masters')->twice()->andReturn($masters, [$masters[1]]); - $client->expects('scan')->with(null, $masters[0], '*', 10) - ->andReturnUsing(function (&$cursor): array { - $cursor = 42; - - return ['a']; - }); - $client->expects('scan')->with(null, $masters[1], '*', 10) - ->andReturnUsing(function (&$cursor): array { - $cursor = 0; - - return ['b']; - }); + $client = new FakeRedisClusterClient(masters: $masters, scanResults: [ + '127.0.0.1:6379' => [['keys' => ['a'], 'iterator' => 42]], + '127.0.0.2:6379' => [['keys' => ['b'], 'iterator' => 0]], + ]); + $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client)->shouldTransform(); $cursor = null; [$cursor] = $connection->scan($cursor); + $client->setMasters([$masters[1]]); $this->assertSame([0, ['b']], $connection->scan($cursor)); + $this->assertSame(2, $client->mastersRequested); + $this->assertSame([ + ['iterator' => null, 'node' => $masters[0], 'pattern' => '*', 'count' => 10], + ['iterator' => null, 'node' => $masters[1], 'pattern' => '*', 'count' => 10], + ], $client->getScanCalls()); } public function testInfoTransformIncludesTheDefaultNodeAndSections(): void { $defaultNode = ['127.0.0.1', 6379]; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->expects('_masters')->once()->andReturn([$defaultNode]); + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects('_masters')->returns([$defaultNode]); $client->expects('info') ->with($defaultNode, 'server', 'memory') - ->andReturn(['redis_version' => '8.0.0']); + ->returns(['redis_version' => '8.0.0']); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client); @@ -488,12 +480,12 @@ public function testInfoTransformIncludesTheDefaultNodeAndSections(): void public function testInfoTransformSupportsAnUnfilteredRequest(): void { $defaultNode = ['127.0.0.1', 6379]; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->expects('_masters')->once()->andReturn([$defaultNode]); + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects('_masters')->returns([$defaultNode]); $client->expects('info') ->with($defaultNode) - ->andReturn(['redis_version' => '8.0.0', 'used_memory' => 1024]); + ->returns(['redis_version' => '8.0.0', 'used_memory' => 1024]); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client); @@ -508,11 +500,11 @@ public function testInfoTransformSupportsAnUnfilteredRequest(): void public function testPingTransformRoutesToTheDefaultNode(): void { $defaultNode = ['127.0.0.1', 6379]; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->expects('_masters')->once()->andReturn([$defaultNode]); - $client->expects('ping')->with($defaultNode)->andReturnTrue(); - $client->expects('ping')->with($defaultNode, 'hello')->andReturn('hello'); + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects('_masters')->returns([$defaultNode]); + $client->expects('ping')->with($defaultNode)->returns(true); + $client->expects('ping')->with($defaultNode, 'hello')->returns('hello'); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client); @@ -524,11 +516,11 @@ public function testPingTransformRoutesToTheDefaultNode(): void public function testExecuteRawRoutesByTheFirstArgumentAndNormalizesNullReplies(): void { - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::ATOMIC); $client->expects('rawCommand') ->with('{user}:1', 'GET', '{user}:1') - ->andReturnNull(); + ->returns(null); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client); @@ -539,11 +531,11 @@ public function testExecuteRawRoutesByTheFirstArgumentAndNormalizesNullReplies() public function testExecuteRawRoutesByTheFirstArgumentWhileQueueing(): void { - $client = m::mock(RedisCluster::class); - $client->expects('getMode')->andReturn(Redis::MULTI); + $client = Double::for(RedisCluster::class); + $client->expects('getMode')->returns(Redis::MULTI); $client->expects('rawCommand') ->with('{user}:1', 'GET', '{user}:1') - ->andReturn($client); + ->returns($client); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client); @@ -558,12 +550,12 @@ public function testExecuteRawRoutesByTheFirstArgumentWhileQueueing(): void public function testExecuteRawRoutesKeylessCommandsToTheDefaultNode(): void { $defaultNode = ['127.0.0.1', 6379]; - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->expects('_masters')->once()->andReturn([$defaultNode]); + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects('_masters')->returns([$defaultNode]); $client->expects('rawCommand') ->with($defaultNode, 'TIME') - ->andReturn(['1', '2']); + ->returns(['1', '2']); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client); @@ -810,13 +802,13 @@ public function setOptionsForTest(RedisCluster $redis): void $this->setOptions($redis); } }; - $redis = m::mock(RedisCluster::class); + $redis = Double::for(RedisCluster::class); $redis->expects('setOption') ->with(RedisCluster::OPT_SLAVE_FAILOVER, RedisCluster::FAILOVER_DISTRIBUTE) - ->andReturnTrue(); + ->returns(true); $redis->expects('setOption') ->with(Redis::OPT_PACK_IGNORE_NUMBERS, true) - ->andReturnTrue(); + ->returns(true); $this->expectDefaultConnectionOptions($redis); $connection->setOptionsForTest($redis); @@ -834,7 +826,7 @@ public function setOptionsForTest(RedisCluster $redis): void $this->setOptions($redis); } }; - $redis = m::mock(RedisCluster::class); + $redis = Double::for(RedisCluster::class); $this->expectDefaultConnectionOptions($redis); $this->expectExceptionObject(new InvalidRedisOptionException( @@ -868,7 +860,7 @@ public function setOptionsForTest(RedisCluster $redis): void $this->setOptions($redis); } }; - $redis = m::mock(RedisCluster::class); + $redis = Double::for(RedisCluster::class); $this->expectDefaultConnectionOptions($redis); $connection->setOptionsForTest($redis); @@ -935,15 +927,14 @@ public function formatClusterPasswordForTest(): mixed public function testDefaultNodeIsCached(): void { - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->shouldReceive('_masters') - ->once() - ->andReturn([['127.0.0.1', 6379]]); - $client->shouldReceive('ping') - ->twice() + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects('_masters') + ->returns([['127.0.0.1', 6379]]); + $client->expects('ping') + ->times(2) ->with(['127.0.0.1', 6379]) - ->andReturnTrue(); + ->returns(true); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client); @@ -955,11 +946,10 @@ public function testDefaultNodeIsCached(): void public function testDefaultNodeThrowsWhenNoMasters(): void { - $client = m::mock(RedisCluster::class); - $client->allows('getMode')->andReturn(Redis::ATOMIC); - $client->shouldReceive('_masters') - ->once() - ->andReturn([]); + $client = Double::for(RedisCluster::class); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->expects('_masters') + ->returns([]); $connection = new PhpRedisClusterConnectionStub; $connection->setActiveConnection($client); @@ -974,13 +964,13 @@ public function testDefaultNodeThrowsWhenNoMasters(): void public function testConnectionRebuildsItsClientOnNextAcquisitionWithoutReplayingCommand(): void { $exception = new RedisException('Connection lost'); - $failedClient = m::mock(RedisCluster::class); - $healthyClient = m::mock(RedisCluster::class); + $failedClient = Double::for(RedisCluster::class); + $healthyClient = Double::for(RedisCluster::class); $this->expectDefaultConnectionOptions($failedClient); $this->expectDefaultConnectionOptions($healthyClient); - $failedClient->expects('get')->once()->with('foo')->andThrow($exception); - $failedClient->expects('getLastError')->andReturnNull(); - $healthyClient->expects('get')->once()->with('foo')->andReturn('bar'); + $failedClient->expects('get')->with('foo')->throws($exception); + $failedClient->expects('getLastError')->returns(null); + $healthyClient->expects('get')->with('foo')->returns('bar'); $connection = new class($this->getContainer(), $this->getMockedPool(), $this->clusterConfig(), [$failedClient, $healthyClient]) extends PhpRedisClusterConnection { /** @@ -1023,29 +1013,29 @@ protected function createRedisCluster(): RedisCluster public function testReconnectClearsCachedDefaultNode(): void { - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray([])); + $pool = Double::for(ConnectionPool::class); + $pool->allows('getOptions')->returns(PoolOptions::fromArray([])); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->andReturn(false); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(ContainerContract::class, override: true); + $container->allows('has')->returns(false); + $container->allows('bound')->with('events')->returns(false); // First client: master is node A - $clientA = m::mock(RedisCluster::class); - $clientA->shouldReceive('_masters')->once()->andReturn([['10.0.0.1', 6379]]); - $clientA->allows('getMode')->andReturn(Redis::ATOMIC); - $clientA->expects('ping')->with(['10.0.0.1', 6379])->andReturnTrue(); - $clientA->shouldReceive('setOption')->andReturnTrue(); + $clientA = Double::for(RedisCluster::class); + $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 = m::mock(RedisCluster::class); - $clientB->shouldReceive('_masters')->once()->andReturn([['10.0.0.2', 6379]]); - $clientB->allows('getMode')->andReturn(Redis::ATOMIC); - $clientB->expects('ping')->with(['10.0.0.2', 6379])->andReturnTrue(); - $clientB->shouldReceive('setOption')->andReturnTrue(); + $clientB = Double::for(RedisCluster::class); + $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); + $clientB->allows('setOption')->returns(true); $callCount = 0; - $connection = new class($container, $pool, $this->clusterConfig(['cluster' => ['enabled' => true, 'seeds' => ['tcp://10.0.0.1:6379']]]), $clientA, $clientB, $callCount) extends PhpRedisClusterConnection { + $connection = new class($container->instance(), $pool, $this->clusterConfig(['cluster' => ['enabled' => true, 'seeds' => ['tcp://10.0.0.1:6379']]]), $clientA, $clientB, $callCount) extends PhpRedisClusterConnection { public function __construct( ContainerContract $container, ConnectionPool $pool, @@ -1075,9 +1065,6 @@ protected function createRedisCluster(): RedisCluster // The next ping must resolve node B from the replacement client. $this->assertTrue($connection->ping()); - - // Mockery's ->once() on each client's _masters() verifies each was called exactly once, - // proving the cache was cleared and re-populated after reconnect. } /** @@ -1122,12 +1109,12 @@ private function clusterConfig(array $overrides = []): array */ private function expectDefaultConnectionOptions(RedisCluster $redis): void { - $redis->expects('setOption')->with(Redis::OPT_MAX_RETRIES, 3)->andReturnTrue(); + $redis->expects('setOption')->with(Redis::OPT_MAX_RETRIES, 3)->returns(true); $redis->expects('setOption') ->with(Redis::OPT_BACKOFF_ALGORITHM, Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER) - ->andReturnTrue(); - $redis->expects('setOption')->with(Redis::OPT_BACKOFF_BASE, 100)->andReturnTrue(); - $redis->expects('setOption')->with(Redis::OPT_BACKOFF_CAP, 1000)->andReturnTrue(); + ->returns(true); + $redis->expects('setOption')->with(Redis::OPT_BACKOFF_BASE, 100)->returns(true); + $redis->expects('setOption')->with(Redis::OPT_BACKOFF_CAP, 1000)->returns(true); } /** @@ -1135,8 +1122,8 @@ private function expectDefaultConnectionOptions(RedisCluster $redis): void */ private function getMockedPool(): ConnectionPool { - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray([])); + $pool = Double::for(ConnectionPool::class); + $pool->allows('getOptions')->returns(PoolOptions::fromArray([])); return $pool; } @@ -1146,11 +1133,11 @@ private function getMockedPool(): ConnectionPool */ private function getContainer(): ContainerContract { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->andReturn(false); - $container->shouldReceive('bound')->with('events')->andReturn(false); + $container = Double::for(ContainerContract::class, override: true); + $container->allows('has')->returns(false); + $container->allows('bound')->with('events')->returns(false); - return $container; + return $container->instance(); } /** diff --git a/tests/Redis/RedisEventsTest.php b/tests/Redis/RedisEventsTest.php index 5f171a078..b5ca8dcc6 100644 --- a/tests/Redis/RedisEventsTest.php +++ b/tests/Redis/RedisEventsTest.php @@ -20,12 +20,16 @@ use Hypervel\Redis\RedisSentinelFactory; use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Tests\TestCase; -use Mockery as m; -use Redis as PhpRedis; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Throwable; class RedisEventsTest extends TestCase { + use VerifiesDoubles; + public function testCommandFailedEventIsDispatched(): void { $exception = new Exception('Test exception'); @@ -100,15 +104,15 @@ public function testCommandFailedEventContainsTime(): void { $exception = new Exception('Test exception'); - $mockEventDispatcher = m::mock(Dispatcher::class); - $mockEventDispatcher->shouldReceive('hasListeners') + $mockEventDispatcher = Double::for(Dispatcher::class); + $mockEventDispatcher->allows('hasListeners') ->with(CommandFailed::class) - ->andReturn(true); - $mockEventDispatcher->shouldReceive('hasListeners') + ->returns(true); + $mockEventDispatcher->allows('hasListeners') ->with(CommandExecuted::class) - ->andReturn(false); + ->returns(false); $mockEventDispatcher->expects('dispatch') - ->with(m::on(function (mixed $event): bool { + ->with(Argument::satisfies(function (mixed $event): bool { return $event instanceof CommandFailed && is_float($event->time) && $event->time >= 0; @@ -128,9 +132,9 @@ public function testCommandFailedEventContainsTime(): void public function testListenRegistersCallback(): void { - $mockEventDispatcher = m::mock(Dispatcher::class); + $mockEventDispatcher = Double::for(Dispatcher::class); $mockEventDispatcher->expects('listen') - ->with(CommandExecuted::class, m::type(Closure::class)); + ->with(CommandExecuted::class, Argument::type(Closure::class)); $container = Container::getInstance(); $container->instance('events', $mockEventDispatcher); @@ -160,14 +164,14 @@ public function testListenForFailuresRegistersCallback(): void public function testCommandExecutedNotDispatchedWhenNoListeners(): void { - $mockEventDispatcher = m::mock(Dispatcher::class); - $mockEventDispatcher->shouldReceive('hasListeners') + $mockEventDispatcher = Double::for(Dispatcher::class); + $mockEventDispatcher->allows('hasListeners') ->with(CommandFailed::class) - ->andReturn(false); - $mockEventDispatcher->shouldReceive('hasListeners') + ->returns(false); + $mockEventDispatcher->allows('hasListeners') ->with(CommandExecuted::class) - ->andReturn(false); - $mockEventDispatcher->shouldNotReceive('dispatch'); + ->returns(false); + $mockEventDispatcher->expects('dispatch')->never(); $connection = $this->createMockRedisConnection('get', 'value', null, $mockEventDispatcher); $connection->expects('release'); @@ -181,14 +185,14 @@ public function testCommandFailedNotDispatchedWhenNoListeners(): void { $exception = new Exception('Redis error'); - $mockEventDispatcher = m::mock(Dispatcher::class); - $mockEventDispatcher->shouldReceive('hasListeners') + $mockEventDispatcher = Double::for(Dispatcher::class); + $mockEventDispatcher->allows('hasListeners') ->with(CommandFailed::class) - ->andReturn(false); - $mockEventDispatcher->shouldReceive('hasListeners') + ->returns(false); + $mockEventDispatcher->allows('hasListeners') ->with(CommandExecuted::class) - ->andReturn(false); - $mockEventDispatcher->shouldNotReceive('dispatch'); + ->returns(false); + $mockEventDispatcher->expects('dispatch')->never(); $connection = $this->createMockRedisConnection('get', null, $exception, $mockEventDispatcher); $connection->expects('release'); @@ -239,19 +243,19 @@ public function testListenForFailuresNoOpsWhenEventsUnbound(): void /** * Create a Redis proxy using the given connection. */ - private function createRedis(m\MockInterface|RedisConnection $connection): RedisProxy + private function createRedis(RedisConnection $connection): RedisProxy { - $pool = m::mock(RedisPool::class); - $pool->shouldReceive('borrow')->andReturn($connection); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray([])); + $pool = Double::for(RedisPool::class); + $pool->allows('borrow')->returns($connection); + $pool->allows('getOptions')->returns(PoolOptions::fromArray([])); - $poolManager = m::mock(PoolManager::class)->makePartial(); - $poolManager->shouldReceive('pool')->with('default')->andReturn($pool); + $poolManager = Double::for(PoolManager::class); + $poolManager->allows('pool')->with('default')->returns($pool); return new RedisProxy( $poolManager, 'default', - m::mock(RedisSentinelFactory::class), + Double::for(RedisSentinelFactory::class), ); } @@ -263,29 +267,28 @@ private function createMockRedisConnection( mixed $returnValue = 'value', ?Throwable $exception = null, ?Dispatcher $eventDispatcher = null - ): RedisConnection&m\MockInterface { - $mockPhpRedis = m::mock(PhpRedis::class); + ): RedisConnection&DoubleInterface { + $mockRedisConnection = Double::for(RedisEventsConnection::class); + $mockRedisConnection->allows('shouldTransform')->returns($mockRedisConnection); + $mockRedisConnection->allows('getConnection')->returns($mockRedisConnection); + $mockRedisConnection->allows('getEventDispatcher')->returns($eventDispatcher); + $mockRedisConnection->allows('getName')->returns('default'); if ($exception !== null) { - $mockPhpRedis->expects($command) - ->with('key') - ->andThrow($exception); + $mockRedisConnection->expects($command)->with('key')->throws($exception); } else { - $mockPhpRedis->shouldReceive($command) - ->andReturn($returnValue); + $mockRedisConnection->allows($command)->with('key')->returns($returnValue); } - $mockRedisConnection = m::mock(PhpRedisConnection::class); - $mockRedisConnection->shouldReceive('shouldTransform')->andReturnSelf(); - $mockRedisConnection->shouldReceive('getConnection')->andReturn($mockRedisConnection); - $mockRedisConnection->shouldReceive('getEventDispatcher')->andReturn($eventDispatcher); - $mockRedisConnection->shouldReceive('getName')->andReturn('default'); - - $mockRedisConnection->shouldReceive($command) - ->andReturnUsing(function (mixed ...$arguments) use ($mockPhpRedis, $command): mixed { - return $mockPhpRedis->{$command}(...$arguments); - }); - return $mockRedisConnection; } } + +// Declare the dynamic command so Double can enforce its arguments and call count. +abstract class RedisEventsConnection extends PhpRedisConnection +{ + /** + * Get the value stored at the key. + */ + abstract public function get(string $key): mixed; +} diff --git a/tests/Routing/RoutingRedirectorTest.php b/tests/Routing/RoutingRedirectorTest.php index 753c37e4b..9ba86e2c0 100644 --- a/tests/Routing/RoutingRedirectorTest.php +++ b/tests/Routing/RoutingRedirectorTest.php @@ -11,11 +11,14 @@ use Hypervel\Routing\UrlGenerator; use Hypervel\Session\NullSessionHandler; use Hypervel\Session\Store; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\HeaderBag; class RoutingRedirectorTest extends RoutingTestCase { + use VerifiesDoubles; + protected HeaderBag $headers; protected Request $request; @@ -32,22 +35,18 @@ protected function setUp(): void $this->headers = new HeaderBag; - $this->request = m::mock(Request::class); - $this->request->shouldReceive('isMethod')->andReturn(true)->byDefault(); - $this->request->shouldReceive('method')->andReturn('GET')->byDefault(); - $this->request->shouldReceive('route')->andReturn(true)->byDefault(); - $this->request->shouldReceive('ajax')->andReturn(false)->byDefault(); - $this->request->shouldReceive('expectsJson')->andReturn(false)->byDefault(); + $this->request = Request::create('/', 'GET'); + $this->request->setRouteResolver(fn (): bool => true); $this->request->headers = $this->headers; - $this->url = m::mock(UrlGenerator::class); - $this->url->shouldReceive('getRequest')->andReturn($this->request); - $this->url->shouldReceive('to')->with('bar', [], null)->andReturn('http://foo.com/bar'); - $this->url->shouldReceive('to')->with('bar', [], true)->andReturn('https://foo.com/bar'); - $this->url->shouldReceive('to')->with('login', [], null)->andReturn('http://foo.com/login'); - $this->url->shouldReceive('to')->with('http://foo.com/bar', [], null)->andReturn('http://foo.com/bar'); - $this->url->shouldReceive('to')->with('/', [], null)->andReturn('http://foo.com/'); - $this->url->shouldReceive('to')->with('http://foo.com/bar?signature=secret', [], null)->andReturn('http://foo.com/bar?signature=secret'); + $this->url = Double::for(UrlGenerator::class); + $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'); + $this->url->allows('to')->with('login', [], null)->returns('http://foo.com/login'); + $this->url->allows('to')->with('http://foo.com/bar', [], null)->returns('http://foo.com/bar'); + $this->url->allows('to')->with('/', [], null)->returns('http://foo.com/'); + $this->url->allows('to')->with('http://foo.com/bar?signature=secret', [], null)->returns('http://foo.com/bar?signature=secret'); $this->session = new Store('test', new NullSessionHandler); @@ -77,7 +76,7 @@ public function testComplexRedirectTo(): void public function testGuestPutCurrentUrlInSession(): void { - $this->url->expects('full')->andReturn('http://foo.com/bar'); + $this->url->expects('full')->returns('http://foo.com/bar'); $response = $this->redirect->guest('login'); @@ -87,8 +86,8 @@ public function testGuestPutCurrentUrlInSession(): void public function testGuestPutPreviousUrlInSession(): void { - $this->request->expects('isMethod')->with('GET')->andReturn(false); - $this->url->expects('previous')->andReturn('http://foo.com/bar'); + $this->request->setMethod('POST'); + $this->url->expects('previous')->returns('http://foo.com/bar'); $response = $this->redirect->guest('login'); @@ -119,14 +118,14 @@ public function testIntendedWithoutIntendedUrlInSession(): void public function testRefreshRedirectToCurrentUrl(): void { - $this->request->expects('path')->andReturn('http://foo.com/bar'); + $this->url->allows('getRequest')->returns(Request::create('/bar')); $response = $this->redirect->refresh(); $this->assertSame('http://foo.com/bar', $response->getTargetUrl()); } public function testBackRedirectToHttpReferer(): void { - $this->url->expects('previous')->andReturn('http://foo.com/bar'); + $this->url->expects('previous')->returns('http://foo.com/bar'); $response = $this->redirect->back(); $this->assertSame('http://foo.com/bar', $response->getTargetUrl()); } @@ -145,14 +144,14 @@ public function testSecureRedirectToHttpsUrl(): void public function testAction(): void { - $this->url->expects('action')->with('bar@index', [])->andReturn('http://foo.com/bar'); + $this->url->expects('action')->with('bar@index', [])->returns('http://foo.com/bar'); $response = $this->redirect->action('bar@index'); $this->assertSame('http://foo.com/bar', $response->getTargetUrl()); } public function testRoute(): void { - $this->url->expects('route')->with('home', [])->andReturn('http://foo.com/bar'); + $this->url->expects('route')->with('home', [])->returns('http://foo.com/bar'); $response = $this->redirect->route('home'); $this->assertSame('http://foo.com/bar', $response->getTargetUrl()); @@ -160,9 +159,9 @@ public function testRoute(): void public function testRouteAcceptsUrlRoutableParameters(): void { - $parameter = m::mock(UrlRoutable::class); + $parameter = Double::for(UrlRoutable::class); - $this->url->expects('route')->with('home', $parameter)->andReturn('http://foo.com/bar'); + $this->url->expects('route')->with('home', $parameter)->returns('http://foo.com/bar'); $response = $this->redirect->route('home', $parameter); @@ -171,7 +170,7 @@ public function testRouteAcceptsUrlRoutableParameters(): void public function testSignedRoute(): void { - $this->url->expects('signedRoute')->with('home', [], null)->andReturn('http://foo.com/bar?signature=secret'); + $this->url->expects('signedRoute')->with('home', [], null)->returns('http://foo.com/bar?signature=secret'); $response = $this->redirect->signedRoute('home'); $this->assertSame('http://foo.com/bar?signature=secret', $response->getTargetUrl()); @@ -179,7 +178,7 @@ public function testSignedRoute(): void public function testTemporarySignedRoute(): void { - $this->url->expects('temporarySignedRoute')->with('home', 10, [])->andReturn('http://foo.com/bar?signature=secret'); + $this->url->expects('temporarySignedRoute')->with('home', 10, [])->returns('http://foo.com/bar?signature=secret'); $response = $this->redirect->temporarySignedRoute('home', 10); $this->assertSame('http://foo.com/bar?signature=secret', $response->getTargetUrl()); diff --git a/tests/Routing/RoutingResponseFactoryTest.php b/tests/Routing/RoutingResponseFactoryTest.php index 3e11b657e..c23d206bf 100644 --- a/tests/Routing/RoutingResponseFactoryTest.php +++ b/tests/Routing/RoutingResponseFactoryTest.php @@ -13,7 +13,8 @@ use Hypervel\Routing\Redirector; use Hypervel\Routing\ResponseFactory; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -23,6 +24,8 @@ class RoutingResponseFactoryTest extends TestCase { + use VerifiesDoubles; + // PHPUnit's output capture runs outside the test coroutine. protected bool $runTestsInCoroutine = false; @@ -174,8 +177,8 @@ public function testStreamingFactoriesPassCancellationThroughWithoutReportingOrW { $failure = new CanceledException('response canceled'); $cleanup = new RuntimeException('cleanup failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->never(); Container::getInstance()->instance(ExceptionHandler::class, $handler); $operation = static function () use ($failure, $cleanup, $cleanupThrows): never { try { @@ -225,8 +228,8 @@ public static function streamingFactoryMethods(): array private function factory(): ResponseFactory { return new ResponseFactory( - m::mock(ViewFactory::class), - m::mock(Redirector::class), + Double::for(ViewFactory::class), + Double::for(Redirector::class), ); } } diff --git a/tests/Session/EncryptedSessionStoreTest.php b/tests/Session/EncryptedSessionStoreTest.php index fc3467ba5..ab116e0b1 100644 --- a/tests/Session/EncryptedSessionStoreTest.php +++ b/tests/Session/EncryptedSessionStoreTest.php @@ -7,16 +7,19 @@ use Hypervel\Contracts\Encryption\Encrypter; use Hypervel\Session\EncryptedStore; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use SessionHandlerInterface; class EncryptedSessionStoreTest extends TestCase { + use VerifiesDoubles; + public function testSessionIsProperlyEncrypted(): void { $session = $this->getSession(); - $session->getEncrypter()->expects('decrypt')->with(serialize([]))->andReturn(serialize([])); - $session->getHandler()->expects('read')->andReturn(serialize([])); + $session->getEncrypter()->expects('decrypt')->with(serialize([]))->returns(serialize([])); + $session->getHandler()->expects('read')->returns(serialize([])); $session->start(); $session->put('foo', 'bar'); $session->flash('baz', 'boom'); @@ -30,11 +33,11 @@ public function testSessionIsProperlyEncrypted(): void 'old' => ['baz'], ], ]); - $session->getEncrypter()->expects('encrypt')->with($serialized)->andReturn($serialized); + $session->getEncrypter()->expects('encrypt')->with($serialized)->returns($serialized); $session->getHandler()->expects('write')->with( $this->getSessionId(), $serialized - )->andReturnTrue(); + )->returns(true); $session->save(); $this->assertFalse($session->isStarted()); @@ -47,8 +50,8 @@ public function getSession(): EncryptedStore { return new EncryptedStore( $this->getSessionName(), - m::mock(SessionHandlerInterface::class), - m::mock(Encrypter::class), + Double::for(SessionHandlerInterface::class), + Double::for(Encrypter::class), $this->getSessionId() ); } diff --git a/tests/Session/FileSessionHandlerTest.php b/tests/Session/FileSessionHandlerTest.php index aa07018b5..7b2a17209 100644 --- a/tests/Session/FileSessionHandlerTest.php +++ b/tests/Session/FileSessionHandlerTest.php @@ -11,13 +11,17 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use function Hypervel\Filesystem\join_paths; class FileSessionHandlerTest extends TestCase { + use VerifiesDoubles; + protected Filesystem $files; protected FileSessionHandler $sessionHandler; @@ -26,7 +30,7 @@ protected function setUp(): void { parent::setUp(); - $this->files = m::mock(Filesystem::class); + $this->files = Double::for(Filesystem::class); $this->sessionHandler = new FileSessionHandler($this->files, '/path/to/sessions', 30); } @@ -53,7 +57,7 @@ public function testValidateIdChecksFileExists(): void $sessionId = 'session_id'; $path = '/path/to/sessions/' . $sessionId; - $this->files->expects('isFile')->with($path)->andReturn(true); + $this->files->expects('isFile')->with($path)->returns(true); $this->assertTrue($this->sessionHandler->validateId($sessionId)); } @@ -64,11 +68,11 @@ public function testReadReturnsDataWhenFileExistsAndIsValid(): void $path = '/path/to/sessions/' . $sessionId; CarbonImmutable::setTestNow(CarbonImmutable::parse('2025-02-02 01:30:00')); - $this->files->expects('isFile')->with($path)->andReturn(true); + $this->files->expects('isFile')->with($path)->returns(true); $minutesAgo30 = CarbonImmutable::parse('2025-02-02 01:00:00')->getTimestamp(); - $this->files->expects('lastModified')->with($path)->andReturn($minutesAgo30); - $this->files->expects('sharedGet')->with($path)->andReturn('session_data'); + $this->files->expects('lastModified')->with($path)->returns($minutesAgo30); + $this->files->expects('sharedGet')->with($path)->returns('session_data'); $result = $this->sessionHandler->read($sessionId); @@ -81,11 +85,11 @@ public function testReadReturnsEmptyStringWhenFileExistsButExpired(): void $path = '/path/to/sessions/' . $sessionId; CarbonImmutable::setTestNow(CarbonImmutable::parse('2025-02-02 01:30:01')); - $this->files->expects('isFile')->with($path)->andReturn(true); + $this->files->expects('isFile')->with($path)->returns(true); $minutesAgo30 = CarbonImmutable::parse('2025-02-02 01:00:00')->getTimestamp(); - $this->files->expects('lastModified')->with($path)->andReturn($minutesAgo30); - $this->files->shouldReceive('sharedGet')->never(); + $this->files->expects('lastModified')->with($path)->returns($minutesAgo30); + $this->files->expects('sharedGet')->never(); $result = $this->sessionHandler->read($sessionId); @@ -97,7 +101,7 @@ public function testReadReturnsEmptyStringWhenFileDoesNotExist(): void $sessionId = 'non_existing_session_id'; $path = '/path/to/sessions/' . $sessionId; - $this->files->expects('isFile')->with($path)->andReturn(false); + $this->files->expects('isFile')->with($path)->returns(false); $result = $this->sessionHandler->read($sessionId); @@ -110,9 +114,9 @@ public function testReadReturnsEmptyStringWhenTheSessionFileDisappearsBeforeRead $path = '/path/to/sessions/' . $sessionId; CarbonImmutable::setTestNow(CarbonImmutable::parse('2025-02-02 01:30:00')); - $this->files->expects('isFile')->with($path)->andReturnTrue(); - $this->files->expects('lastModified')->with($path)->andReturn(CarbonImmutable::now()->getTimestamp()); - $this->files->expects('sharedGet')->with($path)->andThrow( + $this->files->expects('isFile')->with($path)->returns(true); + $this->files->expects('lastModified')->with($path)->returns(CarbonImmutable::now()->getTimestamp()); + $this->files->expects('sharedGet')->with($path)->throws( new FileNotFoundException("Unable to read file at path {$path}.") ); @@ -124,7 +128,7 @@ public function testWriteStoresData(): void $sessionId = 'session_id'; $data = 'session_data'; - $this->files->expects('put')->with('/path/to/sessions/' . $sessionId, $data, true)->andReturn(strlen($data)); + $this->files->expects('put')->with('/path/to/sessions/' . $sessionId, $data, true)->returns(strlen($data)); $result = $this->sessionHandler->write($sessionId, $data); @@ -136,10 +140,10 @@ public function testWriteRejectsFalseAndShortFilesystemWrites(): void $data = 'session_data'; foreach ([false, strlen($data) - 1] as $written) { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $files->expects('put') ->with('/path/to/sessions/session_id', $data, true) - ->andReturn($written); + ->returns($written); $handler = new FileSessionHandler($files, '/path/to/sessions', 30); @@ -151,8 +155,8 @@ public function testFailedFileWriteLeavesLiveSessionStateUntouched(): void { $sessionId = str_repeat('a', 40); $path = '/path/to/sessions/' . $sessionId; - $this->files->expects('isFile')->with($path)->andReturnFalse(); - $this->files->expects('put')->with($path, m::type('string'), true)->andReturnFalse(); + $this->files->expects('isFile')->with($path)->returns(false); + $this->files->expects('put')->with($path, Argument::type('string'), true)->returns(false); $session = new Store('name', $this->sessionHandler, $sessionId); $session->start(); @@ -174,7 +178,7 @@ public function testDestroyDeletesSessionFile(): void { $sessionId = 'session_id'; - $this->files->expects('delete')->with('/path/to/sessions/' . $sessionId)->andReturn(true); + $this->files->expects('delete')->with('/path/to/sessions/' . $sessionId)->returns(true); $result = $this->sessionHandler->destroy($sessionId); @@ -190,8 +194,8 @@ public function testGcDeletesOldSessionFiles(): void try { $session = new FileSessionHandler($this->files, $tempDir, 30); - $this->files->expects('delete')->with(join_paths($tempDir, 'a2'))->andReturn(false); - $this->files->expects('delete')->with(join_paths($tempDir, 'a3'))->andReturn(true); + $this->files->expects('delete')->with(join_paths($tempDir, 'a2'))->returns(false); + $this->files->expects('delete')->with(join_paths($tempDir, 'a3'))->returns(true); touch(join_paths($tempDir, 'a1'), time() - 3); // last modified: 3 sec ago touch(join_paths($tempDir, 'a2'), time() - 5); // last modified: 5 sec ago diff --git a/tests/Session/Middleware/AuthenticateSessionTest.php b/tests/Session/Middleware/AuthenticateSessionTest.php index 54199b141..eece16784 100644 --- a/tests/Session/Middleware/AuthenticateSessionTest.php +++ b/tests/Session/Middleware/AuthenticateSessionTest.php @@ -4,356 +4,40 @@ namespace Hypervel\Tests\Session\Middleware; -use Hypervel\Auth\AuthenticationException; -use Hypervel\Auth\AuthManager; -use Hypervel\Container\Container; +use Hypervel\Auth\SessionGuard; use Hypervel\Contracts\Auth\Authenticatable; use Hypervel\Contracts\Auth\Factory as AuthFactory; use Hypervel\Contracts\Auth\Guard; -use Hypervel\Contracts\Auth\StatefulGuard; use Hypervel\Http\Request; use Hypervel\Session\ArraySessionHandler; use Hypervel\Session\Middleware\AuthenticateSession; use Hypervel\Session\Store; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class AuthenticateSessionTest extends TestCase { - public function testHandleWithoutSession(): void - { - $request = new Request; - $next = fn (): string => 'next-1'; - - $authFactory = m::mock(AuthFactory::class); - $authFactory->shouldReceive('viaRemember')->never(); - - $middleware = new AuthenticateSession($authFactory); - $response = $middleware->handle($request, $next); - $this->assertSame('next-1', $response); - } - - public function testHandleWithSessionWithoutRequestUser(): void - { - $request = new Request; - - // set session: - $request->setHypervelSession(new Store('name', new ArraySessionHandler(1))); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->shouldReceive('viaRemember')->never(); - - $next = fn (): string => 'next-2'; - $middleware = new AuthenticateSession($authFactory); - $response = $middleware->handle($request, $next); - $this->assertSame('next-2', $response); - } - - public function testHandleWithSessionWithoutAuthPassword(): void - { - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): ?string - { - return null; - } - }; - - $request = new Request; - - // set session: - $request->setHypervelSession(new Store('name', new ArraySessionHandler(1))); - // set a password-less user: - $request->setUserResolver(fn (): object => $user); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->shouldReceive('viaRemember')->never(); - - $next = fn (): string => 'next-3'; - $middleware = new AuthenticateSession($authFactory); - $response = $middleware->handle($request, $next); - - $this->assertSame('next-3', $response); - } - - public function testHandleWithSessionWithUserAuthPasswordOnRequestViaRememberFalse(): void - { - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): string - { - return 'my-pass-(*&^%$#!@'; - } - }; - - $request = new Request; - $request->setUserResolver(fn (): object => $user); - - $session = new Store('name', new ArraySessionHandler(1)); - $request->setHypervelSession($session); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->expects('viaRemember')->andReturn(false); - $authFactory->expects('getDefaultDriver')->times(3)->andReturn('web'); - $authFactory->expects('user')->andReturn(null); - // expected MAC for current password when storing in session: - $authFactory->expects('hashPasswordForCookie')->times(2)->with('my-pass-(*&^%$#!@')->andReturn('mac:my-pass-(*&^%$#!@'); - - $middleware = new AuthenticateSession($authFactory); - $response = $middleware->handle($request, fn (): string => 'next-4'); - - $this->assertSame('mac:my-pass-(*&^%$#!@', $session->get('password_hash_web')); - $this->assertSame('next-4', $response); - } - - public function testHandleWithInvalidPasswordHash(): void - { - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): string - { - return 'my-pass-(*&^%$#!@'; - } - }; - - $request = new Request(cookies: ['recaller-name' => 'a|b|invalid-mac']); - $request->setUserResolver(fn (): object => $user); - - $session = new Store('name', new ArraySessionHandler(1)); - $session->put('a', '1'); - $session->put('b', '2'); - // set session: - $request->setHypervelSession($session); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->expects('viaRemember')->andReturn(true); - $authFactory->expects('getRecallerName')->andReturn('recaller-name'); - $authFactory->expects('logoutCurrentDevice')->andReturn(null); - $authFactory->expects('getDefaultDriver')->andReturn('web'); - // expected MAC for current password (won't match cookie): - $authFactory->expects('hashPasswordForCookie')->with('my-pass-(*&^%$#!@')->andReturn('mac:my-pass-(*&^%$#!@'); - - $this->assertNotNull($session->get('a')); - $this->assertNotNull($session->get('b')); - AuthenticateSession::redirectUsing(fn (Request $request): string => 'i-wanna-go-home'); - - // act: - $middleware = new AuthenticateSession($authFactory); - - $message = ''; - try { - $middleware->handle($request, fn (): string => 'next-7'); - } catch (AuthenticationException $e) { - $message = $e->getMessage(); - $this->assertSame('i-wanna-go-home', $e->redirectTo($request)); - } - $this->assertSame('Unauthenticated.', $message); - - // ensure session is flushed: - $this->assertNull($session->get('a')); - $this->assertNull($session->get('b')); - } - - public function testAuthManagerRedirectGuestsToConfiguresSessionMismatchRedirect(): void - { - $manager = new AuthManager(new Container); - $manager->redirectGuestsTo('/login'); - - // Isolate AuthenticateSession's own slot so this test fails if the - // aggregate stops configuring session-mismatch redirects directly. - AuthenticationException::flushState(); - - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): string - { - return 'my-pass-(*&^%$#!@'; - } - }; - - $request = new Request(cookies: ['recaller-name' => 'a|b|invalid-mac']); - $request->setUserResolver(fn (): object => $user); - - $session = new Store('name', new ArraySessionHandler(1)); - $request->setHypervelSession($session); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->expects('viaRemember')->andReturn(true); - $authFactory->expects('getRecallerName')->andReturn('recaller-name'); - $authFactory->expects('logoutCurrentDevice')->andReturn(null); - $authFactory->expects('getDefaultDriver')->andReturn('web'); - $authFactory->expects('hashPasswordForCookie')->with('my-pass-(*&^%$#!@')->andReturn('mac:my-pass-(*&^%$#!@'); - - try { - (new AuthenticateSession($authFactory))->handle($request, fn (): string => 'next'); - } catch (AuthenticationException $exception) { - $this->assertSame('/login', $exception->redirectTo($request)); - - return; - } - - $this->fail('AuthenticationException was not thrown.'); - } - - public function testHandleWithInvalidIncookiePasswordHashViaRememberTrue(): void - { - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): string - { - return 'my-pass-(*&^%$#!@'; - } - }; - - $request = new Request(cookies: ['recaller-name' => 'a|b|invalid-mac']); - $request->setUserResolver(fn (): object => $user); - - $session = new Store('name', new ArraySessionHandler(1)); - $session->put('a', '1'); - $session->put('b', '2'); - // set session: - $request->setHypervelSession($session); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->expects('viaRemember')->andReturn(true); - $authFactory->expects('getRecallerName')->andReturn('recaller-name'); - $authFactory->expects('logoutCurrentDevice'); - $authFactory->expects('getDefaultDriver')->andReturn('web'); - // expected MAC for current password (won't match cookie): - $authFactory->expects('hashPasswordForCookie')->with('my-pass-(*&^%$#!@')->andReturn('mac:my-pass-(*&^%$#!@'); - - $middleware = new AuthenticateSession($authFactory); - // act: - try { - $message = ''; - $middleware->handle($request, fn (): string => 'next-6'); - } catch (AuthenticationException $e) { - $message = $e->getMessage(); - } - $this->assertSame('Unauthenticated.', $message); - - // ensure session is flushed - $this->assertNull($session->get('password_hash_web')); - $this->assertNull($session->get('a')); - $this->assertNull($session->get('b')); - } - - public function testHandleWithValidIncookieInvalidInsessionHashViaRememberTrue(): void - { - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): string - { - return 'my-pass-(*&^%$#!@'; - } - }; - - $request = new Request(cookies: ['recaller-name' => 'a|b|mac:my-pass-(*&^%$#!@']); - $request->setUserResolver(fn (): object => $user); - - $session = new Store('name', new ArraySessionHandler(1)); - $session->put('a', '1'); - $session->put('b', '2'); - $session->put('password_hash_web', 'invalid-password'); - // set session on the request: - $request->setHypervelSession($session); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->expects('viaRemember')->andReturn(true); - $authFactory->expects('getRecallerName')->andReturn('recaller-name'); - $authFactory->expects('logoutCurrentDevice')->andReturn(null); - $authFactory->expects('getDefaultDriver')->times(3)->andReturn('web'); - // expected MAC for current password (matches cookie but not session): - $authFactory->expects('hashPasswordForCookie')->times(2)->with('my-pass-(*&^%$#!@')->andReturn('mac:my-pass-(*&^%$#!@'); - - // act: - $middleware = new AuthenticateSession($authFactory); - try { - $message = ''; - $middleware->handle($request, fn (): string => 'next-7'); - } catch (AuthenticationException $e) { - $message = $e->getMessage(); - } - $this->assertSame('Unauthenticated.', $message); - - // ensure session is flushed: - $this->assertNull($session->get('password_hash_web')); - $this->assertNull($session->get('a')); - $this->assertNull($session->get('b')); - } - - public function testHandleWithValidPasswordInSessionCookieIsEmptyGuardHasUser(): void - { - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): string - { - return 'my-pass-(*&^%$#!@'; - } - }; - - $request = new Request(cookies: ['recaller-name' => 'a|b']); - $request->setUserResolver(fn (): object => $user); - - $session = new Store('name', new ArraySessionHandler(1)); - $session->put('a', '1'); - $session->put('b', '2'); - $session->put('password_hash_web', 'mac:my-pass-(*&^%$#!@'); - // set session on the request: - $request->setHypervelSession($session); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->expects('viaRemember')->andReturn(false); - $authFactory->shouldReceive('getRecallerName')->never(); - $authFactory->shouldReceive('logoutCurrentDevice')->never(); - $authFactory->expects('getDefaultDriver')->times(3)->andReturn('web'); - $authFactory->expects('user')->andReturn($user); - // expected MAC for current password: - $authFactory->expects('hashPasswordForCookie')->times(2)->with('my-pass-(*&^%$#!@')->andReturn('mac:my-pass-(*&^%$#!@'); - - // act: - $middleware = new AuthenticateSession($authFactory); - $response = $middleware->handle($request, fn (): string => 'next-8'); - - $this->assertSame('next-8', $response); - // ensure session is not flushed: - $this->assertSame('mac:my-pass-(*&^%$#!@', $session->get('password_hash_web')); - $this->assertSame('1', $session->get('a')); - $this->assertSame('2', $session->get('b')); - } + use VerifiesDoubles; public function testGuardOverrideCanReturnAConcreteGuard(): void { - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthPassword')->andReturn('password-hash'); + $user = Double::for(Authenticatable::class); + $user->allows('getAuthPassword')->returns('password-hash'); $request = new Request; $request->setUserResolver(fn (): Authenticatable => $user); $session = new Store('name', new ArraySessionHandler(1)); $request->setHypervelSession($session); - $guard = m::mock(StatefulGuard::class); - $guard->expects('viaRemember')->andReturn(false); - $guard->expects('hashPasswordForCookie')->twice()->with('password-hash')->andReturn('password-mac'); - $guard->expects('user')->andReturn(null); + $guard = Double::for(SessionGuard::class); + $guard->expects('viaRemember')->returns(false); + $guard->expects('hashPasswordForCookie')->times(2)->with('password-hash')->returns('password-mac'); + $guard->expects('user')->returns(null); - $authFactory = m::mock(AuthFactory::class); - $authFactory->shouldReceive('guard')->andReturn($guard); - $authFactory->shouldReceive('getDefaultDriver')->andReturn('web'); + $authFactory = Double::for(AuthFactory::class); + $authFactory->allows('guard')->returns($guard); + $authFactory->allows('getDefaultDriver')->returns('web'); $middleware = new class($authFactory) extends AuthenticateSession { /** @@ -368,133 +52,4 @@ protected function guard(): Guard $this->assertSame('next', $middleware->handle($request, fn (): string => 'next')); $this->assertSame('password-mac', $session->get('password_hash_web')); } - - // REMOVED: Laravel's OldFormatCookie* backward-compatibility tests, - // including guards without hashPasswordForCookie(); only HMAC artifacts are supported. - public function testHandleWithRawRememberCookiePasswordHashLogsOut(): void - { - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): string - { - return 'my-pass-(*&^%$#!@'; - } - }; - - $request = new Request(cookies: ['recaller-name' => 'a|b|my-pass-(*&^%$#!@']); - $request->setUserResolver(fn (): object => $user); - - $session = new Store('name', new ArraySessionHandler(1)); - $session->put('a', '1'); - $session->put('b', '2'); - $request->setHypervelSession($session); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->expects('viaRemember')->andReturn(true); - $authFactory->expects('getRecallerName')->andReturn('recaller-name'); - $authFactory->expects('logoutCurrentDevice')->andReturn(null); - $authFactory->expects('getDefaultDriver')->andReturn('web'); - $authFactory->expects('hashPasswordForCookie')->with('my-pass-(*&^%$#!@')->andReturn('mac:my-pass-(*&^%$#!@'); - - $middleware = new AuthenticateSession($authFactory); - - $message = ''; - try { - $middleware->handle($request, fn (): string => 'next-9'); - } catch (AuthenticationException $e) { - $message = $e->getMessage(); - } - - $this->assertSame('Unauthenticated.', $message); - $this->assertNull($session->get('a')); - $this->assertNull($session->get('b')); - } - - public function testHandleWithRawSessionPasswordHashLogsOut(): void - { - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): string - { - return 'my-pass-(*&^%$#!@'; - } - }; - - $request = new Request; - $request->setUserResolver(fn (): object => $user); - - $session = new Store('name', new ArraySessionHandler(1)); - $session->put('a', '1'); - $session->put('b', '2'); - $session->put('password_hash_web', 'my-pass-(*&^%$#!@'); - $request->setHypervelSession($session); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->expects('viaRemember')->andReturn(false); - $authFactory->shouldReceive('getRecallerName')->never(); - $authFactory->expects('logoutCurrentDevice')->andReturn(null); - $authFactory->expects('getDefaultDriver')->times(3)->andReturn('web'); - $authFactory->expects('hashPasswordForCookie')->with('my-pass-(*&^%$#!@')->andReturn('mac:my-pass-(*&^%$#!@'); - - $middleware = new AuthenticateSession($authFactory); - - $message = ''; - try { - $middleware->handle($request, fn (): string => 'next-9'); - } catch (AuthenticationException $e) { - $message = $e->getMessage(); - } - - $this->assertSame('Unauthenticated.', $message); - $this->assertNull($session->get('password_hash_web')); - $this->assertNull($session->get('a')); - $this->assertNull($session->get('b')); - } - - public function testHandleWithMalformedSessionPasswordHashLogsOut(): void - { - $user = new class { - /** - * Get the user's authentication password. - */ - public function getAuthPassword(): string - { - return 'my-pass-(*&^%$#!@'; - } - }; - - $request = new Request; - $request->setUserResolver(fn (): object => $user); - - $session = new Store('name', new ArraySessionHandler(1)); - $session->put('a', '1'); - $session->put('b', '2'); - $session->put('password_hash_web', ['not-a-password-hash']); - $request->setHypervelSession($session); - - $authFactory = m::mock(AuthFactory::class); - $authFactory->expects('viaRemember')->andReturn(false); - $authFactory->shouldReceive('getRecallerName')->never(); - $authFactory->expects('logoutCurrentDevice')->andReturn(null); - $authFactory->expects('getDefaultDriver')->times(3)->andReturn('web'); - $authFactory->shouldReceive('hashPasswordForCookie')->never(); - - $middleware = new AuthenticateSession($authFactory); - - $message = ''; - try { - $middleware->handle($request, fn (): string => 'next-10'); - } catch (AuthenticationException $e) { - $message = $e->getMessage(); - } - - $this->assertSame('Unauthenticated.', $message); - $this->assertNull($session->get('password_hash_web')); - $this->assertNull($session->get('a')); - $this->assertNull($session->get('b')); - } } diff --git a/tests/Session/SessionManagerTest.php b/tests/Session/SessionManagerTest.php index 36ffe9256..0b105f5cf 100644 --- a/tests/Session/SessionManagerTest.php +++ b/tests/Session/SessionManagerTest.php @@ -25,13 +25,16 @@ use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use SessionHandlerInterface; class SessionManagerTest extends TestCase { + use VerifiesDoubles; + // REMOVED: CacheBasedSessionHandlerTest; Redis sessions use a dedicated handler, // and the APC, Memcached and DynamoDB session drivers are unsupported. @@ -57,7 +60,7 @@ public function testEnumDefaultDriverIsNormalizedWithoutTreatingZeroAsAbsent(): ], ])); - $manager->extend('0', fn () => m::mock(SessionHandlerInterface::class)); + $manager->extend('0', fn () => Double::for(SessionHandlerInterface::class)); $manager->setDefaultDriver(SessionIntegerIdentifier::Zero); $this->assertSame('0', $manager->getDefaultDriver()); @@ -96,7 +99,7 @@ public function testRedisDriverUsesConfiguredSessionPrefix(): void 'session.track_user_sessions' => false, 'cache.prefix' => 'cache_prefix', ]); - $container->instance(RedisFactory::class, m::mock(RedisFactory::class)); + $container->instance(RedisFactory::class, Double::for(RedisFactory::class)); $sessionStore = (new SessionManager($container))->driver(); $handler = $this->handlerFromStore($sessionStore); @@ -142,7 +145,7 @@ public function testExplicitSessionConnectionOverridesBothDrivers(): void 'session.prefix' => 'application_session:', 'session.track_user_sessions' => true, ]); - $redis = m::mock(RedisFactory::class); + $redis = Double::for(RedisFactory::class); $container->instance(RedisFactory::class, $redis); $redisSessionStore = (new SessionManager($container))->driver(); @@ -179,7 +182,7 @@ public function testCapabilityProbeReflectsTheConfiguredHandler(): void 'session.prefix' => 'application_session:', 'session.track_user_sessions' => $tracking, ]); - $container->instance(RedisFactory::class, m::mock(RedisFactory::class)); + $container->instance(RedisFactory::class, Double::for(RedisFactory::class)); $this->assertSame( $tracking, @@ -225,8 +228,8 @@ public function testForUserExtractsAnAuthenticatableIdentifier(): void { $handler = new SessionManagerCapableHandler; $manager = $this->customManager($handler); - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->once()->andReturn('user-1'); + $user = Double::for(Authenticatable::class); + $user->expects('getAuthIdentifier')->returns('user-1'); $manager->forUser($user)->all(); @@ -329,8 +332,8 @@ public function testForUserRejectsEmptyAndInvalidModelIdentifiers(): void $this->assertSame('The user identifier may not be empty.', $exception->getMessage()); } - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getAuthIdentifier')->once()->andReturnNull(); + $user = Double::for(Authenticatable::class); + $user->expects('getAuthIdentifier')->returns(null); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('The user identifier must be an integer or string.'); @@ -357,7 +360,7 @@ public function testForUserRejectsUnsupportedAndDisabledDrivers(): void 'session.prefix' => 'application_session:', 'session.track_user_sessions' => false, ]); - $container->instance(RedisFactory::class, m::mock(RedisFactory::class)); + $container->instance(RedisFactory::class, Double::for(RedisFactory::class)); $disabled = new SessionManager($container); foreach ([$unsupported, $disabled] as $manager) { @@ -435,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, m::mock(Encrypter::class)); - $container->instance('db', m::mock(ConnectionResolverInterface::class)); + $container->instance(Encrypter::class, Double::for(Encrypter::class)); + $container->instance('db', Double::for(ConnectionResolverInterface::class)); Container::setInstance($container); diff --git a/tests/Session/SessionStoreTest.php b/tests/Session/SessionStoreTest.php index 965a4e28d..870518fd3 100644 --- a/tests/Session/SessionStoreTest.php +++ b/tests/Session/SessionStoreTest.php @@ -9,6 +9,7 @@ use Hypervel\Container\Container; use Hypervel\Context\CoroutineContext; use Hypervel\Contracts\Auth\Factory as AuthFactory; +use Hypervel\Cookie\CookieJar; use Hypervel\Events\Dispatcher; use Hypervel\Http\Request; use Hypervel\Session\ArraySessionHandler; @@ -24,8 +25,9 @@ use Hypervel\Support\ViewErrorBag; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use RuntimeException; use SessionHandlerInterface; use UnitEnum; @@ -34,10 +36,12 @@ class SessionStoreTest extends TestCase { + use VerifiesDoubles; + public function testSessionIsLoadedFromHandler(): void { $session = $this->getSession(); - $session->getHandler()->expects('read')->with($this->getSessionId())->andReturn(serialize(['foo' => 'bar', 'bagged' => ['name' => 'taylor'], '123' => 'bax'])); + $session->getHandler()->expects('read')->with($this->getSessionId())->returns(serialize(['foo' => 'bar', 'bagged' => ['name' => 'taylor'], '123' => 'bax'])); $session->start(); $this->assertSame('bar', $session->get('foo')); @@ -56,13 +60,13 @@ public function testSessionMigration(): void { $session = $this->getSession(); $oldId = $session->getId(); - $session->getHandler()->shouldReceive('destroy')->never(); + $session->getHandler()->expects('destroy')->never(); $this->assertTrue($session->migrate()); $this->assertNotEquals($oldId, $session->getId()); $session = $this->getSession(); $oldId = $session->getId(); - $session->getHandler()->expects('destroy')->with($oldId); + $session->getHandler()->expects('destroy')->with($oldId)->returns(true); $this->assertTrue($session->migrate(true)); $this->assertNotEquals($oldId, $session->getId()); } @@ -71,7 +75,7 @@ public function testSessionRegeneration(): void { $session = $this->getSession(); $oldId = $session->getId(); - $session->getHandler()->shouldReceive('destroy')->never(); + $session->getHandler()->expects('destroy')->never(); $this->assertTrue($session->regenerate()); $this->assertNotSame($oldId, $session->getId()); $this->assertFalse(UserSessionIdentity::resolve(null, $session->getId())->isUnowned()); @@ -92,8 +96,8 @@ public function testCantSetInvalidId(): void public function testStoresUseIndependentCoroutineState(): void { - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('read')->andReturn(serialize([])); + $handler = Double::for(SessionHandlerInterface::class); + $handler->expects('read')->returns(serialize([])); $first = new Store('first', $handler, str_repeat('a', 40)); $first->start(); @@ -112,7 +116,7 @@ public function testStoresUseIndependentCoroutineState(): void public function testConstructionClearsStaleObjectSpecificCoroutineState(): void { - $handler = m::mock(SessionHandlerInterface::class); + $handler = Double::for(SessionHandlerInterface::class); $session = new class('name', $handler, str_repeat('b', 40)) extends Store { public function __construct(string $name, SessionHandlerInterface $handler, ?string $id = null) @@ -137,7 +141,7 @@ public function __construct(string $name, SessionHandlerInterface $handler, ?str public function testStoreLazilyCreatesAnIdInAFreshCoroutine(): void { - $session = new Store('name', m::mock(SessionHandlerInterface::class), str_repeat('a', 40)); + $session = new Store('name', Double::for(SessionHandlerInterface::class), str_repeat('a', 40)); [$id] = parallel([ fn (): string => $session->getId(), @@ -153,7 +157,7 @@ public function testInvalidSerializationFailsBeforeWritingContext(): void $context = CoroutineContext::captureFrom(); try { - new Store('name', m::mock(SessionHandlerInterface::class), serialization: 'yaml'); + new Store('name', Double::for(SessionHandlerInterface::class), serialization: 'yaml'); $this->fail('Expected invalid session serialization to be rejected.'); } catch (InvalidArgumentException $exception) { @@ -177,7 +181,7 @@ public function testSessionInvalidate(): void $session->flash('name', 'Taylor'); $this->assertTrue($session->has('name')); - $session->getHandler()->expects('destroy')->with($oldId); + $session->getHandler()->expects('destroy')->with($oldId)->returns(true); $this->assertTrue($session->invalidate()); $this->assertFalse($session->has('name')); @@ -189,7 +193,7 @@ public function testSessionInvalidate(): void public function testBrandNewSessionIsProperlySaved(): void { $session = $this->getSession(); - $session->getHandler()->expects('read')->andReturn(serialize([])); + $session->getHandler()->expects('read')->returns(serialize([])); $session->start(); $session->put('foo', 'bar'); $session->flash('baz', 'boom'); @@ -205,7 +209,7 @@ public function testBrandNewSessionIsProperlySaved(): void 'old' => ['baz'], ], ]) - )->andReturnTrue(); + )->returns(true); $session->save(); $this->assertFalse($session->isStarted()); @@ -214,7 +218,7 @@ public function testBrandNewSessionIsProperlySaved(): void public function testSessionIsProperlyUpdated(): void { $session = $this->getSession(); - $session->getHandler()->expects('read')->andReturn(serialize([ + $session->getHandler()->expects('read')->returns(serialize([ '_token' => Str::random(40), 'foo' => 'bar', 'baz' => 'boom', @@ -235,7 +239,7 @@ public function testSessionIsProperlyUpdated(): void 'old' => [], ], ]) - )->andReturnTrue(); + )->returns(true); $session->save(); @@ -245,7 +249,7 @@ public function testSessionIsProperlyUpdated(): void public function testSessionIsReSavedWhenNothingHasChanged(): void { $session = $this->getSession(); - $session->getHandler()->expects('read')->andReturn(serialize([ + $session->getHandler()->expects('read')->returns(serialize([ '_token' => Str::random(40), 'foo' => 'bar', 'baz' => 'boom', @@ -267,7 +271,7 @@ public function testSessionIsReSavedWhenNothingHasChanged(): void 'old' => [], ], ]) - )->andReturnTrue(); + )->returns(true); $session->save(); @@ -279,7 +283,7 @@ public function testSessionIsReSavedWhenNothingHasChangedExceptSessionId(): void $session = $this->getSession(); $oldId = $session->getId(); $token = Str::random(40); - $session->getHandler()->expects('read')->with($oldId)->andReturn(serialize([ + $session->getHandler()->expects('read')->with($oldId)->returns(serialize([ '_token' => $token, 'foo' => 'bar', 'baz' => 'boom', @@ -307,7 +311,7 @@ public function testSessionIsReSavedWhenNothingHasChangedExceptSessionId(): void 'old' => [], ], ]) - )->andReturnTrue(); + )->returns(true); $session->save(); @@ -316,12 +320,12 @@ public function testSessionIsReSavedWhenNothingHasChangedExceptSessionId(): void public function testFailedSaveDoesNotPublishAgedFlashDataBeforeRetry(): void { - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('read')->andReturn(serialize([])); + $handler = Double::for(SessionHandlerInterface::class); + $handler->expects('read')->returns(serialize([])); $attempts = 0; $payloads = []; - $handler->expects('write')->twice()->andReturnUsing( + $handler->expects('write')->times(2)->resolves( function (string $sessionId, string $data) use (&$attempts, &$payloads): bool { $payloads[] = unserialize($data); @@ -360,8 +364,8 @@ function (string $sessionId, string $data) use (&$attempts, &$payloads): bool { public function testReadOnlySessionIsNotSaved(): void { $session = $this->getSession(); - $session->getHandler()->expects('read')->andReturn(serialize([])); - $session->getHandler()->shouldReceive('write')->never(); + $session->getHandler()->expects('read')->returns(serialize([])); + $session->getHandler()->expects('write')->never(); $session->start(); $session->markAsReadOnly(); $session->flash('status', 'saved'); @@ -376,7 +380,7 @@ public function testReadOnlySessionIsNotSaved(): void public function testReadOnlySessionRegenerationDoesNotDestroyTheStoredSession(): void { $session = $this->getSession(); - $session->getHandler()->shouldReceive('destroy')->never(); + $session->getHandler()->expects('destroy')->never(); $session->markAsReadOnly(); $this->assertTrue($session->regenerate(true)); @@ -389,8 +393,8 @@ public function testReadOnlySessionRegenerationDoesNotDestroyTheStoredSession(): public function testStartingTheSessionMakesItWritableAgain(): void { $session = $this->getSession(); - $session->getHandler()->expects('read')->twice()->andReturn(serialize([])); - $session->getHandler()->expects('write')->once()->andReturnTrue(); + $session->getHandler()->expects('read')->times(2)->returns(serialize([])); + $session->getHandler()->expects('write')->returns(true); $session->start(); $session->markAsReadOnly(); @@ -403,9 +407,9 @@ public function testStartingTheSessionMakesItWritableAgain(): void public function testReadOnlyIsIsolatedBetweenCoroutines(): void { - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('read')->twice()->andReturn(serialize([])); - $handler->expects('write')->once()->andReturnTrue(); + $handler = Double::for(SessionHandlerInterface::class); + $handler->expects('read')->times(2)->returns(serialize([])); + $handler->expects('write')->returns(true); $session = new Store('name', $handler, $this->getSessionId()); [$readOnly, $writable] = parallel([ @@ -635,9 +639,10 @@ public function testHandlerNeedsRequest(): void { $session = $this->getSession(); $this->assertFalse($session->handlerNeedsRequest()); - $session->getHandler()->shouldReceive('setRequest')->never(); + $session->setRequestOnHandler(new Request); + $session->getHandler()->unused(); - $handler = m::mock(CookieSessionHandler::class); + $handler = Double::for(new CookieSessionHandler(new CookieJar, 60, false)); $session = new Store('test', $handler); $this->assertTrue($session->handlerNeedsRequest()); $handler->expects('setRequest'); @@ -711,8 +716,8 @@ public function testPasswordConfirmedResolvesCurrentGuardWhenNoneGiven(): void $container = Container::setInstance(new Container); try { - $auth = m::mock(AuthFactory::class); - $auth->expects('getDefaultDriver')->andReturn('admin'); + $auth = Double::for(AuthFactory::class); + $auth->expects('getDefaultDriver')->returns('admin'); $container->instance(AuthFactory::class, $auth); $session = $this->getSession(); @@ -806,7 +811,7 @@ public function testKeyHasAny(): void public function testHasAnyStopsAfterTheFirstPresentKey(): void { - $session = new class('name', m::mock(SessionHandlerInterface::class), $this->getSessionId()) extends Store { + $session = new class('name', Double::for(SessionHandlerInterface::class), $this->getSessionId()) extends Store { public int $getCalls = 0; public function get(UnitEnum|string $key, mixed $default = null): mixed @@ -1048,7 +1053,7 @@ public function testRememberMethodReturnsPreviousValueIfItAlreadySets(): void public function testValidationErrorsCanBeSerializedAsJson(): void { $session = $this->getSession('json'); - $session->getHandler()->expects('read')->andReturn(json_encode([])); + $session->getHandler()->expects('read')->returns(json_encode([])); $session->start(); $session->put('errors', $this->getErrorBag()); @@ -1072,7 +1077,7 @@ public function testValidationErrorsCanBeSerializedAsJson(): void 'new' => [], ], ]) - )->andReturnTrue(); + )->returns(true); $session->save(); $this->assertFalse($session->isStarted()); @@ -1080,12 +1085,12 @@ public function testValidationErrorsCanBeSerializedAsJson(): void public function testFailedJsonSaveKeepsLiveErrorBagAndFlashUntilRetry(): void { - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('read')->andReturn(json_encode([])); + $handler = Double::for(SessionHandlerInterface::class); + $handler->expects('read')->returns(json_encode([])); $attempts = 0; $payloads = []; - $handler->expects('write')->twice()->andReturnUsing( + $handler->expects('write')->times(2)->resolves( function (string $sessionId, string $data) use (&$attempts, &$payloads): bool { $payloads[] = json_decode($data, true, flags: JSON_THROW_ON_ERROR); @@ -1126,9 +1131,9 @@ function (string $sessionId, string $data) use (&$attempts, &$payloads): bool { public function testConsecutiveJsonSavesKeepTheLiveErrorBag(): void { - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('read')->andReturn(json_encode([])); - $handler->expects('write')->twice()->andReturnTrue(); + $handler = Double::for(SessionHandlerInterface::class); + $handler->expects('read')->returns(json_encode([])); + $handler->expects('write')->times(2)->returns(true); $session = new Store('name', $handler, $this->getSessionId(), 'json'); $session->start(); @@ -1149,9 +1154,9 @@ public function testJsonSessionRoundTripsAtTheMaximumSupportedNestingDepth(): vo } $storedPayload = null; - $writer = m::mock(SessionHandlerInterface::class); - $writer->expects('read')->andReturn('{}'); - $writer->expects('write')->andReturnUsing( + $writer = Double::for(SessionHandlerInterface::class); + $writer->expects('read')->returns('{}'); + $writer->expects('write')->resolves( function (string $sessionId, string $payload) use (&$storedPayload): bool { $storedPayload = $payload; @@ -1164,8 +1169,8 @@ function (string $sessionId, string $payload) use (&$storedPayload): bool { $session->put('nested', $value); $session->save(); - $reader = m::mock(SessionHandlerInterface::class); - $reader->expects('read')->andReturn($storedPayload); + $reader = Double::for(SessionHandlerInterface::class); + $reader->expects('read')->returns($storedPayload); $restored = new Store('name', $reader, $this->getSessionId(), 'json'); $restored->start(); @@ -1181,9 +1186,9 @@ public function testJsonSessionRejectsOneLevelOverTheMaximumNestingDepth(): void $value = ['value' => $value]; } - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('read')->andReturn('{}'); - $handler->shouldReceive('write')->never(); + $handler = Double::for(SessionHandlerInterface::class); + $handler->expects('read')->returns('{}'); + $handler->expects('write')->never(); $session = new Store('name', $handler, $this->getSessionId(), 'json'); $session->start(); @@ -1196,8 +1201,8 @@ public function testJsonSessionRejectsOneLevelOverTheMaximumNestingDepth(): void public function testStartingJsonSessionRetainsLiveErrorBagWhenStorageHasNone(): void { - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('read')->andReturn(json_encode([])); + $handler = Double::for(SessionHandlerInterface::class); + $handler->expects('read')->returns(json_encode([])); $session = new Store('name', $handler, $this->getSessionId(), 'json'); $errorBag = $this->getErrorBag(); @@ -1216,8 +1221,8 @@ public function testStartingJsonSessionRetainsLiveErrorBagWhenStorageHasNone(): public function testPersistedJsonErrorBagOverridesLiveErrorBagOnStart(): void { - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('read')->andReturn(json_encode([ + $handler = Double::for(SessionHandlerInterface::class); + $handler->expects('read')->returns(json_encode([ 'errors' => [ 'persisted' => [ 'format' => ':message', @@ -1247,9 +1252,9 @@ public function testPersistedJsonErrorBagOverridesLiveErrorBagOnStart(): void public function testJsonEncodingFailureLeavesLiveStateUntouched(): void { - $handler = m::mock(SessionHandlerInterface::class); - $handler->expects('read')->andReturn(json_encode([])); - $handler->shouldReceive('write')->never(); + $handler = Double::for(SessionHandlerInterface::class); + $handler->expects('read')->returns(json_encode([])); + $handler->expects('write')->never(); $session = new Store('name', $handler, $this->getSessionId(), 'json'); $session->start(); @@ -1271,7 +1276,7 @@ public function testJsonEncodingFailureLeavesLiveStateUntouched(): void public function testValidationErrorsCanBeReadAsJson(): void { $session = $this->getSession('json'); - $session->getHandler()->expects('read')->with($this->getSessionId())->andReturn(json_encode([ + $session->getHandler()->expects('read')->with($this->getSessionId())->returns(json_encode([ 'errors' => [ 'default' => [ 'format' => '

:message

', @@ -1415,7 +1420,7 @@ public function getSession(string $serialization = 'php'): Store { return new Store( $this->getSessionName(), - m::mock(SessionHandlerInterface::class), + Double::for(SessionHandlerInterface::class), $this->getSessionId(), $serialization ); diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 49b876176..01f199c86 100644 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -31,9 +31,10 @@ use Hypervel\Tests\Support\Fixtures\TestTraversableAndJsonSerializableObject; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; use JsonSerializable; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionClass; use SortDirection; @@ -47,6 +48,8 @@ class SupportCollectionTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('collectionClassProvider')] public function testFirstReturnsFirstItemInCollection($collection): void { @@ -738,10 +741,10 @@ public function testGetArrayableItems($collection): void #[DataProvider('collectionClassProvider')] public function testToArrayCallsToArrayOnEachItemInCollection(string $collection): void { - $item1 = m::mock(Arrayable::class); - $item1->expects('toArray')->andReturn(['foo.array']); - $item2 = m::mock(Arrayable::class); - $item2->expects('toArray')->andReturn(['bar.array']); + $item1 = Double::for(Arrayable::class); + $item1->expects('toArray')->returns(['foo.array']); + $item2 = Double::for(Arrayable::class); + $item2->expects('toArray')->returns(['bar.array']); $c = new $collection([$item1, $item2]); $results = $c->toArray(); @@ -763,10 +766,10 @@ public function testLazyReturnsLazyCollection(): void #[DataProvider('collectionClassProvider')] public function testJsonSerializeCallsToArrayOrJsonSerializeOnEachItemInCollection(string $collection): void { - $item1 = m::mock(JsonSerializable::class); - $item1->expects('jsonSerialize')->andReturn('foo.json'); - $item2 = m::mock(Arrayable::class); - $item2->expects('toArray')->andReturn(['bar.array']); + $item1 = Double::for(JsonSerializable::class); + $item1->expects('jsonSerialize')->returns('foo.json'); + $item2 = Double::for(Arrayable::class); + $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 8a30125f1..134aa22b2 100644 --- a/tests/Support/SupportComposerTest.php +++ b/tests/Support/SupportComposerTest.php @@ -11,7 +11,8 @@ use Hypervel\Support\Env; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Symfony\Component\Process\Process; @@ -21,6 +22,8 @@ class SupportComposerTest extends TestCase { + use VerifiesDoubles; + protected string $tempDir; protected ?string $originalComposerVendorDirectory = null; @@ -255,10 +258,10 @@ private function mockComposer(array $expectedProcessArguments, bool $customCompo { $directory = __DIR__; - $files = m::mock(Filesystem::class); - $files->expects('exists')->with($directory . '/composer.phar')->andReturn($customComposerPhar); + $files = Double::for(Filesystem::class); + $files->expects('exists')->with($directory . '/composer.phar')->returns($customComposerPhar); - $process = m::mock(Process::class); + $process = Double::for(Process::class); $process->expects('run'); $composer = $this->getMockBuilder(Composer::class) diff --git a/tests/Support/SupportFacadeTest.php b/tests/Support/SupportFacadeTest.php index 522b71449..946f7f5f1 100755 --- a/tests/Support/SupportFacadeTest.php +++ b/tests/Support/SupportFacadeTest.php @@ -13,7 +13,6 @@ use Hypervel\Support\Facades\Facade; use Hypervel\Support\Testing\Fakes\Fake; use Hypervel\Tests\TestCase; -use Mockery as m; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\DataProvider; use stdClass; @@ -111,8 +110,7 @@ public function testExpectsCanBeCalledTwice(): void public function testFacadeResolvesAgainAfterClearingSpecific(): void { $app = new ApplicationStub; - $app->setInstances(['foo' => $mock = m::mock(stdClass::class)]); - $mock->expects('bar')->times(3)->andReturn('baz'); + $app->setInstances(['foo' => $service = new FacadeTestService]); // Resolve for the first time FacadeStub::setFacadeApplication($app); @@ -125,13 +123,14 @@ public function testFacadeResolvesAgainAfterClearingSpecific(): void // Clear resolved instance through parent and resolve the third time Facade::clearResolvedInstance('foo'); $this->assertSame('baz', FacadeStub::bar()); + + $this->assertSame(3, $service->calls); } public function testFacadeResolvesAgainAfterClearingAll(): void { $app = new ApplicationStub; - $app->setInstances(['foo' => $mock = m::mock(stdClass::class)]); - $mock->expects('bar')->times(2)->andReturn('baz'); + $app->setInstances(['foo' => $service = new FacadeTestService]); // Resolve for the first time FacadeStub::setFacadeApplication($app); @@ -140,6 +139,8 @@ public function testFacadeResolvesAgainAfterClearingAll(): void // Clear all resolved instances and resolve a second time Facade::clearResolvedInstances(); $this->assertSame('baz', FacadeStub::bar()); + + $this->assertSame(2, $service->calls); } public function testGetFacadeApplicationReturnsSetApplication(): void @@ -179,12 +180,12 @@ public function testSwapWorksWithoutApp(): void { // swap() should not throw when $app is null FacadeStub::setFacadeApplication(null); - $replacement = m::mock(stdClass::class); - $replacement->expects('bar')->andReturn('swapped'); + $replacement = new FacadeTestService; FacadeStub::swap($replacement); - $this->assertSame('swapped', FacadeStub::bar()); + $this->assertSame('baz', FacadeStub::bar()); + $this->assertSame(1, $replacement->calls); } public function testFacadeReturnsNullWhenAppNotSet(): void @@ -499,3 +500,18 @@ public function make(string $abstract, array $parameters = []): mixed return parent::make($abstract, $parameters); } } + +class FacadeTestService +{ + public int $calls = 0; + + /** + * Count the call and return the facade result. + */ + public function bar(): string + { + ++$this->calls; + + return 'baz'; + } +} diff --git a/tests/Support/SupportFacadesEventTest.php b/tests/Support/SupportFacadesEventTest.php index 7db3c353c..5af3bf71c 100644 --- a/tests/Support/SupportFacadesEventTest.php +++ b/tests/Support/SupportFacadesEventTest.php @@ -21,12 +21,15 @@ use Hypervel\Support\Facades\Facade; use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SupportFacadesEventTest extends TestCase { - private Dispatcher&MockInterface $events; + use VerifiesDoubles; + + private Dispatcher&DoubleInterface $events; /** * Set up the event and cache services. @@ -35,8 +38,8 @@ protected function setUp(): void { parent::setUp(); - $this->events = m::mock(Dispatcher::class); - $this->events->shouldReceive('hasListeners')->andReturnTrue(); + $this->events = Double::for(Dispatcher::class); + $this->events->allows('hasListeners')->returns(true); $container = new Container; $container->instance('events', $this->events); diff --git a/tests/Support/SupportFacadesQueueTest.php b/tests/Support/SupportFacadesQueueTest.php index ef7560103..6bf24c35e 100644 --- a/tests/Support/SupportFacadesQueueTest.php +++ b/tests/Support/SupportFacadesQueueTest.php @@ -7,19 +7,22 @@ use Hypervel\Bus\Queueable; use Hypervel\Container\Container; use Hypervel\Contracts\Queue\Factory as QueueContract; -use Hypervel\Queue\QueueManager; +use Hypervel\Contracts\Queue\Queue as QueueInterface; use Hypervel\Queue\Worker; use Hypervel\Support\Facades\Facade; use Hypervel\Support\Facades\Queue; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionProperty; class SupportFacadesQueueTest extends TestCase { - private QueueManager&MockInterface $queueManager; + use VerifiesDoubles; + + private QueueContract&QueueInterface&DoubleInterface $queueManager; /** * Set up the queue manager and facade. @@ -28,7 +31,7 @@ protected function setUp(): void { parent::setUp(); - $this->queueManager = m::mock(QueueManager::class); + $this->queueManager = Double::for(QueueContract::class, QueueInterface::class); $container = new Container; $container->instance('queue', $this->queueManager); @@ -76,6 +79,15 @@ public function testFakeExceptFor(): void $this->assertSame($this->queueManager, Queue::getFacadeRoot()); } + public function testFakeExceptForSwapsQueueManager(): void + { + Queue::fakeExceptFor(function (): void { + $this->assertInstanceOf(QueueFake::class, Queue::getFacadeRoot()); + }, []); + + $this->assertSame($this->queueManager, Queue::getFacadeRoot()); + } + public function testFakeExceptForReturnValue(): void { $result = Queue::fakeExceptFor(function (): string { diff --git a/tests/Support/SupportLazyCollectionIsLazyTest.php b/tests/Support/SupportLazyCollectionIsLazyTest.php index 9af798638..f6e045738 100644 --- a/tests/Support/SupportLazyCollectionIsLazyTest.php +++ b/tests/Support/SupportLazyCollectionIsLazyTest.php @@ -11,7 +11,6 @@ use Hypervel\Support\MultipleItemsFoundException; use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; -use Mockery as m; use stdClass; class SupportLazyCollectionIsLazyTest extends TestCase @@ -1325,65 +1324,26 @@ public function testTakeUntilIsLazy(): void public function testTakeUntilTimeoutIsLazy(): void { - tap(m::mock(LazyCollection::class . '[now]')->times(100), function ($mock) { - $this->assertDoesNotEnumerateCollection($mock, function ($mock) { - $timeout = CarbonImmutable::now(); - - $results = $mock - ->tap(function ($collection) use ($mock, $timeout) { - tap($collection) - ->mockery_init($mock->mockery_getContainer()) - ->shouldAllowMockingProtectedMethods() - ->expects('now') - ->times(1) - ->andReturn( - $timeout->getTimestamp() - ); - }) - ->takeUntilTimeout($timeout) - ->all(); - }); + $timeout = CarbonImmutable::now(); + + CarbonImmutable::setTestNow($timeout); + + $this->assertDoesNotEnumerateCollection(LazyCollection::times(100), function ($collection) use ($timeout) { + $collection->takeUntilTimeout($timeout)->all(); }); - tap(m::mock(LazyCollection::class . '[now]')->times(100), function ($mock) { - $this->assertEnumeratesCollection($mock, 1, function ($mock) { - $timeout = CarbonImmutable::now(); - - $results = $mock - ->tap(function ($collection) use ($mock, $timeout) { - tap($collection) - ->mockery_init($mock->mockery_getContainer()) - ->shouldAllowMockingProtectedMethods() - ->expects('now') - ->times(2) - ->andReturn( - $timeout->sub(1, 'minute')->getTimestamp(), - $timeout->getTimestamp() - ); - }) - ->takeUntilTimeout($timeout) - ->all(); - }); + CarbonImmutable::setTestNow($timeout->sub(1, 'minute')); + + $source = LazyCollection::times(100)->tapEach(fn () => CarbonImmutable::setTestNow($timeout)); + + $this->assertEnumeratesCollection($source, 1, function ($collection) use ($timeout) { + $collection->takeUntilTimeout($timeout)->all(); }); - tap(m::mock(LazyCollection::class . '[now]')->times(100), function ($mock) { - $this->assertEnumeratesCollectionOnce($mock, function ($mock) { - $timeout = CarbonImmutable::now(); - - $results = $mock - ->tap(function ($collection) use ($mock, $timeout) { - tap($collection) - ->mockery_init($mock->mockery_getContainer()) - ->shouldAllowMockingProtectedMethods() - ->expects('now') - ->times(100) - ->andReturn( - $timeout->sub(1, 'minute')->getTimestamp() - ); - }) - ->takeUntilTimeout($timeout) - ->all(); - }); + CarbonImmutable::setTestNow($timeout->sub(1, 'minute')); + + $this->assertEnumeratesCollectionOnce(LazyCollection::times(100), function ($collection) use ($timeout) { + $collection->takeUntilTimeout($timeout)->all(); }); } diff --git a/tests/Support/SupportLazyCollectionTest.php b/tests/Support/SupportLazyCollectionTest.php index 5969530e7..6d0813384 100644 --- a/tests/Support/SupportLazyCollectionTest.php +++ b/tests/Support/SupportLazyCollectionTest.php @@ -14,7 +14,6 @@ use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; class SupportLazyCollectionTest extends TestCase { @@ -228,24 +227,13 @@ public function testTakeUntilTimeout(): void { $timeout = CarbonImmutable::now(); - $mock = m::mock(LazyCollection::class . '[now]'); - $timedOutWith = []; - $results = $mock - ->times(10) - ->tap(function ($collection) use ($mock, $timeout) { - tap($collection) - ->mockery_init($mock->mockery_getContainer()) - ->shouldAllowMockingProtectedMethods() - ->expects('now') - ->times(3) - ->andReturn( - $timeout->sub(2, 'minute')->getTimestamp(), - $timeout->sub(1, 'minute')->getTimestamp(), - $timeout->getTimestamp() - ); - }) + CarbonImmutable::setTestNow($timeout->sub(2, 'minute')); + + // The clock moves forward one minute for each item, reaching the timeout on the second. + $results = LazyCollection::times(10) + ->tapEach(fn ($number) => CarbonImmutable::setTestNow($timeout->sub(2 - $number, 'minute'))) ->takeUntilTimeout($timeout, function ($value, $key) use (&$timedOutWith) { $timedOutWith = [$value, $key]; }) diff --git a/tests/Support/SupportServiceProviderTest.php b/tests/Support/SupportServiceProviderTest.php index 1f9648620..721f80a24 100644 --- a/tests/Support/SupportServiceProviderTest.php +++ b/tests/Support/SupportServiceProviderTest.php @@ -13,11 +13,14 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use Hypervel\Translation\Translator; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use WeakReference; class SupportServiceProviderTest extends TestCase { + use VerifiesDoubles; + protected Application $app; protected ConfigMutationTracker $configMutationTracker; @@ -26,21 +29,19 @@ protected function setUp(): void { parent::setUp(); - $this->app = $app = m::mock(Application::class)->makePartial(); + $this->app = $app = new Application; + $app->instance('config_loaded_from_cache', false); $config = new ConfigRepository([ 'database' => ['migrations' => [ 'update_date_on_publish' => true, ]], ]); - $app->shouldReceive('make')->with('config')->andReturn($config)->byDefault(); + $app->instance('config', $config); $this->configMutationTracker = new ConfigMutationTracker; $this->configMutationTracker->observe($config); - $app->shouldReceive('make') - ->with(ConfigMutationTracker::class) - ->andReturn($this->configMutationTracker) - ->byDefault(); + $app->instance(ConfigMutationTracker::class, $this->configMutationTracker); $one = new ServiceProviderForTestingOne($app); $one->boot(); @@ -65,8 +66,8 @@ public function testIsEnabledCanBeOverriddenToReturnFalse(): void public function testIsEnabledCanReadFromContainerAndConfig(): void { $config = new ConfigRepository(['package' => ['enabled' => true]]); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('make')->with('config')->andReturn($config); + $app = new Application; + $app->instance('config', $config); $provider = new ServiceProviderForTestingConditionallyEnabled($app); $this->assertTrue($provider->isEnabled()); @@ -205,7 +206,7 @@ public function testPublishesMigrationsDoesNotUpdateDatesWhenSettingIsOmitted(): $config = new ConfigRepository([ 'database' => ['migrations' => []], ]); - $this->app->shouldReceive('make')->with('config')->andReturn($config); + $this->app->instance('config', $config); $serviceProvider = new ServiceProviderForTestingOne($this->app); (fn () => $this->publishesMigrations(['source' => 'destination'])) @@ -247,7 +248,7 @@ public function testEmptyArrayIsReturnedWhenGroupNotFound(): void public function testMergeConfigFromWithFlatConfig(): void { $config = new ConfigRepository; - $this->app->shouldReceive('make')->with('config')->andReturn($config); + $this->app->instance('config', $config); $provider = new ServiceProviderForTestingFlat($this->app); $provider->register(); @@ -261,7 +262,7 @@ public function testMergeConfigFromAppOverridesPackageDefaults(): void $config = new ConfigRepository([ 'flat' => ['default' => 'redis'], ]); - $this->app->shouldReceive('make')->with('config')->andReturn($config); + $this->app->instance('config', $config); $provider = new ServiceProviderForTestingFlat($this->app); $provider->register(); @@ -281,7 +282,7 @@ public function testMergeConfigFromWithoutMergeableOptionsReplacesNestedArrays() ], ], ]); - $this->app->shouldReceive('make')->with('config')->andReturn($config); + $this->app->instance('config', $config); $provider = new ServiceProviderForTestingFlatWithStores($this->app); $provider->register(); @@ -309,7 +310,7 @@ public function testMergeConfigFromWithMergeableOptionsCombinesNestedArrays(): v ], ], ]); - $this->app->shouldReceive('make')->with('config')->andReturn($config); + $this->app->instance('config', $config); $provider = new ServiceProviderForTestingMergeableStores($this->app); $provider->register(); @@ -344,7 +345,7 @@ public function testMergeConfigFromWithMergeableOptionsWhenAppHasNoStores(): voi 'default' => 'redis', ], ]); - $this->app->shouldReceive('make')->with('config')->andReturn($config); + $this->app->instance('config', $config); $provider = new ServiceProviderForTestingMergeableStores($this->app); $provider->register(); @@ -360,7 +361,7 @@ public function testMergeConfigFromWithMergeableOptionsWhenAppHasNoStores(): voi public function testMergeConfigFromWithMergeableOptionsWhenNoExistingConfig(): void { $config = new ConfigRepository; - $this->app->shouldReceive('make')->with('config')->andReturn($config); + $this->app->instance('config', $config); $provider = new ServiceProviderForTestingMergeableStores($this->app); $provider->register(); @@ -381,10 +382,10 @@ public function testMergeConfigFromReplaysAgainstFreshApplicationConfig(): void ]); $tracker = new ConfigMutationTracker; $tracker->observe($masterConfig); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturn(false); - $app->shouldReceive('make')->with('config')->andReturn($masterConfig); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn($tracker); + $app = new Application; + $app->instance('config_loaded_from_cache', false); + $app->instance('config', $masterConfig); + $app->instance(ConfigMutationTracker::class, $tracker); (new ServiceProviderForTestingFlat($app))->register(); @@ -402,10 +403,10 @@ public function testMergeableOptionsReplayWithoutRetainingTheProvider(): void $masterConfig = new ConfigRepository; $tracker = new ConfigMutationTracker; $tracker->observe($masterConfig); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturn(false); - $app->shouldReceive('make')->with('config')->andReturn($masterConfig); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn($tracker); + $app = new Application; + $app->instance('config_loaded_from_cache', false); + $app->instance('config', $masterConfig); + $app->instance(ConfigMutationTracker::class, $tracker); $provider = new ServiceProviderForTestingMergeableStores($app); $providerReference = WeakReference::create($provider); @@ -434,10 +435,10 @@ public function testReplaceConfigRecursivelyFromReplaysAgainstFreshApplicationCo ]); $tracker = new ConfigMutationTracker; $tracker->observe($masterConfig); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturn(false); - $app->shouldReceive('make')->with('config')->andReturn($masterConfig); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn($tracker); + $app = new Application; + $app->instance('config_loaded_from_cache', false); + $app->instance('config', $masterConfig); + $app->instance(ConfigMutationTracker::class, $tracker); (new ServiceProviderForTestingReplace($app))->register(); @@ -462,25 +463,22 @@ public function testMergeableOptionsDefaultsToEmptyArray(): void public function testMergeConfigFromSkipsWhenConfigIsCached(): void { - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturn(true); - $app->shouldReceive('make')->with('config')->never(); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->never(); + $app = Double::for(Application::class, override: true); + $app->allows('configurationIsCached')->returns(true); + $app->expects('make')->with('config')->never(); + $app->expects('make')->with(ConfigMutationTracker::class)->never(); - $provider = new ServiceProviderForTestingFlat($app); + $provider = new ServiceProviderForTestingFlat($app->instance()); $provider->register(); - - // Config should not have been touched — merge was skipped - $this->assertNull((new ConfigRepository)->get('flat')); } public function testMergeConfigFromRunsWhenConfigIsNotCached(): void { $config = new ConfigRepository; - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturn(false); - $app->shouldReceive('make')->with('config')->andReturn($config); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn(new ConfigMutationTracker); + $app = new Application; + $app->instance('config_loaded_from_cache', false); + $app->instance('config', $config); + $app->instance(ConfigMutationTracker::class, new ConfigMutationTracker); $provider = new ServiceProviderForTestingFlat($app); $provider->register(); @@ -490,15 +488,13 @@ public function testMergeConfigFromRunsWhenConfigIsNotCached(): void public function testReplaceConfigRecursivelyFromSkipsWhenCached(): void { - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturn(true); - $app->shouldReceive('make')->with('config')->never(); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->never(); + $app = Double::for(Application::class, override: true); + $app->allows('configurationIsCached')->returns(true); + $app->expects('make')->with('config')->never(); + $app->expects('make')->with(ConfigMutationTracker::class)->never(); - $provider = new ServiceProviderForTestingReplace($app); + $provider = new ServiceProviderForTestingReplace($app->instance()); $provider->register(); - - $this->assertNull((new ConfigRepository)->get('flat')); } public function testReplaceConfigRecursivelyFromRunsWhenNotCached(): void @@ -506,10 +502,10 @@ public function testReplaceConfigRecursivelyFromRunsWhenNotCached(): void $config = new ConfigRepository([ 'flat' => ['default' => 'redis', 'extra' => 'app-value'], ]); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturn(false); - $app->shouldReceive('make')->with('config')->andReturn($config); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn(new ConfigMutationTracker); + $app = new Application; + $app->instance('config_loaded_from_cache', false); + $app->instance('config', $config); + $app->instance(ConfigMutationTracker::class, new ConfigMutationTracker); $provider = new ServiceProviderForTestingReplace($app); $provider->register(); @@ -526,10 +522,10 @@ public function testConfigureUsingComputesAgainAgainstTheRebuiltConfiguration(): $masterConfig = new ConfigRepository(['computed' => ['record' => 10]]); $tracker = new ConfigMutationTracker; $tracker->observe($masterConfig); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturn(false); - $app->shouldReceive('make')->with('config')->andReturn($masterConfig); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn($tracker); + $app = new Application; + $app->instance('config_loaded_from_cache', false); + $app->instance('config', $masterConfig); + $app->instance(ConfigMutationTracker::class, $tracker); (new ServiceProviderForTestingComputed($app))->register(); @@ -544,27 +540,21 @@ public function testConfigureUsingComputesAgainAgainstTheRebuiltConfiguration(): public function testConfigureUsingSkipsWhenConfigIsCached(): void { - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturn(true); - $app->shouldReceive('make')->with('config')->never(); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->never(); + $app = Double::for(Application::class, override: true); + $app->allows('configurationIsCached')->returns(true); + $app->expects('make')->with('config')->never(); + $app->expects('make')->with(ConfigMutationTracker::class)->never(); // Cached configuration already holds the computed value, so neither the configuration nor the tracker is touched. - (new ServiceProviderForTestingComputed($app))->register(); - - $this->addToAssertionCount(1); + (new ServiceProviderForTestingComputed($app->instance()))->register(); } public function testLoadTranslationsFromWithoutNamespace(): void { - $translator = m::mock(Translator::class); + $translator = Double::for(Translator::class); $translator->expects('addPath')->with(__DIR__ . '/translations'); - $this->app->expects('afterResolving')->with('translator', m::on(function (callable $callback) use ($translator): bool { - $callback($translator); - - return true; - })); + $this->app->instance('translator', $translator); $provider = new ServiceProviderForTestingOne($this->app); $provider->loadTranslationsFrom(__DIR__ . '/translations'); @@ -572,14 +562,10 @@ public function testLoadTranslationsFromWithoutNamespace(): void public function testLoadTranslationsFromWithNamespace(): void { - $translator = m::mock(Translator::class); + $translator = Double::for(Translator::class); $translator->expects('addNamespace')->with('namespace', __DIR__ . '/translations'); - $this->app->expects('afterResolving')->with('translator', m::on(function (callable $callback) use ($translator): bool { - $callback($translator); - - return true; - })); + $this->app->instance('translator', $translator); $provider = new ServiceProviderForTestingOne($this->app); $provider->loadTranslationsFrom(__DIR__ . '/translations', 'namespace'); diff --git a/tests/Support/SupportTestingBusFakeTest.php b/tests/Support/SupportTestingBusFakeTest.php index 2b767533f..b1d0fbc8e 100644 --- a/tests/Support/SupportTestingBusFakeTest.php +++ b/tests/Support/SupportTestingBusFakeTest.php @@ -21,7 +21,8 @@ use Hypervel\Support\Testing\Fakes\BusFake; use Hypervel\Support\Testing\Fakes\PendingBatchFake; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\ExpectationFailedException; @@ -29,19 +30,21 @@ class SupportTestingBusFakeTest extends TestCase { + use VerifiesDoubles; + protected BusFake $fake; protected function setUp(): void { parent::setUp(); - $this->fake = new BusFake(m::mock(QueueingDispatcher::class)); + $this->fake = new BusFake(new BusDispatcher(new Container)); } public function testItUsesCustomBusRepository(): void { $busRepository = new BatchRepositoryFake; - $fake = new BusFake(m::mock(QueueingDispatcher::class), [], $busRepository); + $fake = new BusFake(new BusDispatcher(new Container), [], $busRepository); $this->assertNull($fake->findBatch('non-existent-batch')); @@ -162,7 +165,7 @@ public static function fakeReturnMethods(): array public function testFakeDispatchMethodsAcceptDispatchLockOwnership(string $dispatchMethod): void { $command = new BusJobStub; - DispatchLockContext::registerUnique($command, m::mock(Cache::class), null, 'key', 'owner'); + DispatchLockContext::registerUnique($command, Double::for(Cache::class), null, 'key', 'owner'); $this->assertTrue(DispatchLockContext::has($command)); @@ -720,9 +723,9 @@ public function testFakeChainKeepsTheFirstJobsOwnSettings(): void public function testDispatchingAfterResponsesCanBeToggledOnTheFake(): void { - $dispatcher = m::mock(BusDispatcher::class); - $dispatcher->expects('withoutDispatchingAfterResponses')->andReturnSelf(); - $dispatcher->expects('withDispatchingAfterResponses')->andReturnSelf(); + $dispatcher = Double::for(BusDispatcher::class); + $dispatcher->expects('withoutDispatchingAfterResponses')->returns($dispatcher); + $dispatcher->expects('withDispatchingAfterResponses')->returns($dispatcher); $fake = new BusFake($dispatcher); @@ -732,15 +735,15 @@ public function testDispatchingAfterResponsesCanBeToggledOnTheFake(): void public function testAssertDispatchedWithIgnoreClass(): void { - $dispatcher = m::mock(QueueingDispatcher::class); + $dispatcher = Double::for(QueueingDispatcher::class); $job = new BusJobStub; $dispatcher->expects('dispatch')->with($job); $dispatcher->expects('dispatchNow')->with($job, null); $otherJob = new OtherBusJobStub; - $dispatcher->shouldReceive('dispatch')->never()->with($otherJob); - $dispatcher->shouldReceive('dispatchNow')->never()->with($otherJob, null); + $dispatcher->expects('dispatch')->never()->with($otherJob); + $dispatcher->expects('dispatchNow')->never()->with($otherJob, null); $fake = new BusFake($dispatcher, OtherBusJobStub::class); @@ -756,19 +759,19 @@ public function testAssertDispatchedWithIgnoreClass(): void public function testDispatchedFakingOnlyGivenJobs(): void { - $dispatcher = m::mock(QueueingDispatcher::class); + $dispatcher = Double::for(QueueingDispatcher::class); $job = new BusJobStub; - $dispatcher->shouldReceive('dispatch')->never()->with($job); - $dispatcher->shouldReceive('dispatchNow')->never()->with($job, null); + $dispatcher->expects('dispatch')->never()->with($job); + $dispatcher->expects('dispatchNow')->never()->with($job, null); $otherJob = new OtherBusJobStub; $dispatcher->expects('dispatch')->with($otherJob); $dispatcher->expects('dispatchNow')->with($otherJob, null); $thirdJob = new ThirdJob; - $dispatcher->shouldReceive('dispatch')->never()->with($thirdJob); - $dispatcher->shouldReceive('dispatchNow')->never()->with($thirdJob, null); + $dispatcher->expects('dispatch')->never()->with($thirdJob); + $dispatcher->expects('dispatchNow')->never()->with($thirdJob, null); $fake = (new BusFake($dispatcher))->except(OtherBusJobStub::class); @@ -795,19 +798,20 @@ public function testBulkRecordsEachJob(): void public function testAssertDispatchedWithIgnoreCallback(): void { - $dispatcher = m::mock(QueueingDispatcher::class); + $dispatcher = Double::for(QueueingDispatcher::class); $job = new BusJobStub; - $dispatcher->expects('dispatch')->with($job); - $dispatcher->expects('dispatchNow')->with($job, null); - $otherJob = new OtherBusJobStub; - $dispatcher->expects('dispatch')->with($otherJob); - $dispatcher->expects('dispatchNow')->with($otherJob, null); - $anotherJob = new OtherBusJobStub(1); - $dispatcher->shouldReceive('dispatch')->never()->with($anotherJob); - $dispatcher->shouldReceive('dispatchNow')->never()->with($anotherJob, null); + + $dispatched = []; + $dispatcher->expects('dispatch')->times(2)->resolves(function ($command) use (&$dispatched): void { + $dispatched[] = $command; + }); + $dispatcher->expects('dispatchNow')->times(2)->resolves(function ($command, $handler) use (&$dispatched): void { + $this->assertNull($handler); + $dispatched[] = $command; + }); $fake = new BusFake($dispatcher, [ function ($command) { @@ -832,6 +836,8 @@ function ($command) { $fake->assertDispatched(OtherBusJobStub::class, function ($job) { return $job->id === 1; }); + + $this->assertSame([$job, $job, $otherJob, $otherJob], $dispatched); } public function testAssertNothingBatched(): void @@ -924,7 +930,7 @@ public function testFinishedBatchesHaveImmutableFinishedAtTimestamp(): void { $batchRepository = new BatchRepositoryFake; - $fake = new BusFake(m::mock(QueueingDispatcher::class), [], $batchRepository); + $fake = new BusFake(new BusDispatcher(new Container), [], $batchRepository); $batch = $fake->batch([])->dispatch(); @@ -1014,7 +1020,7 @@ public static function serializeAndRestoreCommandMethodsDataProvider(): array public function testSerializedCommandAcceptanceUsesOriginalIdentity(): void { $command = new BusFakeJobWithSerialization('hello'); - DispatchLockContext::registerUnique($command, m::mock(Cache::class), null, 'key', 'owner'); + DispatchLockContext::registerUnique($command, Double::for(Cache::class), null, 'key', 'owner'); $serializingBusFake = (clone $this->fake)->serializeAndRestore(); $serializingBusFake->dispatch($command); @@ -1029,7 +1035,7 @@ public function testSerializationFailureRetainsDispatchLockOwnership(): void { $exception = new RuntimeException('Serialization failed.'); $command = new BusFakeJobWithFailingSerialization($exception); - DispatchLockContext::registerUnique($command, m::mock(Cache::class), null, 'key', 'owner'); + DispatchLockContext::registerUnique($command, Double::for(Cache::class), null, 'key', 'owner'); $serializingBusFake = (clone $this->fake)->serializeAndRestore(); try { diff --git a/tests/Support/SupportTestingMailFakeTest.php b/tests/Support/SupportTestingMailFakeTest.php index 00827118d..fceed4b2a 100644 --- a/tests/Support/SupportTestingMailFakeTest.php +++ b/tests/Support/SupportTestingMailFakeTest.php @@ -5,22 +5,28 @@ namespace Hypervel\Tests\Support; use Hypervel\Bus\Queueable; +use Hypervel\Config\Repository; use Hypervel\Contracts\Queue\ShouldQueue; use Hypervel\Contracts\Translation\HasLocalePreference; +use Hypervel\Foundation\Application; use Hypervel\Mail\Mailable; use Hypervel\Mail\MailManager; use Hypervel\Support\Testing\Fakes\MailFake; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; -use Mockery\MockInterface; use PHPUnit\Framework\ExpectationFailedException; use UnitEnum; class SupportTestingMailFakeTest extends TestCase { - private MailManager&MockInterface $mailManager; + use VerifiesDoubles; + + private MailManager $mailManager; + + private Application $app; private MailFake $fake; @@ -32,11 +38,10 @@ class SupportTestingMailFakeTest extends TestCase protected function setUp(): void { parent::setUp(); - $this->mailManager = m::mock(MailManager::class, function (MailManager $mock): void { - $mock->shouldReceive('getDefaultDriver') - ->byDefault() - ->andReturn('smtp'); - }); + $this->app = new Application; + // No transport is configured, so forwarding a fake send or queue operation fails. + $this->app->instance('config', new Repository(['mail' => ['default' => 'smtp']])); + $this->mailManager = new MailManager($this->app); $this->fake = new MailFake($this->mailManager); $this->mailable = new MailableStub; } @@ -388,10 +393,6 @@ public function testAssertNothingQueued(): void public function testRawHtmlAndPlainMessagesAreNotSent(): void { - $this->mailManager->shouldNotReceive('raw'); - $this->mailManager->shouldNotReceive('html'); - $this->mailManager->shouldNotReceive('plain'); - $callback = fn ($message) => $message->to('taylor@hypervel.com'); $this->fake->raw('Hello', $callback); @@ -455,9 +456,7 @@ public function testAssertSentWithClosure(): void public function testMissingMethodsAreForwarded(): void { - $this->mailManager->expects('foo')->andReturn('bar'); - - $this->assertSame('bar', $this->fake->foo()); + $this->assertSame($this->app, $this->fake->getApplication()); } public function testAssertMailer(): void @@ -513,9 +512,6 @@ public function testDriverMethod(): void public function testQueueSetsQueueOnMailable(): void { - $this->mailManager->shouldNotReceive('onQueue'); - $this->mailManager->shouldNotReceive('queueOn'); - $mailable1 = new QueueableMailableStub; $this->fake->mailer('ses')->queue($mailable1, 'podcasts'); @@ -549,8 +545,6 @@ public function testQueueSetsQueueOnMailable(): void public function testLaterSetsQueueOnMailable(): void { - $this->mailManager->shouldNotReceive('laterOn'); - $mailable1 = new QueueableMailableStub; $this->fake->later(15, $mailable1, 'podcasts'); @@ -584,8 +578,8 @@ public function testSendNowSendsQueueableMailableSynchronouslyWithPendingRecipie public function testDefaultMailerIsResolvedWhenEachOperationOccurs(): void { - $manager = m::mock(MailManager::class); - $manager->expects('getDefaultDriver')->twice()->andReturn('smtp', 'ses'); + $manager = Double::for(MailManager::class); + $manager->expects('getDefaultDriver')->times(2)->returns('smtp', 'ses'); $fake = new MailFake($manager); $first = new MailableStub; @@ -670,10 +664,6 @@ public function testFailedQueueSelectionConsumesExplicitMailer(): void public function testQueueHelpersAcceptEnumsWithoutCallingTheRealManager(): void { - $this->mailManager->shouldNotReceive('onQueue'); - $this->mailManager->shouldNotReceive('queueOn'); - $this->mailManager->shouldNotReceive('laterOn'); - $onQueueEnum = new QueueableMailableStub; $queueOnEnum = new QueueableMailableStub; $laterOnEnum = new QueueableMailableStub; @@ -705,8 +695,8 @@ public function testNamedPendingRecipientsMatchTheRealMailer(): void public function testShouldQueueSendResolvesTheDefaultMailerOnce(): void { - $manager = m::mock(MailManager::class); - $manager->expects('getDefaultDriver')->andReturn('smtp'); + $manager = Double::for(MailManager::class); + $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 fe5973534..a90405f46 100644 --- a/tests/Support/SupportTestingQueueFakeTest.php +++ b/tests/Support/SupportTestingQueueFakeTest.php @@ -23,19 +23,25 @@ use Hypervel\Queue\Attributes\Delay; use Hypervel\Queue\CallQueuedClosure; use Hypervel\Queue\Jobs\InspectedJob; +use Hypervel\Queue\NullQueue; use Hypervel\Queue\QueueManager; use Hypervel\Queue\QueueRoutes; use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Testing\Fakes\QueueFake; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\ExpectationFailedException; use RuntimeException; use stdClass; +use UnitEnum; class SupportTestingQueueFakeTest extends TestCase { + use VerifiesDoubles; + private QueueFake $fake; private JobStub $job; @@ -79,18 +85,17 @@ public function testAssertPushedWithIgnore(): void { $job = new JobStub; - $queue = m::mock(Queue::class); - $queue->expects('push')->withArgs(function ($passedJob) use ($job) { - return $passedJob === $job; - }); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->with(null)->andReturn($queue); + $queue = new QueueFakeTestRecordingQueue; + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with(null)->returns($queue); $fake = new QueueFake(new Application, JobToFakeStub::class, $manager); $fake->push($job); $fake->push(new JobToFakeStub); + $this->assertSame([[$job, '', null]], $queue->pushed); + $fake->assertNotPushed(JobStub::class); $fake->assertPushed(JobToFakeStub::class); } @@ -504,18 +509,17 @@ public function testItDoesntFakeJobsPassedViaExcept(): void { $job = new JobStub; - $queue = m::mock(Queue::class); - $queue->expects('push')->withArgs(function ($passedJob) use ($job) { - return $passedJob === $job; - }); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->with(null)->andReturn($queue); + $queue = new QueueFakeTestRecordingQueue; + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with(null)->returns($queue); $fake = (new QueueFake(new Application, [], $manager))->except(JobStub::class); $fake->push($job); $fake->push(new JobToFakeStub); + $this->assertSame([[$job, '', null]], $queue->pushed); + $fake->assertNotPushed(JobStub::class); $fake->assertPushed(JobToFakeStub::class); } @@ -612,12 +616,9 @@ public function testItCanInvokeCallbacksBeforeAndAfterPushingDispatchedJobs(): v $job = new JobStub; $steps = []; - $queue = m::mock(Queue::class); - $queue->expects('push')->withArgs(function ($passedJob, $passedData, $passedQueue) use ($job) { - return $passedJob === $job && $passedData === ['foo' => 'bar'] && $passedQueue === 'redis'; - }); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->with(null)->andReturn($queue); + $queue = new QueueFakeTestRecordingQueue; + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with(null)->returns($queue); $fake = (new QueueFake(new Application, [], $manager)) ->except(JobStub::class) @@ -636,6 +637,8 @@ public function testItCanInvokeCallbacksBeforeAndAfterPushingDispatchedJobs(): v $fake->push($job, ['foo' => 'bar'], 'redis'); + $this->assertSame([[$job, ['foo' => 'bar'], 'redis']], $queue->pushed); + $this->assertSame([ ['before', JobStub::class, ['foo' => 'bar'], 'redis'], ['before again', JobStub::class, ['foo' => 'bar'], 'redis'], @@ -1024,13 +1027,12 @@ public function testPushedRaw(): void public function testPartialFakePreservesDelayOnTheDefaultConnection(): void { $job = new JobStub; - $queue = m::mock(Queue::class); - $queue->shouldReceive('later') - ->once() + $queue = Double::for(Queue::class); + $queue->expects('later') ->with(10, $job, ['key' => 'value'], 'emails') - ->andReturn('job-id'); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->once()->with(null)->andReturn($queue); + ->returns('job-id'); + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with(null)->returns($queue); $fake = (new QueueFake(new Application, [], $manager))->except(JobStub::class); @@ -1041,13 +1043,12 @@ public function testPartialFakePreservesDelayOnTheDefaultConnection(): void public function testPartialFakeUsesTheJobConnectionAndLaterOnPreservesDelay(): void { $job = new JobWithConnectionStub; - $queue = m::mock(Queue::class); - $queue->shouldReceive('later') - ->once() + $queue = Double::for(Queue::class); + $queue->expects('later') ->with(15, $job, '', 'emails') - ->andReturn('job-id'); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->once()->with('redis')->andReturn($queue); + ->returns('job-id'); + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with('redis')->returns($queue); $fake = (new QueueFake(new Application, [], $manager))->except(JobWithConnectionStub::class); @@ -1058,10 +1059,10 @@ public function testPartialFakeUsesTheJobConnectionAndLaterOnPreservesDelay(): v public function testPartialFakeUsesTheJobConnectionAttribute(): void { $job = new JobWithConnectionAttributeStub; - $queue = m::mock(Queue::class); - $queue->expects('push')->with($job, '', null)->andReturn('job-id'); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->with('attribute-connection')->andReturn($queue); + $queue = Double::for(Queue::class); + $queue->expects('push')->with($job, '', null)->returns('job-id'); + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with('attribute-connection')->returns($queue); $fake = (new QueueFake(new Application, [], $manager))->except(JobWithConnectionAttributeStub::class); @@ -1075,10 +1076,10 @@ public function testPartialFakeUsesTheJobConnectionAttribute(): void public function testSelectedConnectionWinsOverTheJobConnection(QueueNameEnumStub|string $selected, string $expected): void { $job = new JobWithConnectionStub; - $queue = m::mock(Queue::class); - $queue->expects('push')->with($job, '', 'emails')->andReturn('job-id'); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->with($expected)->andReturn($queue); + $queue = Double::for(Queue::class); + $queue->expects('push')->with($job, '', 'emails')->returns('job-id'); + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with($expected)->returns($queue); $fake = (new QueueFake(new Application, [], $manager))->except(JobWithConnectionStub::class); @@ -1093,10 +1094,10 @@ public function testPartialFakeSendsBusJobsToTheirRoutedConnection(): void $app->instance('queue.routes', $routes); $job = new QueuedJobStub; - $queue = m::mock(Queue::class); - $queue->expects('push')->with($job, '', null)->andReturn('job-id'); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->with('routed-connection')->andReturn($queue); + $queue = Double::for(Queue::class); + $queue->expects('push')->with($job, '', null)->returns('job-id'); + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with('routed-connection')->returns($queue); $fake = (new QueueFake($app, [], $manager))->except(QueuedJobStub::class); $bus = new BusDispatcher($app, fn (?string $connection = null) => $fake->connection($connection)); @@ -1106,10 +1107,10 @@ public function testPartialFakeSendsBusJobsToTheirRoutedConnection(): void public function testPartialFakeSendsQueuedListenersToTheirSelectedConnection(): void { - $queue = m::mock(Queue::class); - $queue->expects('push')->with(m::type(CallQueuedListener::class), '', null)->andReturn('job-id'); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->with('listener-connection')->andReturn($queue); + $queue = Double::for(Queue::class); + $queue->expects('push')->with(Argument::type(CallQueuedListener::class), '', null)->returns('job-id'); + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with('listener-connection')->returns($queue); $fake = (new QueueFake(new Application, [], $manager))->except(CallQueuedListener::class); $events = new EventsDispatcher; @@ -1123,11 +1124,11 @@ public function testPartialFakeSendsQueuedListenersToTheirSelectedConnection(): public function testSelectedConnectionsShareTheFakesHistory(): void { - $queue = m::mock(Queue::class); - $queue->expects('push')->twice()->andReturn('job-id'); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->with('redis')->andReturn($queue); - $manager->expects('connection')->with('sqs')->andReturn($queue); + $queue = Double::for(Queue::class); + $queue->expects('push')->times(2)->returns('job-id'); + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with('redis')->returns($queue); + $manager->expects('connection')->with('sqs')->returns($queue); $fake = (new QueueFake(new Application, [], $manager))->except(JobStub::class); $redis = $fake->connection('redis'); @@ -1147,11 +1148,11 @@ public function testSelectedConnectionKeepsItsConnectionForBulkJobs(): void { $plainJob = new JobWithRuntimeDelayStub; $delayedJob = (new JobWithRuntimeDelayStub)->delay(10); - $queue = m::mock(Queue::class); - $queue->expects('push')->with($plainJob, '', 'emails')->andReturn('plain-id'); - $queue->expects('later')->with(10, $delayedJob, '', 'emails')->andReturn('delayed-id'); - $manager = m::mock(QueueManager::class); - $manager->expects('connection')->twice()->with('redis')->andReturn($queue); + $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); + $manager->expects('connection')->times(2)->with('redis')->returns($queue); $fake = (new QueueFake(new Application, [], $manager))->except(JobWithRuntimeDelayStub::class); @@ -1194,10 +1195,10 @@ public function testBeforeCallbackFailurePreventsPublicationAndAfterCallbacks(): public function testPassThroughFailureDoesNotRunAfterCallbacks(): void { $job = new JobStub; - $queue = m::mock(Queue::class); - $queue->shouldReceive('push')->once()->andThrow(new RuntimeException('push failed')); - $manager = m::mock(QueueManager::class); - $manager->shouldReceive('connection')->once()->with(null)->andReturn($queue); + $queue = Double::for(Queue::class); + $queue->expects('push')->throws(new RuntimeException('push failed')); + $manager = Double::for(QueueManager::class); + $manager->expects('connection')->with(null)->returns($queue); $afterCalled = false; $fake = (new QueueFake(new Application, [], $manager)) @@ -1386,3 +1387,18 @@ class QueueFakeUniqueJobStub implements ShouldBeUnique { use Queueable; } + +class QueueFakeTestRecordingQueue extends NullQueue +{ + public array $pushed = []; + + /** + * Record the job and its payload and queue. + */ + public function push(object|string $job, mixed $data = '', UnitEnum|string|null $queue = null): mixed + { + $this->pushed[] = [$job, $data, $queue]; + + return null; + } +} diff --git a/tests/Support/SupportTimeboxTest.php b/tests/Support/SupportTimeboxTest.php index ad91f2bc8..0b0cf61cc 100644 --- a/tests/Support/SupportTimeboxTest.php +++ b/tests/Support/SupportTimeboxTest.php @@ -7,7 +7,8 @@ use Exception; use Hypervel\Support\Timebox; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -15,6 +16,8 @@ class SupportTimeboxTest extends TestCase { + use VerifiesDoubles; + public function testMakeExecutesCallback(): void { $callback = function (): void { @@ -26,28 +29,28 @@ public function testMakeExecutesCallback(): void public function testMakeWaitsForMicroseconds(): void { - $mock = m::spy(Timebox::class)->shouldAllowMockingProtectedMethods()->makePartial(); + $mock = Double::for(Timebox::class)->passthru(); $mock->expects('usleep'); $mock->call(function (): void { }, 10000); - $mock->shouldHaveReceived('usleep')->once(); + $mock->received('usleep')->times(1); } public function testMakeShouldNotSleepWhenEarlyReturnHasBeenFlagged(): void { - $mock = m::spy(Timebox::class)->shouldAllowMockingProtectedMethods()->makePartial(); + $mock = Double::for(Timebox::class)->passthru(); $mock->call(function (Timebox $timebox): void { $timebox->returnEarly(); }, 10000); - $mock->shouldNotHaveReceived('usleep'); + $mock->received('usleep')->never(); } public function testMakeShouldSleepWhenDontEarlyReturnHasBeenFlagged(): void { - $mock = m::spy(Timebox::class)->shouldAllowMockingProtectedMethods()->makePartial(); + $mock = Double::for(Timebox::class)->passthru(); $mock->expects('usleep'); $mock->call(function (Timebox $timebox): void { @@ -55,12 +58,12 @@ public function testMakeShouldSleepWhenDontEarlyReturnHasBeenFlagged(): void $timebox->dontReturnEarly(); }, 10000); - $mock->shouldHaveReceived('usleep')->once(); + $mock->received('usleep')->times(1); } public function testMakeWaitsForMicrosecondsWhenExceptionIsThrown(): void { - $mock = m::spy(Timebox::class)->shouldAllowMockingProtectedMethods()->makePartial(); + $mock = Double::for(Timebox::class)->passthru(); $mock->expects('usleep'); try { @@ -70,13 +73,13 @@ public function testMakeWaitsForMicrosecondsWhenExceptionIsThrown(): void throw new Exception('Exception within Timebox callback.'); }, 10000); } finally { - $mock->shouldHaveReceived('usleep')->once(); + $mock->received('usleep')->times(1); } } public function testMakeShouldNotSleepWhenEarlyReturnHasBeenFlaggedAndExceptionIsThrown(): void { - $mock = m::spy(Timebox::class)->shouldAllowMockingProtectedMethods()->makePartial(); + $mock = Double::for(Timebox::class)->passthru(); try { $this->expectExceptionObject(new Exception('Exception within Timebox callback.')); @@ -86,7 +89,7 @@ public function testMakeShouldNotSleepWhenEarlyReturnHasBeenFlaggedAndExceptionI throw new Exception('Exception within Timebox callback.'); }, 10000); } finally { - $mock->shouldNotHaveReceived('usleep'); + $mock->received('usleep')->never(); } } @@ -100,7 +103,7 @@ public function testMakeDoesNotPadCancellationFromCallback(bool $wrapped): void $cancellation = new RuntimeException('Callback cleanup failed.', previous: $cancellation); } - $mock = m::spy(Timebox::class)->shouldAllowMockingProtectedMethods()->makePartial(); + $mock = Double::for(Timebox::class)->passthru(); try { $mock->call(fn () => throw $cancellation, 10000); @@ -109,7 +112,7 @@ public function testMakeDoesNotPadCancellationFromCallback(bool $wrapped): void } catch (Throwable $exception) { $this->assertSame($cancellation, $exception); } finally { - $mock->shouldNotHaveReceived('usleep'); + $mock->received('usleep')->never(); } } } diff --git a/tests/Testing/Concerns/TestDatabasesTest.php b/tests/Testing/Concerns/TestDatabasesTest.php index 35a69e628..02e26bf40 100644 --- a/tests/Testing/Concerns/TestDatabasesTest.php +++ b/tests/Testing/Concerns/TestDatabasesTest.php @@ -6,18 +6,22 @@ use Hypervel\Config\Repository as Config; use Hypervel\Container\Container; +use Hypervel\Database\Connection; use Hypervel\Database\DatabaseManager; use Hypervel\Support\Facades\Facade; use Hypervel\Testing\Concerns\TestDatabases; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionMethod; class TestDatabasesTest extends TestCase { + use VerifiesDoubles; + private mixed $originalParallelTesting; protected function setUp(): void @@ -61,7 +65,7 @@ public function testSwitchToDatabaseWithoutUrl(): void { $container = Container::getInstance(); - $db = m::mock(DatabaseManager::class); + $db = Double::for(DatabaseManager::class); $db->expects('purge'); $container->instance('db', $db); @@ -83,7 +87,7 @@ public function testSwitchToDatabaseWithUrl( ): void { $container = Container::getInstance(); - $db = m::mock(DatabaseManager::class); + $db = Double::for(DatabaseManager::class); $db->expects('purge'); $container->instance('db', $db); @@ -329,16 +333,16 @@ protected function whenNotUsingInMemoryDatabase( array $configuration = [], bool $expectsConnectionLookup = true, ): void { - $db = m::mock(DatabaseManager::class); + $db = Double::for(Connection::class); if ($expectsConnectionLookup) { - $db->shouldReceive('getConfig')->with('database')->andReturn($database); + $db->allows('getConfig')->with('database')->returns($database); if (! $withoutDatabases) { - $db->shouldReceive('getConfig')->with('driver')->andReturn($driver); + $db->allows('getConfig')->with('driver')->returns($driver); } } else { - $db->shouldNotReceive('getConfig'); + $db->expects('getConfig')->never(); } Container::getInstance()->instance('db', $db); diff --git a/tests/Testing/Concerns/TestViewsTest.php b/tests/Testing/Concerns/TestViewsTest.php index fcf79b4e0..bfa0f60e0 100644 --- a/tests/Testing/Concerns/TestViewsTest.php +++ b/tests/Testing/Concerns/TestViewsTest.php @@ -14,7 +14,6 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use Hypervel\View\Compilers\BladeCompiler; -use Mockery as m; use ReflectionMethod; use ReflectionProperty; @@ -135,7 +134,7 @@ public function testSwitchToCompiledViewPathUpdatesConfig(): void public function testSwitchToCompiledViewPathUpdatesCompilerCachePath(): void { $container = Container::getInstance(); - $compiler = new BladeCompiler(m::mock(Filesystem::class), '/original/path'); + $compiler = new BladeCompiler($this->filesystem, '/original/path'); $container->instance('blade.compiler', $compiler); diff --git a/tests/Translation/TranslationFileLoaderTest.php b/tests/Translation/TranslationFileLoaderTest.php index ac979e56e..a7a316876 100644 --- a/tests/Translation/TranslationFileLoaderTest.php +++ b/tests/Translation/TranslationFileLoaderTest.php @@ -8,32 +8,35 @@ use Hypervel\Tests\TestCase; use Hypervel\Translation\FileLoader; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; class TranslationFileLoaderTest extends TestCase { + use VerifiesDoubles; + public function testLoadMethodLoadsTranslationsFromAddedPath(): void { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $loader = new FileLoader($files, __DIR__); $loader->addPath(__DIR__ . '/another'); - $files->expects('exists')->with(__DIR__ . '/en/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/en/messages.php')->andReturn(['foo' => 'bar']); + $files->expects('exists')->with(__DIR__ . '/en/messages.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/en/messages.php')->returns(['foo' => 'bar']); - $files->expects('exists')->with(__DIR__ . '/another/en/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/another/en/messages.php')->andReturn(['baz' => 'backagesplash']); + $files->expects('exists')->with(__DIR__ . '/another/en/messages.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/another/en/messages.php')->returns(['baz' => 'backagesplash']); $this->assertEquals(['foo' => 'bar', 'baz' => 'backagesplash'], $loader->load('en', 'messages')); } public function testLoadMethodIgnoresLocalesAndGroupsContainingPathTraversal(): void { - $files = m::mock(Filesystem::class); - $files->shouldNotReceive('exists'); - $files->shouldNotReceive('getRequire'); + $files = Double::for(Filesystem::class); + $files->expects('exists')->never(); + $files->expects('getRequire')->never(); $loader = new FileLoader($files, __DIR__); $loader->addNamespace('namespace', __DIR__ . '/namespace'); @@ -50,80 +53,80 @@ public function testLoadMethodIgnoresLocalesAndGroupsContainingPathTraversal(): public function testLoadMethodAllowsGroupsInSubdirectories(): void { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $loader = new FileLoader($files, __DIR__); - $files->expects('exists')->with(__DIR__ . '/en/admin/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/en/admin/messages.php')->andReturn(['foo' => 'bar']); + $files->expects('exists')->with(__DIR__ . '/en/admin/messages.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/en/admin/messages.php')->returns(['foo' => 'bar']); $this->assertEquals(['foo' => 'bar'], $loader->load('en', 'admin/messages')); } public function testLoadMethodHandlesMissingAddedPath(): void { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $loader = new FileLoader($files, __DIR__); $loader->addPath(__DIR__ . '/missing'); - $files->expects('exists')->with(__DIR__ . '/en/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/en/messages.php')->andReturn(['foo' => 'bar']); + $files->expects('exists')->with(__DIR__ . '/en/messages.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/en/messages.php')->returns(['foo' => 'bar']); - $files->expects('exists')->with(__DIR__ . '/missing/en/messages.php')->andReturn(false); + $files->expects('exists')->with(__DIR__ . '/missing/en/messages.php')->returns(false); $this->assertEquals(['foo' => 'bar'], $loader->load('en', 'messages')); } public function testLoadMethodOverwritesExistingKeysFromAddedPath(): void { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $loader = new FileLoader($files, __DIR__); $loader->addPath(__DIR__ . '/another'); - $files->expects('exists')->with(__DIR__ . '/en/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/en/messages.php')->andReturn(['foo' => 'bar']); + $files->expects('exists')->with(__DIR__ . '/en/messages.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/en/messages.php')->returns(['foo' => 'bar']); - $files->expects('exists')->with(__DIR__ . '/another/en/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/another/en/messages.php')->andReturn(['foo' => 'baz']); + $files->expects('exists')->with(__DIR__ . '/another/en/messages.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/another/en/messages.php')->returns(['foo' => 'baz']); $this->assertEquals(['foo' => 'baz'], $loader->load('en', 'messages')); } public function testLoadMethodLoadsTranslationsFromMultipleAddedPaths(): void { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $loader = new FileLoader($files, __DIR__); $loader->addPath(__DIR__ . '/another'); $loader->addPath(__DIR__ . '/yet-another'); - $files->expects('exists')->with(__DIR__ . '/en/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/en/messages.php')->andReturn(['foo' => 'bar']); + $files->expects('exists')->with(__DIR__ . '/en/messages.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/en/messages.php')->returns(['foo' => 'bar']); - $files->expects('exists')->with(__DIR__ . '/another/en/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/another/en/messages.php')->andReturn(['baz' => 'backagesplash']); + $files->expects('exists')->with(__DIR__ . '/another/en/messages.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/another/en/messages.php')->returns(['baz' => 'backagesplash']); - $files->expects('exists')->with(__DIR__ . '/yet-another/en/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/yet-another/en/messages.php')->andReturn(['qux' => 'quux']); + $files->expects('exists')->with(__DIR__ . '/yet-another/en/messages.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/yet-another/en/messages.php')->returns(['qux' => 'quux']); $this->assertEquals(['foo' => 'bar', 'baz' => 'backagesplash', 'qux' => 'quux'], $loader->load('en', 'messages')); } public function testLoadMethodWithoutNamespacesProperlyCallsLoader(): void { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $loader = new FileLoader($files, __DIR__); - $files->expects('exists')->with(__DIR__ . '/en/foo.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/en/foo.php')->andReturn(['messages']); + $files->expects('exists')->with(__DIR__ . '/en/foo.php')->returns(true); + $files->expects('getRequire')->with(__DIR__ . '/en/foo.php')->returns(['messages']); $this->assertEquals(['messages'], $loader->load('en', 'foo', null)); } public function testLoadMethodWithoutNamespacesProperlyCallsLoaderWithMultiplePaths(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with(__DIR__ . '/en/foo.php')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/second/en/foo.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/en/foo.php')->andReturn(['messages' => 'first']); - $files->expects('getRequire')->with(__DIR__ . '/second/en/foo.php')->andReturn(['messages' => 'second']); + $files = Double::for(Filesystem::class); + $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']); + $files->expects('getRequire')->with(__DIR__ . '/second/en/foo.php')->returns(['messages' => 'second']); $loader = new FileLoader($files, [__DIR__, __DIR__ . '/second']); $this->assertEquals(['messages' => 'second'], $loader->load('en', 'foo', null)); @@ -131,10 +134,10 @@ public function testLoadMethodWithoutNamespacesProperlyCallsLoaderWithMultiplePa public function testLoadMethodWithNamespacesProperlyCallsLoader(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with('bar/en/foo.php')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->andReturn(false); - $files->expects('getRequire')->with('bar/en/foo.php')->andReturn(['foo' => 'bar']); + $files = Double::for(Filesystem::class); + $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']); $loader = new FileLoader($files, __DIR__); $loader->addNamespace('namespace', 'bar'); @@ -143,11 +146,11 @@ public function testLoadMethodWithNamespacesProperlyCallsLoader(): void public function testLoadMethodWithNamespacesProperlyCallsLoaderWithMultiplePaths(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with('test-namespace-dir/en/foo.php')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->andReturn(false); - $files->expects('exists')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->andReturn(false); - $files->expects('getRequire')->with('test-namespace-dir/en/foo.php')->andReturn(['foo' => 'bar']); + $files = Double::for(Filesystem::class); + $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); + $files->expects('getRequire')->with('test-namespace-dir/en/foo.php')->returns(['foo' => 'bar']); $loader = new FileLoader($files, [__DIR__, __DIR__ . '/second']); $loader->addNamespace('namespace', 'test-namespace-dir'); @@ -156,11 +159,11 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderWithMultiplePaths public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOverrides(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with('bar/en/foo.php')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->andReturn(true); - $files->expects('getRequire')->with('bar/en/foo.php')->andReturn(['foo' => 'bar']); - $files->expects('getRequire')->with(__DIR__ . '/vendor/namespace/en/foo.php')->andReturn(['foo' => 'override', 'baz' => 'boom']); + $files = Double::for(Filesystem::class); + $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']); + $files->expects('getRequire')->with(__DIR__ . '/vendor/namespace/en/foo.php')->returns(['foo' => 'override', 'baz' => 'boom']); $loader = new FileLoader($files, __DIR__); $loader->addNamespace('namespace', 'bar'); @@ -169,13 +172,13 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOver public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOverridesWithMultiplePaths(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with('test-namespace-dir/en/foo.php')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->andReturn(true); - $files->expects('getRequire')->with('test-namespace-dir/en/foo.php')->andReturn(['foo' => 'bar']); - $files->expects('getRequire')->with(__DIR__ . '/vendor/namespace/en/foo.php')->andReturn(['foo' => 'override', 'baz' => 'boom']); - $files->expects('getRequire')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->andReturn(['foo' => 'override-2', 'baz' => 'boom-2']); + $files = Double::for(Filesystem::class); + $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); + $files->expects('getRequire')->with('test-namespace-dir/en/foo.php')->returns(['foo' => 'bar']); + $files->expects('getRequire')->with(__DIR__ . '/vendor/namespace/en/foo.php')->returns(['foo' => 'override', 'baz' => 'boom']); + $files->expects('getRequire')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->returns(['foo' => 'override-2', 'baz' => 'boom-2']); $loader = new FileLoader($files, [__DIR__, __DIR__ . '/second']); $loader->addNamespace('namespace', 'test-namespace-dir'); @@ -184,13 +187,13 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOver public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOverridesWithMultiplePathsWithMissingKey(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with('test-namespace-dir/en/foo.php')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->andReturn(true); - $files->expects('getRequire')->with('test-namespace-dir/en/foo.php')->andReturn(['foo' => 'bar']); - $files->expects('getRequire')->with(__DIR__ . '/vendor/namespace/en/foo.php')->andReturn(['foo' => 'override', 'baz' => 'boom']); - $files->expects('getRequire')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->andReturn(['baz' => 'boom-2']); + $files = Double::for(Filesystem::class); + $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); + $files->expects('getRequire')->with('test-namespace-dir/en/foo.php')->returns(['foo' => 'bar']); + $files->expects('getRequire')->with(__DIR__ . '/vendor/namespace/en/foo.php')->returns(['foo' => 'override', 'baz' => 'boom']); + $files->expects('getRequire')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->returns(['baz' => 'boom-2']); $loader = new FileLoader($files, [__DIR__, __DIR__ . '/second']); $loader->addNamespace('namespace', 'test-namespace-dir'); @@ -200,10 +203,10 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOver #[DataProvider('invalidLocaleProvider')] public function testInvalidLocalesAreRejectedBeforeFilesystemAccess(string $locale, string $group = 'messages', ?string $namespace = null): void { - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->never(); - $files->shouldReceive('get')->never(); - $files->shouldReceive('getRequire')->never(); + $files = Double::for(Filesystem::class); + $files->expects('exists')->never(); + $files->expects('get')->never(); + $files->expects('getRequire')->never(); $loader = new FileLoader($files, __DIR__); $loader->addNamespace('namespace', __DIR__ . '/namespace'); @@ -234,12 +237,12 @@ public static function invalidLocaleProvider(): array public function testDotBearingLocalesReachPhpAndJsonTranslationPaths(): void { - $loader = new FileLoader($files = m::mock(Filesystem::class), __DIR__); + $loader = new FileLoader($files = Double::for(Filesystem::class), __DIR__); - $files->expects('exists')->with(__DIR__ . '/en.UTF-8/messages.php')->andReturn(true); - $files->expects('getRequire')->with(__DIR__ . '/en.UTF-8/messages.php')->andReturn(['foo' => 'bar']); - $files->expects('exists')->with(__DIR__ . '/en.UTF-8.json')->andReturn(true); - $files->expects('get')->with(__DIR__ . '/en.UTF-8.json')->andReturn('{"foo":"bar"}'); + $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']); + $files->expects('exists')->with(__DIR__ . '/en.UTF-8.json')->returns(true); + $files->expects('get')->with(__DIR__ . '/en.UTF-8.json')->returns('{"foo":"bar"}'); $this->assertSame(['foo' => 'bar'], $loader->load('en.UTF-8', 'messages')); $this->assertSame(['foo' => 'bar'], $loader->load('en.UTF-8', '*', '*')); @@ -247,9 +250,9 @@ public function testDotBearingLocalesReachPhpAndJsonTranslationPaths(): void public function testEmptyArraysReturnedWhenFilesDontExist(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with(__DIR__ . '/en/foo.php')->andReturn(false); - $files->shouldReceive('getRequire')->never(); + $files = Double::for(Filesystem::class); + $files->expects('exists')->with(__DIR__ . '/en/foo.php')->returns(false); + $files->expects('getRequire')->never(); $loader = new FileLoader($files, __DIR__); $this->assertSame([], $loader->load('en', 'foo', null)); @@ -257,8 +260,8 @@ public function testEmptyArraysReturnedWhenFilesDontExist(): void public function testEmptyArraysReturnedWhenFilesDontExistForNamespacedItems(): void { - $files = m::mock(Filesystem::class); - $files->shouldReceive('getRequire')->never(); + $files = Double::for(Filesystem::class); + $files->expects('getRequire')->never(); $loader = new FileLoader($files, __DIR__); $this->assertSame([], $loader->load('en', 'foo', 'bar')); @@ -266,9 +269,9 @@ public function testEmptyArraysReturnedWhenFilesDontExistForNamespacedItems(): v public function testLoadMethodForJSONProperlyCallsLoader(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with(__DIR__ . '/en.json')->andReturn(true); - $files->expects('get')->with(__DIR__ . '/en.json')->andReturn('{"foo":"bar"}'); + $files = Double::for(Filesystem::class); + $files->expects('exists')->with(__DIR__ . '/en.json')->returns(true); + $files->expects('get')->with(__DIR__ . '/en.json')->returns('{"foo":"bar"}'); $loader = new FileLoader($files, __DIR__); $this->assertEquals(['foo' => 'bar'], $loader->load('en', '*', '*')); @@ -276,37 +279,37 @@ public function testLoadMethodForJSONProperlyCallsLoader(): void public function testLoadMethodForJsonAcceptsArraysWithNumericKeys(): void { - $loader = new FileLoader($files = m::mock(Filesystem::class), __DIR__); - $files->expects('exists')->with(__DIR__ . '/en.json')->andReturn(true); - $files->expects('get')->with(__DIR__ . '/en.json')->andReturn('["first","second"]'); + $loader = new FileLoader($files = Double::for(Filesystem::class), __DIR__); + $files->expects('exists')->with(__DIR__ . '/en.json')->returns(true); + $files->expects('get')->with(__DIR__ . '/en.json')->returns('["first","second"]'); $this->assertSame(['first', 'second'], $loader->load('en', '*', '*')); } public function testLoadMethodForJSONProperlyCallsLoaderForMultiplePaths(): void { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $loader = new FileLoader($files, __DIR__); $loader->addJsonPath(__DIR__ . '/another'); - $files->expects('exists')->with(__DIR__ . '/en.json')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/another/en.json')->andReturn(true); - $files->expects('get')->with(__DIR__ . '/en.json')->andReturn('{"foo":"bar"}'); - $files->expects('get')->with(__DIR__ . '/another/en.json')->andReturn('{"foo":"backagebar", "baz": "backagesplash"}'); + $files->expects('exists')->with(__DIR__ . '/en.json')->returns(true); + $files->expects('exists')->with(__DIR__ . '/another/en.json')->returns(true); + $files->expects('get')->with(__DIR__ . '/en.json')->returns('{"foo":"bar"}'); + $files->expects('get')->with(__DIR__ . '/another/en.json')->returns('{"foo":"backagebar", "baz": "backagesplash"}'); $this->assertEquals(['foo' => 'bar', 'baz' => 'backagesplash'], $loader->load('en', '*', '*')); } public function testLoadMethodForJSONPreservesNumericKeys(): void { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $loader = new FileLoader($files, __DIR__); $loader->addJsonPath(__DIR__ . '/another'); - $files->expects('exists')->with(__DIR__ . '/en.json')->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/another/en.json')->andReturn(true); - $files->expects('get')->with(__DIR__ . '/en.json')->andReturn('{"404":"Page not found","foo":"bar"}'); - $files->expects('get')->with(__DIR__ . '/another/en.json')->andReturn('{"404":"Not found","500":"Server error"}'); + $files->expects('exists')->with(__DIR__ . '/en.json')->returns(true); + $files->expects('exists')->with(__DIR__ . '/another/en.json')->returns(true); + $files->expects('get')->with(__DIR__ . '/en.json')->returns('{"404":"Page not found","foo":"bar"}'); + $files->expects('get')->with(__DIR__ . '/another/en.json')->returns('{"404":"Not found","500":"Server error"}'); $this->assertSame([404 => 'Page not found', 500 => 'Server error', 'foo' => 'bar'], $loader->load('en', '*', '*')); } @@ -314,12 +317,12 @@ public function testLoadMethodForJSONPreservesNumericKeys(): void #[DataProvider('invalidJsonRootProvider')] public function testLoadMethodThrowExceptionWhenProvideInvalidJSON(string $json): void { - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $loader = new FileLoader($files, __DIR__); $loader->addJsonPath(__DIR__ . '/invalid'); - $files->expects('exists')->with(__DIR__ . '/invalid/en.json')->andReturn(true); - $files->expects('get')->with(__DIR__ . '/invalid/en.json')->andReturn($json); + $files->expects('exists')->with(__DIR__ . '/invalid/en.json')->returns(true); + $files->expects('get')->with(__DIR__ . '/invalid/en.json')->returns($json); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs( @@ -346,9 +349,9 @@ public static function invalidJsonRootProvider(): array public function testLoadMethodRejectsScalarJsonTranslationValues(): void { - $loader = new FileLoader($files = m::mock(Filesystem::class), __DIR__); - $files->expects('exists')->with(__DIR__ . '/en.json')->andReturn(true); - $files->expects('get')->with(__DIR__ . '/en.json')->andReturn('{"unread":0}'); + $loader = new FileLoader($files = Double::for(Filesystem::class), __DIR__); + $files->expects('exists')->with(__DIR__ . '/en.json')->returns(true); + $files->expects('get')->with(__DIR__ . '/en.json')->returns('{"unread":0}'); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs( @@ -360,16 +363,16 @@ public function testLoadMethodRejectsScalarJsonTranslationValues(): void public function testLoadMethodAllowsNullJsonTranslationValues(): void { - $loader = new FileLoader($files = m::mock(Filesystem::class), __DIR__); - $files->expects('exists')->with(__DIR__ . '/en.json')->andReturn(true); - $files->expects('get')->with(__DIR__ . '/en.json')->andReturn('{"untranslated":null}'); + $loader = new FileLoader($files = Double::for(Filesystem::class), __DIR__); + $files->expects('exists')->with(__DIR__ . '/en.json')->returns(true); + $files->expects('get')->with(__DIR__ . '/en.json')->returns('{"untranslated":null}'); $this->assertSame(['untranslated' => null], $loader->load('en', '*', '*')); } public function testAllRegisteredNamespaceReturnProperly(): void { - $loader = new FileLoader(m::mock(Filesystem::class), __DIR__); + $loader = new FileLoader(Double::for(Filesystem::class), __DIR__); $loader->addNamespace('namespace', 'foo'); $loader->addNamespace('namespace2', 'bar'); $this->assertEquals(['namespace' => 'foo', 'namespace2' => 'bar'], $loader->namespaces()); @@ -377,7 +380,7 @@ public function testAllRegisteredNamespaceReturnProperly(): void public function testAllAddedJsonPathsReturnProperly(): void { - $loader = new FileLoader(m::mock(Filesystem::class), __DIR__); + $loader = new FileLoader(Double::for(Filesystem::class), __DIR__); $path1 = __DIR__ . '/another'; $path2 = __DIR__ . '/another2'; $loader->addJsonPath($path1); @@ -387,7 +390,7 @@ public function testAllAddedJsonPathsReturnProperly(): void public function testAllAddedPathsReturnProperly(): void { - $loader = new FileLoader(m::mock(Filesystem::class), __DIR__); + $loader = new FileLoader(Double::for(Filesystem::class), __DIR__); $path1 = __DIR__ . '/another'; $path2 = __DIR__ . '/another2'; $loader->addPath($path1); diff --git a/tests/Translation/TranslationTranslatorTest.php b/tests/Translation/TranslationTranslatorTest.php index d40105f42..f78dc86a7 100644 --- a/tests/Translation/TranslationTranslatorTest.php +++ b/tests/Translation/TranslationTranslatorTest.php @@ -18,7 +18,8 @@ use Hypervel\Translation\MissingTranslationGroups; use Hypervel\Translation\Translator; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionProperty; use RuntimeException; use stdClass; @@ -26,6 +27,8 @@ class TranslationTranslatorTest extends TestCase { + use VerifiesDoubles; + public function testSetLocaleRejectsPathTraversal(): void { $t = new Translator($this->getLoader(), 'en'); @@ -62,13 +65,13 @@ public function testHasMethodReturnsFalseWhenReturnedTranslationIsNull(): void $this->assertFalse($translator->hasForLocale('foo', 'bar')); $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'foo', '*')->andReturn(['foo' => 'bar']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'foo', '*')->returns(['foo' => 'bar']); $this->assertTrue($translator->hasForLocale('foo')); $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'foo', '*')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'foo', '*')->returns([]); $this->assertFalse($translator->hasForLocale('foo')); } @@ -89,8 +92,8 @@ public function testHasSuppressesMissingKeyCallbacks(): void public function testGetMethodProperlyLoadsAndRetrievesItem(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :foo', 'qux' => ['tree :foo', 'breeze :foo']]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['foo' => 'foo', 'baz' => 'breeze :foo', 'qux' => ['tree :foo', 'breeze :foo']]); $this->assertEquals(['tree bar', 'breeze bar'], $translator->get('foo::bar.qux', ['foo' => 'bar'], 'en')); $this->assertSame('breeze bar', $translator->get('foo::bar.baz', ['foo' => 'bar'], 'en')); $this->assertSame('foo', $translator->get('foo::bar.foo')); @@ -99,8 +102,8 @@ public function testGetMethodProperlyLoadsAndRetrievesItem(): void public function testGetMethodProperlyLoadsAndRetrievesArrayItem(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :foo', 'qux' => ['tree :foo', 'breeze :foo', 'beep' => ['rock' => 'tree :foo']]]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['foo' => 'foo', 'baz' => 'breeze :foo', 'qux' => ['tree :foo', 'breeze :foo', 'beep' => ['rock' => 'tree :foo']]]); $this->assertEquals(['foo' => 'foo', 'baz' => 'breeze bar', 'qux' => ['tree bar', 'breeze bar', 'beep' => ['rock' => 'tree bar']]], $translator->get('foo::bar', ['foo' => 'bar'], 'en')); $this->assertSame('breeze bar', $translator->get('foo::bar.baz', ['foo' => 'bar'], 'en')); $this->assertSame('foo', $translator->get('foo::bar.foo')); @@ -109,8 +112,8 @@ public function testGetMethodProperlyLoadsAndRetrievesArrayItem(): void public function testStringMethodProperlyLoadsAndRetrievesStringItem(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['baz' => 'breeze :foo']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['baz' => 'breeze :foo']); $this->assertSame('breeze bar', $translator->string('foo::bar.baz', ['foo' => 'bar'], 'en')); } @@ -118,8 +121,8 @@ public function testStringMethodProperlyLoadsAndRetrievesStringItem(): void public function testStringMethodThrowsExceptionForArrayItem(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['baz' => ['breeze']]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['baz' => ['breeze']]); $this->expectExceptionObject(new InvalidArgumentException('Translation value for key [foo::bar.baz] must be a string, array given.')); $translator->string('foo::bar.baz', [], 'en'); @@ -128,8 +131,8 @@ public function testStringMethodThrowsExceptionForArrayItem(): void public function testArrayMethodProperlyLoadsAndRetrievesArrayItem(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['baz' => ['breeze :foo']]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['baz' => ['breeze :foo']]); $this->assertSame(['breeze bar'], $translator->array('foo::bar.baz', ['foo' => 'bar'], 'en')); } @@ -138,11 +141,11 @@ public function testEmptyArrayItemDoesNotFallBackWhileEmptyGroupRemainsMissing() { $translator = new Translator($this->getLoader(), 'en'); $translator->setFallback('lv'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['empty' => []]); - $translator->getLoader()->shouldReceive('load')->with('lv', 'bar', 'foo')->andReturn(['empty' => ['fallback']]); - $translator->getLoader()->expects('load')->with('en', 'missing', 'foo')->andReturn([]); - $translator->getLoader()->expects('load')->with('lv', 'missing', 'foo')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['empty' => []]); + $translator->getLoader()->allows('load')->with('lv', 'bar', 'foo')->returns(['empty' => ['fallback']]); + $translator->getLoader()->expects('load')->with('en', 'missing', 'foo')->returns([]); + $translator->getLoader()->expects('load')->with('lv', 'missing', 'foo')->returns([]); $this->assertSame([], $translator->get('foo::bar.empty')); $this->assertTrue($translator->has('foo::bar.empty')); @@ -153,8 +156,8 @@ public function testEmptyArrayItemDoesNotFallBackWhileEmptyGroupRemainsMissing() public function testArrayMethodThrowsExceptionForStringItem(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['baz' => 'breeze']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['baz' => 'breeze']); $this->expectExceptionObject(new InvalidArgumentException('Translation value for key [foo::bar.baz] must be an array, string given.')); $translator->array('foo::bar.baz', [], 'en'); @@ -163,9 +166,9 @@ public function testArrayMethodThrowsExceptionForStringItem(): void public function testGetMethodForNonExistingReturnsSameKey(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :foo', 'qux' => ['tree :foo', 'breeze :foo']]); - $translator->getLoader()->expects('load')->with('en', 'unknown', 'foo')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['foo' => 'foo', 'baz' => 'breeze :foo', 'qux' => ['tree :foo', 'breeze :foo']]); + $translator->getLoader()->expects('load')->with('en', 'unknown', 'foo')->returns([]); $this->assertSame('foo::unknown', $translator->get('foo::unknown', ['foo' => 'bar'], 'en')); $this->assertSame('foo::bar.unknown', $translator->get('foo::bar.unknown', ['foo' => 'bar'], 'en')); $this->assertSame('foo::unknown.bar', $translator->get('foo::unknown.bar')); @@ -174,16 +177,16 @@ public function testGetMethodForNonExistingReturnsSameKey(): void public function testTransMethodProperlyLoadsAndRetrievesItemWithHTMLInTheMessage(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'foo', '*')->andReturn(['bar' => 'breeze

test

']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'foo', '*')->returns(['bar' => 'breeze

test

']); $this->assertSame('breeze

test

', $translator->get('foo.bar', [], 'en')); } public function testGetMethodProperlyLoadsAndRetrievesItemWithCapitalization(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :0 :Foo :BAR']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['foo' => 'foo', 'baz' => 'breeze :0 :Foo :BAR']); $this->assertSame('breeze john Bar FOO', $translator->get('foo::bar.baz', ['john', 'foo' => 'bar', 'bar' => 'foo'], 'en')); $this->assertSame('foo', $translator->get('foo::bar.foo')); } @@ -191,8 +194,8 @@ public function testGetMethodProperlyLoadsAndRetrievesItemWithCapitalization(): public function testGetMethodProperlyLoadsAndRetrievesItemWithLongestReplacementsFirst(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :foo :foobar']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns(['foo' => 'foo', 'baz' => 'breeze :foo :foobar']); $this->assertSame('breeze bar taylor', $translator->get('foo::bar.baz', ['foo' => 'bar', 'foobar' => 'taylor'], 'en')); $this->assertSame('breeze foo bar baz taylor', $translator->get('foo::bar.baz', ['foo' => 'foo bar baz', 'foobar' => 'taylor'], 'en')); $this->assertSame('foo', $translator->get('foo::bar.foo')); @@ -202,9 +205,9 @@ public function testGetMethodProperlyLoadsAndRetrievesItemForFallback(): void { $translator = new Translator($this->getLoader(), 'en'); $translator->setFallback('lv'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->andReturn([]); - $translator->getLoader()->expects('load')->with('lv', 'bar', 'foo')->andReturn(['foo' => 'foo', 'baz' => 'breeze :foo']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bar', 'foo')->returns([]); + $translator->getLoader()->expects('load')->with('lv', 'bar', 'foo')->returns(['foo' => 'foo', 'baz' => 'breeze :foo']); $this->assertSame('breeze bar', $translator->get('foo::bar.baz', ['foo' => 'bar'], 'en')); $this->assertSame('foo', $translator->get('foo::bar.foo')); } @@ -238,7 +241,7 @@ public function testGetDoesNotCallGetLineTwiceForMissingKeyWhenLocaleMatchesFall { $translator = $this->getMockBuilder(Translator::class)->onlyMethods(['getLine'])->setConstructorArgs([$this->getLoader(), 'en'])->getMock(); $translator->setFallback('en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); $translator->expects($this->once())->method('getLine')->with('*', 'messages', 'en', 'test', [])->willReturn(null); @@ -248,8 +251,8 @@ public function testGetDoesNotCallGetLineTwiceForMissingKeyWhenLocaleMatchesFall public function testGetMethodProperlyLoadsAndRetrievesItemForGlobalNamespace(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'foo', '*')->andReturn(['bar' => 'breeze :foo']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'foo', '*')->returns(['bar' => 'breeze :foo']); $this->assertSame('breeze bar', $translator->get('foo.bar', ['foo' => 'bar'])); } @@ -285,8 +288,8 @@ public function testLinesAddedBeforeLoadingAreAppliedInCallOrder(): void public function testEmptyGroupsAreLoadedOnceWithinAnExecution(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'messages', '*')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'messages', '*')->returns([]); $this->assertSame('messages.missing', $translator->get('messages.missing')); $this->assertSame('messages.other', $translator->get('messages.other')); @@ -338,9 +341,9 @@ public function testPendingLinesRemainWhenLoadingFails(): void { $exception = new RuntimeException('Unable to load translations.'); $attempts = 0; - $loader = m::mock(Loader::class); - $loader->expects('load')->with('en', '*', '*')->andReturn([]); - $loader->expects('load')->twice()->with('en', 'messages', '*')->andReturnUsing( + $loader = Double::for(Loader::class); + $loader->expects('load')->with('en', '*', '*')->returns([]); + $loader->expects('load')->times(2)->with('en', 'messages', '*')->resolves( static function () use (&$attempts, $exception): array { if (++$attempts === 1) { throw $exception; @@ -441,13 +444,15 @@ public function testChoiceMethodProperlyLoadsAndRetrievesItemForAnInt(): void 'items' => '{0} none|{1} one|[2,*] :count items', ]); $translator = new Translator($loader, 'en'); - $selector = m::mock(MessageSelector::class)->makePartial(); - $selector->expects('choose')->with('{0} none|{1} one|[2,*] :count items', 1, 'en')->passthru(); - $selector->expects('choose')->with('{0} none|{1} one|[2,*] :count items', 10, 'en')->passthru(); + $selector = Double::for(MessageSelector::class)->passthru(); $translator->setSelector($selector); $this->assertSame('one', $translator->choice('messages.items', 1)); $this->assertSame('10 items', $translator->choice('messages.items', 10)); + + $selector->received('choose')->times(2); + $selector->received('choose')->with('{0} none|{1} one|[2,*] :count items', 1, 'en')->times(1); + $selector->received('choose')->with('{0} none|{1} one|[2,*] :count items', 10, 'en')->times(1); } public function testChoiceMethodProperlyLoadsAndRetrievesItemForAFloat(): void @@ -456,13 +461,15 @@ public function testChoiceMethodProperlyLoadsAndRetrievesItemForAFloat(): void 'items' => '[1,*] :count items', ]); $translator = new Translator($loader, 'en'); - $selector = m::mock(MessageSelector::class)->makePartial(); - $selector->expects('choose')->with('[1,*] :count items', 1.2, 'en')->passthru(); - $selector->expects('choose')->with('[1,*] :count items', 2.0, 'en')->passthru(); + $selector = Double::for(MessageSelector::class)->passthru(); $translator->setSelector($selector); $this->assertSame('1.2 items', $translator->choice('messages.items', 1.2)); $this->assertSame('2 items', $translator->choice('messages.items', 2.0)); + + $selector->received('choose')->times(2); + $selector->received('choose')->with('[1,*] :count items', 1.2, 'en')->times(1); + $selector->received('choose')->with('[1,*] :count items', 2.0, 'en')->times(1); } public function testChoiceMethodProperlyCountsCollectionsAndLoadsAndRetrievesItem(): void @@ -471,12 +478,14 @@ public function testChoiceMethodProperlyCountsCollectionsAndLoadsAndRetrievesIte 'items' => '{0} none|{1} one|[2,*] :count items', ]); $translator = new Translator($loader, 'en'); - $selector = m::mock(MessageSelector::class)->makePartial(); - $selector->expects('choose')->twice()->with('{0} none|{1} one|[2,*] :count items', 3, 'en')->passthru(); + $selector = Double::for(MessageSelector::class)->passthru(); $translator->setSelector($selector); $this->assertSame('3 items', $translator->choice('messages.items', ['a', 'b', 'c'])); $this->assertSame('3 items', $translator->choice('messages.items', new Collection(['a', 'b', 'c']))); + + $selector->received('choose')->times(2); + $selector->received('choose')->times(2)->with('{0} none|{1} one|[2,*] :count items', 3, 'en'); } public function testChoiceMethodProperlySelectsLocaleForChoose(): void @@ -486,8 +495,8 @@ public function testChoiceMethodProperlySelectsLocaleForChoose(): void ]); $translator = new Translator($loader, 'en'); $translator->setFallback('fr'); - $selector = m::mock(MessageSelector::class); - $selector->expects('choose')->with('{0} aucun|{1} un|[2,*] :count éléments', 2, 'fr')->andReturn(':count éléments'); + $selector = Double::for(MessageSelector::class); + $selector->expects('choose')->with('{0} aucun|{1} un|[2,*] :count éléments', 2, 'fr')->returns(':count éléments'); $translator->setSelector($selector); $this->assertSame('2 éléments', $translator->choice('messages.items', 2)); @@ -499,11 +508,13 @@ public function testChoiceMethodProperlyUsesCustomCountReplacement(): void ':count foos' => '{1} :count foos|[2,*] :count foos', ]); $translator = new Translator($loader, 'en'); - $selector = m::mock(MessageSelector::class)->makePartial(); - $selector->expects('choose')->with('{1} :count foos|[2,*] :count foos', 1234, 'en')->passthru(); + $selector = Double::for(MessageSelector::class)->passthru(); $translator->setSelector($selector); $this->assertSame('1,234 foos', $translator->choice(':count foos', 1234, ['count' => '1,234'])); + + $selector->received('choose')->times(1); + $selector->received('choose')->with('{1} :count foos|[2,*] :count foos', 1234, 'en')->times(1); } public function testChoiceAppliesReplacementsOnceAfterSelectingThePluralForm(): void @@ -537,14 +548,14 @@ public function testChoiceRequiresAStringTranslation(): void public function testGetJson(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn(['foo' => 'one']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns(['foo' => 'one']); $this->assertSame('one', $translator->get('foo')); } public function testGetJsonPreservesFalseyValuesAndHasAgreement(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([ + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([ 'empty' => '', 'zero' => '0', 'items' => [], @@ -560,10 +571,10 @@ public function testGetJsonPreservesFalseyValuesAndHasAgreement(): void public function testNullJsonTranslationValueIsTreatedAsMissing(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with(__DIR__ . '/en.json')->andReturn(true); - $files->expects('get')->with(__DIR__ . '/en.json')->andReturn('{"untranslated":null}'); - $files->expects('exists')->with(__DIR__ . '/en/untranslated.php')->andReturn(false); + $files = Double::for(Filesystem::class); + $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); $translator = new Translator(new FileLoader($files, __DIR__), 'en'); @@ -590,7 +601,7 @@ public function testGetPreservesMixedArrayLeavesForJsonTranslations(): void $expected['nested']['message'] = 'Welcome Taylor'; $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn(['payload' => $line]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns(['payload' => $line]); $this->assertSame($line, $translator->get('payload')); $result = $translator->get('payload', ['name' => 'Taylor']); @@ -618,8 +629,8 @@ public function testGetPreservesMixedArrayLeavesForGroupedTranslations(): void $expected['nested']['message'] = 'Welcome Taylor'; $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'messages', '*')->andReturn(['payload' => $line]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'messages', '*')->returns(['payload' => $line]); $this->assertSame($line, $translator->get('messages.payload')); $result = $translator->get('messages.payload', ['name' => 'Taylor']); @@ -631,68 +642,68 @@ public function testGetPreservesMixedArrayLeavesForGroupedTranslations(): void public function testGetJsonReplaces(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn(['foo :i:c :u' => 'bar :i:c :u']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns(['foo :i:c :u' => 'bar :i:c :u']); $this->assertSame('bar onetwo three', $translator->get('foo :i:c :u', ['i' => 'one', 'c' => 'two', 'u' => 'three'])); } public function testGetJsonHasAtomicReplacements(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn(['Hello :foo!' => 'Hello :foo!']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns(['Hello :foo!' => 'Hello :foo!']); $this->assertSame('Hello baz:bar!', $translator->get('Hello :foo!', ['foo' => 'baz:bar', 'bar' => 'abcdef'])); } public function testGetJsonReplacesForAssociativeInput(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn(['foo :i :c' => 'bar :i :c']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns(['foo :i :c' => 'bar :i :c']); $this->assertSame('bar eye see', $translator->get('foo :i :c', ['i' => 'eye', 'c' => 'see'])); } public function testGetJsonPreservesOrder(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn(['to :name I give :greeting' => ':greeting :name']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns(['to :name I give :greeting' => ':greeting :name']); $this->assertSame('Greetings David', $translator->get('to :name I give :greeting', ['name' => 'David', 'greeting' => 'Greetings'])); } public function testGetJsonForNonExistingJsonKeyLooksForRegularKeys(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'foo', '*')->andReturn(['bar' => 'one']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'foo', '*')->returns(['bar' => 'one']); $this->assertSame('one', $translator->get('foo.bar')); } public function testGetJsonForNonExistingJsonKeyLooksForRegularKeysAndReplace(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'foo', '*')->andReturn(['bar' => 'one :message']); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'foo', '*')->returns(['bar' => 'one :message']); $this->assertSame('one two', $translator->get('foo.bar', ['message' => 'two'])); } public function testGetJsonForNonExistingReturnsSameKey(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'Foo that bar', '*')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'Foo that bar', '*')->returns([]); $this->assertSame('Foo that bar', $translator->get('Foo that bar')); } public function testGetJsonForNonExistingReturnsSameKeyAndReplaces(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'foo :message', '*')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'foo :message', '*')->returns([]); $this->assertSame('foo baz', $translator->get('foo :message', ['message' => 'baz'])); } public function testEmptyFallbacks(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'foo :message', '*')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'foo :message', '*')->returns([]); $this->assertSame('foo ', $translator->get('foo :message', ['message' => null])); } @@ -702,7 +713,7 @@ public function testGetJsonReplacesWithStringable(): void $translator->getLoader() ->expects('load') ->with('en', '*', '*') - ->andReturn(['test' => 'the date is :date']); + ->returns(['test' => 'the date is :date']); $date = CarbonImmutable::createFromTimestamp(0); @@ -726,7 +737,7 @@ public function testGetJsonReplacesWithRegisteredStringableClass(): void $translator->getLoader() ->expects('load') ->with('en', '*', '*') - ->andReturn(['test' => 'the date is :date']); + ->returns(['test' => 'the date is :date']); $translator->stringable( CarbonImmutable::class, @@ -778,7 +789,7 @@ public function testGetJsonReplacesWithEnums(): void $translator->getLoader() ->expects('load') ->with('en', '*', '*') - ->andReturn([ + ->returns([ 'string_backed_enum' => 'The release shipped in :month 2025', 'int_backed_enum' => 'Stay tuned for version :version', 'unit_enum' => ':person gets excited about every new release', @@ -804,8 +815,8 @@ public function testTagReplacements(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'We have some nice documentation', '*')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'We have some nice documentation', '*')->returns([]); $this->assertSame( 'We have some nice documentation', @@ -822,8 +833,8 @@ public function testTagReplacementsHandleMultipleOfSameTag(): void { $translator = new Translator($this->getLoader(), 'en'); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'bold something else also bold', '*')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'bold something else also bold', '*')->returns([]); $this->assertSame( 'bold something else also bold', @@ -844,16 +855,16 @@ public function testDetermineLocalesUsingMethod(): void return ['en', 'lz']; }); - $translator->getLoader()->expects('load')->with('en', '*', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('en', 'foo', '*')->andReturn([]); - $translator->getLoader()->expects('load')->with('lz', 'foo', '*')->andReturn([]); + $translator->getLoader()->expects('load')->with('en', '*', '*')->returns([]); + $translator->getLoader()->expects('load')->with('en', 'foo', '*')->returns([]); + $translator->getLoader()->expects('load')->with('lz', 'foo', '*')->returns([]); $this->assertSame('foo', $translator->get('foo')); } public function testConfiguredInvalidLocaleIsRejectedBeforeFilesystemAccess(): void { - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->never(); + $files = Double::for(Filesystem::class); + $files->expects('exists')->never(); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('Invalid characters present in locale.'); @@ -863,8 +874,8 @@ public function testConfiguredInvalidLocaleIsRejectedBeforeFilesystemAccess(): v public function testExplicitInvalidLocaleIsRejectedBeforeFilesystemAccess(): void { - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->never(); + $files = Double::for(Filesystem::class); + $files->expects('exists')->never(); $translator = new Translator(new FileLoader($files, __DIR__), 'en'); $this->expectException(InvalidArgumentException::class); @@ -875,8 +886,8 @@ public function testExplicitInvalidLocaleIsRejectedBeforeFilesystemAccess(): voi public function testInvalidFallbackLocaleIsRejectedBeforeItsFilesystemAccess(): void { - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->never(); + $files = Double::for(Filesystem::class); + $files->expects('exists')->never(); $translator = new Translator(new FileLoader($files, __DIR__), 'en'); $this->expectException(InvalidArgumentException::class); @@ -887,8 +898,8 @@ public function testInvalidFallbackLocaleIsRejectedBeforeItsFilesystemAccess(): public function testInvalidLocaleFromResolverIsRejectedBeforeItsFilesystemAccess(): void { - $files = m::mock(Filesystem::class); - $files->expects('exists')->with(__DIR__ . '/en.json')->andReturn(false); + $files = Double::for(Filesystem::class); + $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']); @@ -900,8 +911,8 @@ public function testInvalidLocaleFromResolverIsRejectedBeforeItsFilesystemAccess public function testLocaleSettersRejectInvalidLocaleImmediately(): void { - $loader = m::mock(Loader::class); - $loader->shouldReceive('load')->never(); + $loader = Double::for(Loader::class); + $loader->expects('load')->never(); $translator = new Translator($loader, 'en'); foreach (['setLocale', 'setBaseLocale'] as $method) { @@ -967,7 +978,7 @@ public function testDoubleUnderscoreHelperReturnsNullWhenKeyIsNull(): void protected function getLoader(): Loader { - return m::mock(Loader::class); + return Double::for(Loader::class); } protected function missingGroupCount(?MissingTranslationGroups $missingTranslationGroups): int diff --git a/tests/Validation/ValidationDatabasePresenceVerifierTest.php b/tests/Validation/ValidationDatabasePresenceVerifierTest.php index bb99fd539..892b4a410 100644 --- a/tests/Validation/ValidationDatabasePresenceVerifierTest.php +++ b/tests/Validation/ValidationDatabasePresenceVerifierTest.php @@ -19,21 +19,25 @@ use Hypervel\Validation\PresenceQuery; use Hypervel\Validation\Rules\Exists; use Hypervel\Validation\Validator; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; class ValidationDatabasePresenceVerifierTest extends TestCase { + use VerifiesDoubles; + public function testBasicCount(): void { - $db = m::mock(ConnectionResolverInterface::class); + $db = Double::for(ConnectionResolverInterface::class); $verifier = new DatabasePresenceVerifier($db); - $conn = m::mock(Connection::class); - $db->expects('connection')->with('connection')->andReturn($conn); - $builder = m::mock(Builder::class); - $conn->expects('table')->with('table')->andReturn($builder); - $builder->expects('useWritePdo')->andReturn($builder); - $builder->expects('where')->with('column', '=', 'value')->andReturn($builder); + $conn = Double::for(Connection::class); + $db->expects('connection')->with('connection')->returns($conn); + $builder = Double::for(Builder::class); + $conn->expects('table')->with('table')->returns($builder); + $builder->expects('useWritePdo')->returns($builder); + $builder->expects('where')->with('column', '=', 'value')->returns($builder); $extra = new DatabaseConditions( new DatabaseCondition('foo', DatabaseConditionOperator::IsNull), new DatabaseCondition('bar', DatabaseConditionOperator::IsNotNull), @@ -50,21 +54,21 @@ public function testBasicCount(): void $builder->expects('where')->with('not', '!=', 'admin'); $builder->expects('whereIn')->with('role', ['reader', 'editor']); $builder->expects('whereNotIn')->with('role', ['admin']); - $builder->expects('count')->andReturn(100); + $builder->expects('count')->returns(100); $this->assertSame(100, $verifier->getCount(new PresenceQuery('connection', 'table', 'column', $extra), 'value')); } public function testBasicCountWithClosures(): void { - $db = m::mock(ConnectionResolverInterface::class); + $db = Double::for(ConnectionResolverInterface::class); $verifier = new DatabasePresenceVerifier($db); - $conn = m::mock(Connection::class); - $db->expects('connection')->with('connection')->andReturn($conn); - $builder = m::mock(Builder::class); - $conn->expects('table')->with('table')->andReturn($builder); - $builder->expects('useWritePdo')->andReturn($builder); - $builder->expects('where')->with('column', '=', 'value')->andReturn($builder); + $conn = Double::for(Connection::class); + $db->expects('connection')->with('connection')->returns($conn); + $builder = Double::for(Builder::class); + $conn->expects('table')->with('table')->returns($builder); + $builder->expects('useWritePdo')->returns($builder); + $builder->expects('where')->with('column', '=', 'value')->returns($builder); $closure = function (Builder $query): void { $query->where('closure', 1); }; @@ -81,54 +85,54 @@ public function testBasicCountWithClosures(): void $builder->expects('where')->with('baz', '=', 'taylor'); $builder->expects('where')->with('faz', '=', '1'); $builder->expects('where')->with('not', '!=', 'admin'); - $builder->expects('where')->with(m::type(Closure::class))->andReturnUsing(function (Closure $callback) use ($builder): Builder { + $builder->expects('where')->with(Argument::type(Closure::class))->resolves(function (Closure $callback) use ($builder): Builder { $callback($builder); return $builder; }); $builder->expects('where')->with('closure', 1); - $builder->expects('count')->andReturn(100); + $builder->expects('count')->returns(100); $this->assertSame(100, $verifier->getCount(new PresenceQuery('connection', 'table', 'column', $extra), 'value')); } public function testGetCountWithValidExcludeId(): void { - $db = m::mock(ConnectionResolverInterface::class); + $db = Double::for(ConnectionResolverInterface::class); $verifier = new DatabasePresenceVerifier($db); - $conn = m::mock(Connection::class); - $db->expects('connection')->with('connection')->andReturn($conn); - $builder = m::mock(Builder::class); - $conn->expects('table')->with('table')->andReturn($builder); - $builder->expects('useWritePdo')->andReturn($builder); - $builder->expects('where')->with('column', '=', 'value')->andReturn($builder); - $builder->expects('where')->with('id', '<>', 123)->andReturn($builder); - $builder->expects('count')->andReturn(100); + $conn = Double::for(Connection::class); + $db->expects('connection')->with('connection')->returns($conn); + $builder = Double::for(Builder::class); + $conn->expects('table')->with('table')->returns($builder); + $builder->expects('useWritePdo')->returns($builder); + $builder->expects('where')->with('column', '=', 'value')->returns($builder); + $builder->expects('where')->with('id', '<>', 123)->returns($builder); + $builder->expects('count')->returns(100); $this->assertSame(100, $verifier->getCount(new PresenceQuery('connection', 'table', 'column', new DatabaseConditions, 123, 'id'), 'value')); } public function testIntegersAndBooleansAreComparedAsStrings(): void { - $db = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $db->expects('connection')->with('connection')->times(3)->andReturn($connection); + $db = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $db->expects('connection')->with('connection')->times(3)->returns($connection); $verifier = new DatabasePresenceVerifier($db); - $builder = m::mock(Builder::class); - $connection->expects('table')->with('table')->times(3)->andReturn($builder); - $builder->expects('useWritePdo')->times(3)->andReturnSelf(); - $builder->expects('where')->with('column', '=', '0')->andReturnSelf(); - $builder->expects('count')->withNoArgs()->andReturn(0); + $builder = Double::for(Builder::class); + $connection->expects('table')->with('table')->times(3)->returns($builder); + $builder->expects('useWritePdo')->times(3)->returns($builder); + $builder->expects('where')->with('column', '=', '0')->returns($builder); + $builder->expects('count')->with()->returns(0); $this->assertSame(0, $verifier->getCount(new PresenceQuery('connection', 'table', 'column', new DatabaseConditions), 0)); - $builder->expects('whereIn')->with('column', ['0', '1', '7', 'value'])->twice()->andReturnSelf(); - $builder->expects('distinct')->twice()->andReturnSelf(); - $builder->expects('count')->with('column')->andReturn(0); + $builder->expects('whereIn')->with('column', ['0', '1', '7', 'value'])->times(2)->returns($builder); + $builder->expects('distinct')->times(2)->returns($builder); + $builder->expects('count')->with('column')->returns(0); $this->assertSame(0, $verifier->getMultiCount(new PresenceQuery('connection', 'table', 'column', new DatabaseConditions), [false, true, 7, 'value'])); - $builder->expects('pluck')->with('column')->andReturn(new Collection(['0', '1', '7', 'value'])); + $builder->expects('pluck')->with('column')->returns(new Collection(['0', '1', '7', 'value'])); $verifier->getExistingValues(new PresenceQuery('connection', 'table', 'column', new DatabaseConditions), [false, true, 7, 'value']); } @@ -136,16 +140,16 @@ public function testIntegersAndBooleansAreComparedAsStrings(): void #[DataProvider('connections')] public function testGetExistingValuesUsesRequestedConnectionAndReturnsDistinctValues(?string $connection): void { - $verifier = new DatabasePresenceVerifier($db = m::mock(ConnectionResolverInterface::class)); - $db->expects('connection')->with($connection)->andReturn($database = m::mock(Connection::class)); - $database->expects('table')->with('table')->andReturn($builder = m::mock(Builder::class)); - $builder->expects('useWritePdo')->andReturnSelf(); - $builder->expects('whereIn')->with('column', ['first', 'second'])->andReturnSelf(); - $builder->expects('where')->with('uuid', '<>', 'ignored')->andReturnSelf(); + $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)); + $builder->expects('useWritePdo')->returns($builder); + $builder->expects('whereIn')->with('column', ['first', 'second'])->returns($builder); + $builder->expects('where')->with('uuid', '<>', 'ignored')->returns($builder); $builder->expects('whereNull')->with('deleted_at'); $builder->expects('where')->with('status', '=', 'active'); - $builder->expects('distinct')->andReturnSelf(); - $builder->expects('pluck')->with('column')->andReturn(new Collection(['first'])); + $builder->expects('distinct')->returns($builder); + $builder->expects('pluck')->with('column')->returns(new Collection(['first'])); $this->assertSame(['first'], $verifier->getExistingValues( new PresenceQuery($connection, 'table', 'column', new DatabaseConditions( @@ -166,7 +170,7 @@ public static function connections(): array public function testNestedValidationCannotChangeTheOuterConnection(): void { - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $verifier = new DatabasePresenceVerifier($resolver); $translator = new Translator(new ArrayLoader, 'en'); $inner = new Validator($translator, ['email' => 'inner@example.com'], [ @@ -198,13 +202,13 @@ public function queryConditions(): DatabaseConditions $outer->setPresenceVerifier($verifier); foreach (['inner' => 1, 'outer' => 0] as $name => $count) { - $connection = m::mock(Connection::class); - $builder = m::mock(Builder::class); - $resolver->expects('connection')->with($name)->andReturn($connection); - $connection->expects('table')->with('users')->andReturn($builder); - $builder->expects('useWritePdo')->andReturnSelf(); - $builder->expects('where')->with('email', '=', $name . '@example.com')->andReturnSelf(); - $builder->expects('count')->andReturn($count); + $connection = Double::for(Connection::class); + $builder = Double::for(Builder::class); + $resolver->expects('connection')->with($name)->returns($connection); + $connection->expects('table')->with('users')->returns($builder); + $builder->expects('useWritePdo')->returns($builder); + $builder->expects('where')->with('email', '=', $name . '@example.com')->returns($builder); + $builder->expects('count')->returns($count); } $this->assertFalse($outer->passes()); diff --git a/tests/Validation/ValidationValidatorTest.php b/tests/Validation/ValidationValidatorTest.php index 578a4a764..454badf35 100755 --- a/tests/Validation/ValidationValidatorTest.php +++ b/tests/Validation/ValidationValidatorTest.php @@ -46,8 +46,11 @@ use Hypervel\Validation\ValidationException; use Hypervel\Validation\Validator; use InvalidArgumentException; -use Mockery as m; -use Mockery\Matcher\Closure as ClosureMatcher; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use JMac\Testing\Matching\Matcher; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresPhpExtension; use PHPUnit\Framework\Attributes\TestWith; @@ -62,6 +65,8 @@ class ValidationValidatorTest extends TestCase { + use VerifiesDoubles; + private string $originalTimezone; protected function setUp(): void @@ -242,7 +247,7 @@ public function testAfterCallbacksAreCalledWithValidatorInstance(): void { $trans = $this->getArrayTranslator(); $v = new Validator($trans, ['foo' => 'bar', 'baz' => 'boom'], ['foo' => 'Same:baz']); - $v->setContainer(m::mock(ContainerContract::class)); + $v->setContainer(new Container); $v->after(function ($validator) { $_SERVER['__validator.after.test'] = true; @@ -345,7 +350,7 @@ public function testFailingOnce(): void public function testHasNotFailedValidationRules(): void { $trans = $this->getTranslator(); - $trans->shouldReceive('get')->never(); + $trans->expects('get')->never(); $v = new Validator($trans, ['foo' => 'taylor'], ['name' => 'Confirmed']); $this->assertTrue($v->passes()); $this->assertEmpty($v->failed()); @@ -354,7 +359,7 @@ public function testHasNotFailedValidationRules(): void public function testSometimesCanSkipRequiredRules(): void { $trans = $this->getTranslator(); - $trans->shouldReceive('get')->never(); + $trans->expects('get')->never(); $v = new Validator($trans, [], ['name' => 'sometimes|required']); $this->assertTrue($v->passes()); $this->assertEmpty($v->failed()); @@ -363,7 +368,7 @@ public function testSometimesCanSkipRequiredRules(): void public function testInValidatableRulesReturnsValid(): void { $trans = $this->getTranslator(); - $trans->shouldReceive('get')->never(); + $trans->expects('get')->never(); $v = new Validator($trans, ['foo' => 'taylor'], ['name' => 'Confirmed']); $this->assertTrue($v->passes()); } @@ -1576,99 +1581,99 @@ public function testArrayValidationAcceptsLiteralKeysWhenCalledDirectly(): void public function testValidateCurrentPassword(): void { // Fails when user is not logged in. - $guard = m::mock(Guard::class); - $guard->expects('guest')->andReturn(true); - $auth = m::mock(AuthFactory::class); - $auth->expects('guard')->andReturn($guard); + $guard = Double::for(Guard::class); + $guard->expects('guest')->returns(true); + $auth = Double::for(AuthFactory::class); + $auth->expects('guard')->returns($guard); - $hasher = m::mock(Hasher::class); + $hasher = Double::for(Hasher::class); - $container = m::mock(ContainerContract::class); - $container->expects('make')->with('auth')->andReturn($auth); - $container->expects('make')->with('hash')->andReturn($hasher); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('make')->with('auth')->returns($auth); + $container->expects('make')->with('hash')->returns($hasher); $trans = $this->getTranslator(); - $trans->shouldReceive('get')->andReturnArg(0); - $trans->shouldReceive('string')->andReturnArg(0); + $trans->allows('get')->resolves(static fn (string $key): string => $key); + $trans->allows('string')->resolves(static fn (string $key): string => $key); $v = new Validator($trans, ['password' => 'foo'], ['password' => 'current_password']); - $v->setContainer($container); + $v->setContainer($container->instance()); $this->assertFalse($v->passes()); // Fails when password is incorrect. - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $user->expects('getAuthPassword'); - $guard = m::mock(Guard::class); - $guard->expects('guest')->andReturn(false); - $guard->expects('user')->andReturn($user); - $auth = m::mock(AuthFactory::class); - $auth->expects('guard')->andReturn($guard); + $guard = Double::for(Guard::class); + $guard->expects('guest')->returns(false); + $guard->expects('user')->returns($user); + $auth = Double::for(AuthFactory::class); + $auth->expects('guard')->returns($guard); - $hasher = m::mock(Hasher::class); - $hasher->expects('check')->andReturn(false); + $hasher = Double::for(Hasher::class); + $hasher->expects('check')->returns(false); - $container = m::mock(ContainerContract::class); - $container->expects('make')->with('auth')->andReturn($auth); - $container->expects('make')->with('hash')->andReturn($hasher); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('make')->with('auth')->returns($auth); + $container->expects('make')->with('hash')->returns($hasher); $trans = $this->getTranslator(); - $trans->shouldReceive('get')->andReturnArg(0); - $trans->shouldReceive('string')->andReturnArg(0); + $trans->allows('get')->resolves(static fn (string $key): string => $key); + $trans->allows('string')->resolves(static fn (string $key): string => $key); $v = new Validator($trans, ['password' => 'foo'], ['password' => 'current_password']); - $v->setContainer($container); + $v->setContainer($container->instance()); $this->assertFalse($v->passes()); // Succeeds when password is correct. - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $user->expects('getAuthPassword'); - $guard = m::mock(Guard::class); - $guard->expects('guest')->andReturn(false); - $guard->expects('user')->andReturn($user); - $auth = m::mock(AuthFactory::class); - $auth->expects('guard')->andReturn($guard); + $guard = Double::for(Guard::class); + $guard->expects('guest')->returns(false); + $guard->expects('user')->returns($user); + $auth = Double::for(AuthFactory::class); + $auth->expects('guard')->returns($guard); - $hasher = m::mock(Hasher::class); - $hasher->expects('check')->andReturn(true); + $hasher = Double::for(Hasher::class); + $hasher->expects('check')->returns(true); - $container = m::mock(ContainerContract::class); - $container->expects('make')->with('auth')->andReturn($auth); - $container->expects('make')->with('hash')->andReturn($hasher); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('make')->with('auth')->returns($auth); + $container->expects('make')->with('hash')->returns($hasher); $trans = $this->getTranslator(); - $trans->shouldReceive('get')->andReturnArg(0); + $trans->allows('get')->resolves(static fn (string $key): string => $key); $v = new Validator($trans, ['password' => 'foo'], ['password' => 'current_password']); - $v->setContainer($container); + $v->setContainer($container->instance()); $this->assertTrue($v->passes()); // We can use a specific guard. - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $user->expects('getAuthPassword'); - $guard = m::mock(Guard::class); - $guard->expects('guest')->andReturn(false); - $guard->expects('user')->andReturn($user); - $auth = m::mock(AuthFactory::class); - $auth->expects('guard')->with('custom')->andReturn($guard); + $guard = Double::for(Guard::class); + $guard->expects('guest')->returns(false); + $guard->expects('user')->returns($user); + $auth = Double::for(AuthFactory::class); + $auth->expects('guard')->with('custom')->returns($guard); - $hasher = m::mock(Hasher::class); - $hasher->expects('check')->andReturn(true); + $hasher = Double::for(Hasher::class); + $hasher->expects('check')->returns(true); - $container = m::mock(ContainerContract::class); - $container->expects('make')->with('auth')->andReturn($auth); - $container->expects('make')->with('hash')->andReturn($hasher); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('make')->with('auth')->returns($auth); + $container->expects('make')->with('hash')->returns($hasher); $trans = $this->getTranslator(); - $trans->shouldReceive('get')->andReturnArg(0); + $trans->allows('get')->resolves(static fn (string $key): string => $key); $v = new Validator($trans, ['password' => 'foo'], ['password' => 'current_password:custom']); - $v->setContainer($container); + $v->setContainer($container->instance()); $this->assertTrue($v->passes()); } @@ -2570,31 +2575,31 @@ 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 = m::mock($fileClass); - $file->expects('isValid')->andReturn(false); - $file->shouldNotReceive('getSize'); + $file = Double::for($fileClass); + $file->expects('isValid')->returns(false); + $file->expects('getSize')->never(); $v = new Validator($trans, ['photo' => $file], ['photo' => 'Max:10']); $this->assertTrue($v->fails()); $this->assertEquals(['validation.uploaded'], $v->errors()->get('photo')); // Even "required" will not run if the file failed to upload. - $file = m::mock($fileClass); - $file->expects('isValid')->andReturn(false); + $file = Double::for($fileClass); + $file->expects('isValid')->returns(false); $v = new Validator($trans, ['photo' => $file], ['photo' => 'required']); $this->assertTrue($v->fails()); $this->assertEquals(['validation.uploaded'], $v->errors()->get('photo')); // 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 = m::mock($fileClass); - $file->expects('isValid')->andReturn(false); + $file = Double::for($fileClass); + $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 = m::mock($fileClass); - $file->expects('isValid')->andReturn(false); + $file = Double::for($fileClass); + $file->expects('isValid')->returns(false); $v = new Validator($trans, ['photo' => $file], ['photo' => 'file|mimes:pdf|min:10']); $this->assertTrue($v->fails()); $this->assertEquals(['validation.uploaded'], $v->errors()->get('photo')); @@ -2604,9 +2609,9 @@ public function testFailedFileUploads(string $fileClass): void #[TestWith([SymfonyUploadedFile::class])] public function testDirectFileRulesRejectFailedUploads(string $fileClass): void { - $file = m::mock($fileClass); - $file->expects('isValid')->twice()->andReturn(false); - $file->shouldNotReceive('getSize'); + $file = Double::for($fileClass); + $file->expects('isValid')->times(2)->returns(false); + $file->expects('getSize')->never(); $validator = new Validator($this->getArrayTranslator(), [], []); $this->assertFalse($validator->isValidFileInstance($file)); @@ -5077,37 +5082,37 @@ public function testValidateUnique(): void { $trans = $this->getArrayTranslator(); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users']); - $mock = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email', new DatabaseConditions)), 'foo')->andReturn(0); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery('connection', 'users', 'email', new DatabaseConditions)), 'foo')->andReturn(0); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions, '1', 'id')), 'foo')->andReturn(1); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions, '1', 'id_col')), 'foo')->andReturn(2); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email', new DatabaseConditions, '1', 'id')), 'foo')->andReturn(1); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); + $mock = Double::for(PresenceVerifierInterface::class); $mock->expects('getCount')->with( $this->matchingPresenceQuery(new PresenceQuery( null, @@ -5118,7 +5123,7 @@ public function testValidateUnique(): void 'id_col' )), 'foo', - )->andReturn(2); + )->returns(2); $v->setPresenceVerifier($mock); $this->assertFalse($v->passes()); } @@ -5132,7 +5137,7 @@ public function testValidateUniquePreservesNullAndZeroIgnoredIds(): void ['email' => 'foo'], ['email' => [$rule]], ); - $verifier = m::mock(PresenceVerifierInterface::class); + $verifier = Double::for(PresenceVerifierInterface::class); $verifier->expects('getCount') ->with($this->matchingPresenceQuery(new PresenceQuery( null, @@ -5142,7 +5147,7 @@ public function testValidateUniquePreservesNullAndZeroIgnoredIds(): void $ignoredId === null ? null : '0', 'id', )), 'foo') - ->andReturn(0); + ->returns(0); $validator->setPresenceVerifier($verifier); $this->assertTrue($validator->passes()); @@ -5156,9 +5161,9 @@ public function testValidateUniqueAndExistsSendsCorrectFieldNameToDBWithArrays() $v = new Validator($trans, [['email' => 'foo', 'type' => 'bar']], [ '*.email' => 'unique:users', '*.type' => 'exists:user_types', ]); - $mock = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email', new DatabaseConditions)), 'foo')->andReturn(0); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'user_types', 'type', new DatabaseConditions)), 'bar')->andReturn(1); + $mock = Double::for(PresenceVerifierInterface::class); + $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); $this->assertTrue($v->passes()); @@ -5169,13 +5174,13 @@ public function testValidateUniqueAndExistsSendsCorrectFieldNameToDBWithArrays() '*.email' => (new Unique('users'))->where($closure), '*.type' => (new Exists('user_types'))->where($closure), ]); - $mock = m::mock(PresenceVerifierInterface::class); + $mock = Double::for(PresenceVerifierInterface::class); $mock->expects('getCount')->with($this->matchingPresenceQuery( new PresenceQuery(null, 'users', 'email', new DatabaseConditions($closure), null, 'id'), - ), 'foo')->andReturn(0); + ), 'foo')->returns(0); $mock->expects('getCount')->with($this->matchingPresenceQuery( new PresenceQuery(null, 'user_types', 'type', new DatabaseConditions($closure)), - ), 'bar')->andReturn(1); + ), 'bar')->returns(1); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); } @@ -5184,39 +5189,39 @@ public function testValidationExists(): void { $trans = $this->getArrayTranslator(); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:users']); - $mock = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email', new DatabaseConditions)), 'foo')->andReturn(1); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $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')->andReturn(1); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions)), 'foo')->andReturn(0); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $mock->expects('getMultiCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions)), ['foo'])->andReturn(0); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery('connection', 'users', 'email', new DatabaseConditions)), 'foo')->andReturn(1); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $mock->expects('getMultiCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions)), ['foo', 'foo'])->andReturn(1); + $mock = Double::for(PresenceVerifierInterface::class); + $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()); @@ -5235,10 +5240,10 @@ 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 = m::mock(PresenceVerifierInterface::class); + $verifier = Double::for(PresenceVerifierInterface::class); $verifier->expects('getMultiCount') ->with($this->matchingPresenceQuery(new PresenceQuery(null, 'records', $column, new DatabaseConditions)), $values) - ->andReturn(1); + ->returns(1); $validator->setPresenceVerifier($verifier); $this->assertSame($passes, $validator->passes()); @@ -5249,15 +5254,15 @@ public function testValidationExistsIsNotCalledUnnecessarily(): void { $trans = $this->getArrayTranslator(); $v = new Validator($trans, ['id' => 'foo'], ['id' => 'Integer|Exists:users,id']); - $mock = m::mock(PresenceVerifierInterface::class); - $mock->shouldReceive('getCount')->never(); + $mock = Double::for(PresenceVerifierInterface::class); + $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 = m::mock(PresenceVerifierInterface::class); - $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'id', new DatabaseConditions)), '1')->andReturn(1); + $mock = Double::for(PresenceVerifierInterface::class); + $mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'id', new DatabaseConditions)), '1')->returns(1); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); } @@ -6162,8 +6167,9 @@ public function testValidateImageDimensions(): void $v = new Validator($trans, ['x' => $svgUploadedFile], ['x' => 'dimensions:max_width=1,max_height=1']); $this->assertTrue($v->passes()); - $svgFile = m::mock(File::class, [__DIR__ . '/Fixtures/image2.svg'])->makePartial(); - $svgFile->expects('getMimeType')->andReturn('image/svg'); + $svgFile = Double::for(File::class)->passthru(); + $svgFile->__construct(__DIR__ . '/Fixtures/image2.svg'); + $svgFile->expects('getMimeType')->returns('image/svg'); $trans = $this->getArrayTranslator(); $v = new Validator($trans, ['x' => $svgFile], ['x' => 'dimensions:max_width=1,max_height=1']); @@ -8685,10 +8691,11 @@ public function testCustomReplacersReceiveDecodedFieldPaths(bool $classBased): v }; if ($classBased) { - $validator->setContainer($container = m::mock(ContainerContract::class)); - $replacer = m::mock(stdClass::class); - $container->expects('make')->with('LiteralFieldReplacer')->andReturn($replacer); - $replacer->expects('replace')->andReturnUsing($callback); + $container = Double::for(ContainerContract::class, override: true); + $validator->setContainer($container->instance()); + $replacer = Double::for(ClassBasedValidatorStub::class); + $container->expects('make')->with('LiteralFieldReplacer')->returns($replacer); + $replacer->expects('replace')->resolves($callback); $validator->addReplacer('accepted_if', 'LiteralFieldReplacer'); } else { $validator->addReplacer('accepted_if', $callback); @@ -11553,24 +11560,25 @@ protected function uploadedFile( ); } - protected function getTranslator() + /** + * Create a translator double. + */ + protected function getTranslator(): TranslatorContract&DoubleInterface { - return m::mock(TranslatorContract::class); + return Double::for(TranslatorContract::class); } /** * Match a presence query without coercing native values or callback identities. */ - private function matchingPresenceQuery(PresenceQuery $expected): ClosureMatcher + private function matchingPresenceQuery(PresenceQuery $expected): Matcher { - return m::on(static function (PresenceQuery $actual) use ($expected): bool { + return Argument::satisfies(static function (PresenceQuery $actual) use ($expected): bool { $expectedValues = get_object_vars($expected); $expectedValues['conditions'] = $expected->conditions->toArray(); $actualValues = get_object_vars($actual); $actualValues['conditions'] = $actual->conditions->toArray(); - self::assertSame($expectedValues, $actualValues); - - return true; + return $expectedValues === $actualValues; }); } diff --git a/tests/View/Blade/AbstractBladeTestCase.php b/tests/View/Blade/AbstractBladeTestCase.php index ffd029adb..f97f9e5cb 100644 --- a/tests/View/Blade/AbstractBladeTestCase.php +++ b/tests/View/Blade/AbstractBladeTestCase.php @@ -7,10 +7,13 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Tests\TestCase; use Hypervel\View\Compilers\BladeCompiler; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; abstract class AbstractBladeTestCase extends TestCase { + use VerifiesDoubles; + protected BladeCompiler $compiler; protected function setUp(): void @@ -20,8 +23,11 @@ protected function setUp(): void $this->compiler = new BladeCompiler($this->getFiles(), __DIR__); } + /** + * Create the compiler's filesystem double. + */ protected function getFiles(): Filesystem { - return m::mock(Filesystem::class); + return Double::for(Filesystem::class); } } diff --git a/tests/View/Blade/BladeComponentTagCompilerTest.php b/tests/View/Blade/BladeComponentTagCompilerTest.php index 26f7b0b47..270d852da 100644 --- a/tests/View/Blade/BladeComponentTagCompilerTest.php +++ b/tests/View/Blade/BladeComponentTagCompilerTest.php @@ -20,7 +20,7 @@ use Hypervel\View\ComponentAttributeBag; use Hypervel\View\Factory as ViewFactory; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; use Stringable; class BladeComponentTagCompilerTest extends AbstractBladeTestCase @@ -167,11 +167,11 @@ public function testBasicComponentParsing(): void public function testNestedDefaultComponentParsing(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); + $app->expects('getNamespace')->returns('App\\'); Container::setInstance($container); $result = $this->compiler()->compileTags('
'); @@ -428,9 +428,9 @@ public function testClassesCanBeFoundByComponents(): void public function testClassNamesCanBeGuessed(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $app->expects('getNamespace')->andReturn('App\\'); - $container->instance(ApplicationContract::class, $app); + $app = Double::for(ApplicationContract::class, override: true); + $app->expects('getNamespace')->returns('App\\'); + $container->instance(ApplicationContract::class, $app->instance()); Container::setInstance($container); $result = $this->compiler()->guessClassName('alert'); @@ -441,9 +441,9 @@ public function testClassNamesCanBeGuessed(): void public function testClassNamesCanBeGuessedWithNamespaces(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $app->expects('getNamespace')->andReturn('App\\'); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $app->expects('getNamespace')->returns('App\\'); Container::setInstance($container); $result = $this->compiler()->guessClassName('base.alert'); @@ -560,12 +560,12 @@ public function testPairedComponentTags(): void public function testClasslessComponents(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->andReturn(true); + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->returns(true); Container::setInstance($container); $result = $this->compiler()->compileTags(''); @@ -581,12 +581,12 @@ public function testClasslessComponents(): void public function testClasslessComponentsWithIndexView(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->twice()->andReturn(false, true); + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->times(2)->returns(false, true); Container::setInstance($container); $result = $this->compiler()->compileTags(''); @@ -602,12 +602,12 @@ public function testClasslessComponentsWithIndexView(): void public function testClasslessComponentsWithComponentView(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->times(3)->andReturn(false, false, true); + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->times(3)->returns(false, false, true); Container::setInstance($container); $result = $this->compiler()->compileTags(''); @@ -623,12 +623,12 @@ public function testClasslessComponentsWithComponentView(): void public function testPackagesClasslessComponents(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->andReturn(true); + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->returns(true); Container::setInstance($container); $result = $this->compiler()->compileTags(''); @@ -644,21 +644,21 @@ public function testPackagesClasslessComponents(): void public function testClasslessComponentsWithAnonymousComponentNamespace(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->times(4)->andReturnUsing(function (string $arg): bool { + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->times(4)->resolves(function (string $arg): bool { // In our test, we'll do as if the 'public.frontend.anonymous-component' // view exists and not the others. return $arg === 'public.frontend.anonymous-component'; }); Container::setInstance($container); - $blade = m::mock(BladeCompiler::class)->makePartial(); + $blade = Double::for(BladeCompiler::class)->passthru(); - $blade->expects('getAnonymousComponentNamespaces')->andReturn([ + $blade->expects('getAnonymousComponentNamespaces')->returns([ 'frontend' => 'public.frontend', ]); @@ -677,21 +677,21 @@ public function testClasslessComponentsWithAnonymousComponentNamespace(): void public function testClasslessComponentsWithAnonymousComponentNamespaceWithIndexView(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->times(5)->andReturnUsing(function (string $viewNameBeingCheckedForExistence): bool { + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->times(5)->resolves(function (string $viewNameBeingCheckedForExistence): bool { // In our test, we'll do as if the 'admin.auth.components.anonymous-component.index' // view exists and not the others. return $viewNameBeingCheckedForExistence === 'admin.auth.components.anonymous-component.index'; }); Container::setInstance($container); - $blade = m::mock(BladeCompiler::class)->makePartial(); + $blade = Double::for(BladeCompiler::class)->passthru(); - $blade->expects('getAnonymousComponentNamespaces')->andReturn([ + $blade->expects('getAnonymousComponentNamespaces')->returns([ 'admin.auth' => 'admin.auth.components', ]); @@ -710,21 +710,21 @@ public function testClasslessComponentsWithAnonymousComponentNamespaceWithIndexV public function testClasslessComponentsWithAnonymousComponentNamespaceWithComponentView(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->times(6)->andReturnUsing(function (string $viewNameBeingCheckedForExistence): bool { + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->times(6)->resolves(function (string $viewNameBeingCheckedForExistence): bool { // In our test, we'll do as if the 'admin.auth.components.anonymous-component.anonymous-component' // view exists and not the others. return $viewNameBeingCheckedForExistence === 'admin.auth.components.anonymous-component.anonymous-component'; }); Container::setInstance($container); - $blade = m::mock(BladeCompiler::class)->makePartial(); + $blade = Double::for(BladeCompiler::class)->passthru(); - $blade->expects('getAnonymousComponentNamespaces')->andReturn([ + $blade->expects('getAnonymousComponentNamespaces')->returns([ 'admin.auth' => 'admin.auth.components', ]); @@ -743,19 +743,19 @@ public function testClasslessComponentsWithAnonymousComponentNamespaceWithCompon public function testClasslessComponentsWithAnonymousComponentPath(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->times(5)->andReturnUsing(function (string $arg): bool { + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->times(5)->resolves(function (string $arg): bool { return $arg === hash('xxh128', 'test-directory') . '::panel.index'; }); Container::setInstance($container); - $blade = m::mock(BladeCompiler::class)->makePartial(); + $blade = Double::for(BladeCompiler::class)->passthru(); - $blade->expects('getAnonymousComponentPaths')->andReturn([ + $blade->expects('getAnonymousComponentPaths')->returns([ ['path' => 'test-directory', 'prefix' => null, 'prefixHash' => hash('xxh128', 'test-directory')], ]); @@ -774,8 +774,8 @@ public function testClasslessComponentsWithAnonymousComponentPath(): void public function testAnonymousComponentPathGeneratesXxh128PrefixHash(): void { $expectedHash = hash('xxh128', 'test-directory'); - $factory = m::mock(Factory::class); - $factory->expects('addNamespace')->with($expectedHash, 'test-directory')->andReturnSelf(); + $factory = Double::for(Factory::class); + $factory->expects('addNamespace')->with($expectedHash, 'test-directory')->returns($factory); $container = new TestBladeApplication('base_path'); $container->instance(Factory::class, $factory); @@ -797,19 +797,19 @@ public function testAnonymousComponentPathGeneratesXxh128PrefixHash(): void public function testClasslessComponentsWithAnonymousComponentPathComponentName(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->times(6)->andReturnUsing(function (string $arg): bool { + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->times(6)->resolves(function (string $arg): bool { return $arg === hash('xxh128', 'test-directory') . '::panel.panel'; }); Container::setInstance($container); - $blade = m::mock(BladeCompiler::class)->makePartial(); + $blade = Double::for(BladeCompiler::class)->passthru(); - $blade->expects('getAnonymousComponentPaths')->andReturn([ + $blade->expects('getAnonymousComponentPaths')->returns([ ['path' => 'test-directory', 'prefix' => null, 'prefixHash' => hash('xxh128', 'test-directory')], ]); @@ -828,19 +828,19 @@ public function testClasslessComponentsWithAnonymousComponentPathComponentName() public function testClasslessIndexComponentsWithAnonymousComponentPath(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->times(4)->andReturnUsing(function (string $arg): bool { + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->times(4)->resolves(function (string $arg): bool { return $arg === hash('xxh128', 'test-directory') . '::panel'; }); Container::setInstance($container); - $blade = m::mock(BladeCompiler::class)->makePartial(); + $blade = Double::for(BladeCompiler::class)->passthru(); - $blade->expects('getAnonymousComponentPaths')->andReturn([ + $blade->expects('getAnonymousComponentPaths')->returns([ ['path' => 'test-directory', 'prefix' => null, 'prefixHash' => hash('xxh128', 'test-directory')], ]); @@ -895,12 +895,12 @@ public function testItThrowsAnExceptionForNonExistingAliases(): void public function testItThrowsAnExceptionForNonExistingClass(): void { $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $factory = m::mock(Factory::class); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); - $app->expects('getNamespace')->andReturn('App\\'); - $factory->expects('exists')->times(3)->andReturn(false); + $app->expects('getNamespace')->returns('App\\'); + $factory->expects('exists')->times(3)->returns(false); Container::setInstance($container); $this->expectException(InvalidArgumentException::class); @@ -910,13 +910,13 @@ public function testItThrowsAnExceptionForNonExistingClass(): void public function testAttributesTreatedAsPropsAreRemovedFromFinalAttributes(): void { - $factory = m::mock(Factory::class); - $factory->shouldReceive('exists')->never(); + $factory = Double::for(Factory::class); + $factory->expects('exists')->never(); $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $app->shouldNotReceive('getNamespace'); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $app->expects('getNamespace')->never(); $container->instance(Factory::class, $factory); $container->alias(Factory::class, 'view'); @@ -924,16 +924,16 @@ public function testAttributesTreatedAsPropsAreRemovedFromFinalAttributes(): voi $attributes = new ComponentAttributeBag(['userId' => 'bar', 'other' => 'ok']); - $component = m::mock(TestProfileComponent::class); - $component->expects('withName')->with('profile')->andReturnSelf(); - $component->expects('shouldRender')->andReturn(true); - $component->expects('resolveView')->andReturn(''); - $component->expects('data')->andReturn([]); - $component->expects('withAttributes')->with(['attributes' => new ComponentAttributeBag(['other' => 'ok'])])->andReturnSelf(); + $component = Double::for(TestProfileComponent::class); + $component->expects('withName')->with('profile')->returns($component); + $component->expects('shouldRender')->returns(true); + $component->expects('resolveView')->returns(''); + $component->expects('data')->returns([]); + $component->expects('withAttributes')->with(['attributes' => new ComponentAttributeBag(['other' => 'ok'])])->returns($component); Component::resolveComponentsUsing(fn () => $component); - $__env = m::mock(ViewFactory::class); + $__env = Double::for(ViewFactory::class); $__env->expects('startComponent'); $__env->expects('renderComponent'); @@ -950,13 +950,13 @@ public function testAttributesTreatedAsPropsAreRemovedFromFinalAttributes(): voi public function testOriginalAttributesAreRestoredAfterRenderingChildComponentWithProps(): void { - $factory = m::mock(Factory::class); - $factory->shouldReceive('exists')->never(); + $factory = Double::for(Factory::class); + $factory->expects('exists')->never(); $container = new Container; - $app = m::mock(ApplicationContract::class); - $container->instance(ApplicationContract::class, $app); - $app->shouldNotReceive('getNamespace'); + $app = Double::for(ApplicationContract::class, override: true); + $container->instance(ApplicationContract::class, $app->instance()); + $app->expects('getNamespace')->never(); $container->instance(Factory::class, $factory); $container->alias(Factory::class, 'view'); @@ -964,28 +964,28 @@ public function testOriginalAttributesAreRestoredAfterRenderingChildComponentWit $attributes = new ComponentAttributeBag(['userId' => 'bar', 'other' => 'ok']); - $containerComponent = m::mock(TestContainerComponent::class); - $containerComponent->expects('withName')->with('container')->andReturnSelf(); - $containerComponent->expects('shouldRender')->andReturn(true); - $containerComponent->expects('resolveView')->andReturn(''); - $containerComponent->expects('data')->andReturn([]); - $containerComponent->expects('withAttributes')->andReturnSelf(); + $containerComponent = Double::for(TestContainerComponent::class); + $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 = m::mock(TestProfileComponent::class); - $profileComponent->expects('withName')->with('profile')->andReturnSelf(); - $profileComponent->expects('shouldRender')->andReturn(true); - $profileComponent->expects('resolveView')->andReturn(''); - $profileComponent->expects('data')->andReturn([]); - $profileComponent->expects('withAttributes')->with(['attributes' => new ComponentAttributeBag(['other' => 'ok'])])->andReturnSelf(); + $profileComponent = Double::for(TestProfileComponent::class); + $profileComponent->expects('withName')->with('profile')->returns($profileComponent); + $profileComponent->expects('shouldRender')->returns(true); + $profileComponent->expects('resolveView')->returns(''); + $profileComponent->expects('data')->returns([]); + $profileComponent->expects('withAttributes')->with(['attributes' => new ComponentAttributeBag(['other' => 'ok'])])->returns($profileComponent); Component::resolveComponentsUsing(fn ($component) => match ($component) { TestContainerComponent::class => $containerComponent, TestProfileComponent::class => $profileComponent, }); - $__env = m::mock(ViewFactory::class); - $__env->expects('startComponent')->twice(); - $__env->expects('renderComponent')->twice(); + $__env = Double::for(ViewFactory::class); + $__env->expects('startComponent')->times(2); + $__env->expects('renderComponent')->times(2); $template = $this->compiler([ 'container' => TestContainerComponent::class, @@ -1007,10 +1007,10 @@ public function testOriginalAttributesAreRestoredAfterRenderingChildComponentWit protected function mockViewFactory(bool $existsSucceeds = true): void { $container = new Container; - $factory = m::mock(Factory::class); + $factory = Double::for(Factory::class); $container->instance(Factory::class, $factory); $container->alias(Factory::class, 'view'); - $factory->shouldReceive('exists')->andReturn($existsSucceeds); + $factory->allows('exists')->returns($existsSucceeds); Container::setInstance($container); } diff --git a/tests/View/Blade/BladeComponentsTest.php b/tests/View/Blade/BladeComponentsTest.php index 8b06c5cb8..79bd5bdfc 100644 --- a/tests/View/Blade/BladeComponentsTest.php +++ b/tests/View/Blade/BladeComponentsTest.php @@ -11,7 +11,6 @@ use Hypervel\View\Compilers\BladeCompiler; use Hypervel\View\Component; use Hypervel\View\ComponentAttributeBag; -use Mockery as m; use ReflectionClassConstant; use RuntimeException; @@ -94,9 +93,7 @@ public function testPropsAreExtractedFromParentAttributesCorrectlyForClassCompon { $attributes = new ComponentAttributeBag(['foo' => 'baz', 'other' => 'ok']); - $component = m::mock(ComponentStub::class); - $component->expects('withName')->with('test')->andReturnSelf(); - $component->expects('shouldRender')->andReturn(false); + $component = new BladeComponentsTestComponent; $resolvedData = null; Component::resolveComponentsUsing(function (string $componentClass, array $data) use ($component, &$resolvedData): Component { @@ -112,6 +109,7 @@ public function testPropsAreExtractedFromParentAttributesCorrectlyForClassCompon $this->assertSame('', trim((string) ob_get_clean())); $this->assertSame(['foo' => 'bar', 'other' => 'ok'], $resolvedData); + $this->assertSame('test', $component->componentName); } private function expectedEndComponentClass(): string @@ -136,3 +134,14 @@ public function render(): ViewContract|Htmlable|Closure|string return ''; } } + +class BladeComponentsTestComponent extends ComponentStub +{ + /** + * Determine whether the component should be rendered. + */ + public function shouldRender(): bool + { + return false; + } +} diff --git a/tests/View/ComponentTest.php b/tests/View/ComponentTest.php index a6fc18e91..48a38e154 100644 --- a/tests/View/ComponentTest.php +++ b/tests/View/ComponentTest.php @@ -19,13 +19,17 @@ use Hypervel\View\ComponentSlot; use Hypervel\View\Factory; use Hypervel\View\View; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ComponentTest extends TestCase { - protected Factory $viewFactory; + use VerifiesDoubles; - protected Config $config; + protected Factory&DoubleInterface $viewFactory; + + protected Config&DoubleInterface $config; protected Filesystem $filesystem; @@ -35,8 +39,8 @@ protected function setUp(): void { parent::setUp(); - $this->viewFactory = m::mock(Factory::class); - $this->config = m::mock(Config::class); + $this->viewFactory = Double::for(Factory::class); + $this->config = Double::for(Config::class); $this->filesystem = new Filesystem; $this->compiledPath = ParallelTesting::tempDir('ViewComponentTest'); $this->filesystem->deleteDirectory($this->compiledPath); @@ -60,9 +64,9 @@ protected function tearDown(): void public function testInlineViewsGetCreated(): void { - $this->config->expects('string')->with('view.compiled')->andReturn($this->compiledPath); - $this->viewFactory->expects('exists')->andReturn(false); - $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->andReturnSelf(); + $this->config->expects('string')->with('view.compiled')->returns($this->compiledPath); + $this->viewFactory->expects('exists')->returns(false); + $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->returns($this->viewFactory); $component = new TestInlineViewComponent; $this->assertSame('__components::57b7a54afa0eb51fd9b88eec031c9e9e', $component->resolveView()); @@ -72,17 +76,17 @@ public function testInlineViewsUseAtomicFilesystemPublication(): void { $contents = 'Atomically published'; $viewFile = $this->compiledPath . '/' . hash('xxh128', $contents) . '.blade.php'; - $filesystem = m::mock(Filesystem::class); + $filesystem = Double::for(Filesystem::class); - $filesystem->expects('exists')->with($viewFile)->andReturn(false); + $filesystem->expects('exists')->with($viewFile)->returns(false); $filesystem->expects('ensureDirectoryExists')->with($this->compiledPath); $filesystem->expects('replace')->with($viewFile, $contents); Container::getInstance()->instance(Filesystem::class, $filesystem); - $this->config->expects('string')->with('view.compiled')->andReturn($this->compiledPath); - $this->viewFactory->expects('exists')->with($contents)->andReturn(false); - $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->andReturnSelf(); + $this->config->expects('string')->with('view.compiled')->returns($this->compiledPath); + $this->viewFactory->expects('exists')->with($contents)->returns(false); + $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->returns($this->viewFactory); $component = new TestAtomicallyPublishedInlineViewComponent; @@ -93,18 +97,18 @@ public function testCompleteInlineViewsAreNotRepublished(): void { $contents = 'Already published'; $viewFile = $this->compiledPath . '/' . hash('xxh128', $contents) . '.blade.php'; - $filesystem = m::mock(Filesystem::class); + $filesystem = Double::for(Filesystem::class); - $filesystem->expects('exists')->with($viewFile)->andReturn(true); - $filesystem->expects('size')->with($viewFile)->andReturn(strlen($contents)); - $filesystem->shouldReceive('ensureDirectoryExists')->never(); - $filesystem->shouldReceive('replace')->never(); + $filesystem->expects('exists')->with($viewFile)->returns(true); + $filesystem->expects('size')->with($viewFile)->returns(strlen($contents)); + $filesystem->expects('ensureDirectoryExists')->never(); + $filesystem->expects('replace')->never(); Container::getInstance()->instance(Filesystem::class, $filesystem); - $this->config->expects('string')->with('view.compiled')->andReturn($this->compiledPath); - $this->viewFactory->expects('exists')->with($contents)->andReturn(false); - $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->andReturnSelf(); + $this->config->expects('string')->with('view.compiled')->returns($this->compiledPath); + $this->viewFactory->expects('exists')->with($contents)->returns(false); + $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->returns($this->viewFactory); $component = new TestCompleteInlineViewComponent; @@ -113,9 +117,9 @@ public function testCompleteInlineViewsAreNotRepublished(): void public function testEmptyInlineViewsArePublished(): void { - $this->config->expects('string')->with('view.compiled')->andReturn($this->compiledPath); - $this->viewFactory->expects('exists')->with('')->andReturn(false); - $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->andReturnSelf(); + $this->config->expects('string')->with('view.compiled')->returns($this->compiledPath); + $this->viewFactory->expects('exists')->with('')->returns(false); + $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->returns($this->viewFactory); $component = new TestEmptyInlineViewComponent; $viewName = $component->resolveView(); @@ -131,9 +135,9 @@ public function testTruncatedInlineViewsAreReplaced(): void $viewFile = $this->compiledPath . '/' . hash('xxh128', $contents) . '.blade.php'; file_put_contents($viewFile, 'truncated'); - $this->config->expects('string')->with('view.compiled')->andReturn($this->compiledPath); - $this->viewFactory->expects('exists')->with($contents)->andReturn(false); - $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->andReturnSelf(); + $this->config->expects('string')->with('view.compiled')->returns($this->compiledPath); + $this->viewFactory->expects('exists')->with($contents)->returns(false); + $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->returns($this->viewFactory); $component = new TestInlineViewComponent; @@ -143,8 +147,8 @@ public function testTruncatedInlineViewsAreReplaced(): void public function testRegularViewsGetReturnedUsingViewHelper(): void { - $view = m::mock(View::class); - $this->viewFactory->expects('make')->with('alert', [], [])->andReturn($view); + $view = Double::for(View::class); + $this->viewFactory->expects('make')->with('alert', [], [])->returns($view); $component = new TestRegularViewComponentUsingViewHelper; @@ -153,9 +157,9 @@ public function testRegularViewsGetReturnedUsingViewHelper(): void public function testRenderingStringClosureFromComponent(): void { - $this->config->expects('string')->with('view.compiled')->andReturn($this->compiledPath); - $this->viewFactory->expects('exists')->andReturn(false); - $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->andReturnSelf(); + $this->config->expects('string')->with('view.compiled')->returns($this->compiledPath); + $this->viewFactory->expects('exists')->returns(false); + $this->viewFactory->expects('replaceNamespace')->with('__components', $this->compiledPath)->returns($this->viewFactory); $component = new class extends Component { /** @@ -189,8 +193,8 @@ public function render(): ViewContract|Htmlable|Closure|string public function testRegularViewsGetReturnedUsingViewMethod(): void { - $view = m::mock(View::class); - $this->viewFactory->expects('make')->with('alert', [], [])->andReturn($view); + $view = Double::for(View::class); + $this->viewFactory->expects('make')->with('alert', [], [])->returns($view); $component = new TestRegularViewComponentUsingViewMethod; @@ -199,8 +203,8 @@ public function testRegularViewsGetReturnedUsingViewMethod(): void public function testRegularViewNamesGetReturned(): void { - $this->viewFactory->expects('exists')->andReturn(true); - $this->viewFactory->shouldReceive('replaceNamespace')->never(); + $this->viewFactory->expects('exists')->returns(true); + $this->viewFactory->expects('replaceNamespace')->never(); $component = new TestRegularViewNameViewComponent; @@ -292,7 +296,7 @@ public function testBladeViewCacheWithRegularViewNameViewComponent(): void { $component = new TestRegularViewNameViewComponent; - $this->viewFactory->expects('exists')->twice()->andReturn(true); + $this->viewFactory->expects('exists')->times(2)->returns(true); $this->assertSame('alert', $component->resolveView()); $this->assertSame('alert', $component->resolveView()); @@ -318,14 +322,14 @@ public function testBladeViewCacheWithInlineViewComponent(): void { $component = new TestInlineViewComponent; - $this->viewFactory->expects('exists')->twice()->andReturn(false); + $this->viewFactory->expects('exists')->times(2)->returns(false); - $this->config->expects('string')->twice()->with('view.compiled')->andReturn($this->compiledPath); + $this->config->expects('string')->times(2)->with('view.compiled')->returns($this->compiledPath); $this->viewFactory->expects('replaceNamespace') ->with('__components', $this->compiledPath) - ->twice() - ->andReturnSelf(); + ->times(2) + ->returns($this->viewFactory); $compiledViewName = '__components::57b7a54afa0eb51fd9b88eec031c9e9e'; $contents = 'Hello {{ $title }}'; @@ -357,14 +361,14 @@ public function testBladeViewCacheWithInlineViewComponentWhereRenderDependsOnPro $componentA = new TestInlineViewComponentWhereRenderDependsOnProps('A'); $componentB = new TestInlineViewComponentWhereRenderDependsOnProps('B'); - $this->viewFactory->expects('exists')->twice()->andReturn(false); + $this->viewFactory->expects('exists')->times(2)->returns(false); - $this->config->expects('string')->twice()->with('view.compiled')->andReturn($this->compiledPath); + $this->config->expects('string')->times(2)->with('view.compiled')->returns($this->compiledPath); $this->viewFactory->expects('replaceNamespace') ->with('__components', $this->compiledPath) - ->twice() - ->andReturnSelf(); + ->times(2) + ->returns($this->viewFactory); $compiledViewNameA = '__components::9b0498cbe3839becd0d496e05c553485'; $compiledViewNameB = '__components::9d1b9bc4078a3e7274d3766ca02423f3'; @@ -397,12 +401,12 @@ public function testBladeViewCacheCanForgetOneInlineViewWithoutFlushingOtherVari $componentA = new TestInlineViewComponentWhereRenderDependsOnProps('A'); $componentB = new TestInlineViewComponentWhereRenderDependsOnProps('B'); - $this->viewFactory->expects('exists')->times(3)->andReturn(false); - $this->config->expects('string')->times(3)->with('view.compiled')->andReturn($this->compiledPath); + $this->viewFactory->expects('exists')->times(3)->returns(false); + $this->config->expects('string')->times(3)->with('view.compiled')->returns($this->compiledPath); $this->viewFactory->expects('replaceNamespace') ->with('__components', $this->compiledPath) ->times(3) - ->andReturnSelf(); + ->returns($this->viewFactory); $compiledViewNameA = '__components::9b0498cbe3839becd0d496e05c553485'; $compiledViewNameB = '__components::9d1b9bc4078a3e7274d3766ca02423f3'; @@ -436,7 +440,7 @@ public function testFactoryGetsSharedBetweenComponents(): void $this->assertSame($this->viewFactory, $getFactory($regular)); - $replacement = m::mock(Factory::class); + $replacement = Double::for(Factory::class); 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 0e9d64b90..f31db295d 100644 --- a/tests/View/ViewBladeCompilerTest.php +++ b/tests/View/ViewBladeCompilerTest.php @@ -12,7 +12,9 @@ use Hypervel\Tests\TestCase; use Hypervel\View\Compilers\BladeCompiler; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionClassConstant; use RuntimeException; @@ -21,10 +23,12 @@ class ViewBladeCompilerTest extends TestCase { + use VerifiesDoubles; + public function testIsExpiredReturnsTrueIfCompiledFileDoesntExist(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(false); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(false); $this->assertTrue($compiler->isExpired('foo')); } @@ -38,9 +42,9 @@ public function testCannotConstructWithBadCachePath(): void public function testIsExpiredReturnsTrueWhenModificationTimesWarrant(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(true); - $files->expects('lastModified')->with('foo')->andReturn(100); - $files->expects('lastModified')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(0); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(true); + $files->expects('lastModified')->with('foo')->returns(100); + $files->expects('lastModified')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(0); $this->assertTrue($compiler->isExpired('foo')); } @@ -48,8 +52,8 @@ public function testIsExpiredReturnsTrueWhenSourceFileDoesntExist(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $compiled = __DIR__ . '/' . hash('xxh128', 'v3foo') . '.php'; - $files->expects('exists')->with($compiled)->andReturn(true); - $files->expects('lastModified')->with('foo')->andReturn(false); + $files->expects('exists')->with($compiled)->returns(true); + $files->expects('lastModified')->with('foo')->returns(false); $this->assertTrue($compiler->isExpired('foo')); } @@ -58,9 +62,9 @@ public function testIsExpiredReturnsTrueWhenCompiledFileDisappearsBeforeTimestam { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $compiled = __DIR__ . '/' . hash('xxh128', 'v3foo') . '.php'; - $files->expects('exists')->with($compiled)->andReturn(true); - $files->expects('lastModified')->with('foo')->andReturn(100); - $files->expects('lastModified')->with($compiled)->andReturn(false); + $files->expects('exists')->with($compiled)->returns(true); + $files->expects('lastModified')->with('foo')->returns(100); + $files->expects('lastModified')->with($compiled)->returns(false); $this->assertTrue($compiler->isExpired('foo')); } @@ -69,9 +73,9 @@ public function testIsExpiredReturnsTrueWhenModificationTimesAreEqual(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $compiled = __DIR__ . '/' . hash('xxh128', 'v3foo') . '.php'; - $files->expects('exists')->with($compiled)->andReturn(true); - $files->expects('lastModified')->with('foo')->andReturn(100); - $files->expects('lastModified')->with($compiled)->andReturn(100); + $files->expects('exists')->with($compiled)->returns(true); + $files->expects('lastModified')->with('foo')->returns(100); + $files->expects('lastModified')->with($compiled)->returns(100); $this->assertTrue($compiler->isExpired('foo')); } @@ -79,9 +83,9 @@ public function testIsExpiredReturnsTrueWhenModificationTimesAreEqual(): void public function testIsExpiredReturnsFalseWhenUseCacheIsTrueAndNoFileModification(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(true); - $files->expects('lastModified')->with('foo')->andReturn(0); - $files->expects('lastModified')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(100); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(true); + $files->expects('lastModified')->with('foo')->returns(0); + $files->expects('lastModified')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(100); $this->assertFalse($compiler->isExpired('foo')); } @@ -94,7 +98,7 @@ public function testIsExpiredReturnsTrueWhenUseCacheIsFalse(): void public function testIsExpiredReturnsFalseWhenIgnoreCacheTimestampsIsTrue(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, shouldCheckTimestamps: false); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(true); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(true); $this->assertFalse($compiler->isExpired('foo')); } @@ -119,9 +123,9 @@ public function testRelativeCompiledPathsPreserveExternalViewIdentity(): void public function testCompileCompilesFileAndReturnsContents(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('foo')->andReturn('Hello World'); - $files->expects('exists')->with(__DIR__)->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(false); + $files->expects('get')->with('foo')->returns('Hello World'); + $files->expects('exists')->with(__DIR__)->returns(true); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(false); $files->expects('replace')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php', 'Hello World'); $compiler->compile('foo'); } @@ -140,10 +144,10 @@ public function testCompileMissingSourceThrowsPreciseFilesystemException(): void public function testCompileCompilesFileAndReturnsContentsCreatingDirectory(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('foo')->andReturn('Hello World'); - $files->expects('exists')->with(__DIR__)->andReturn(false); + $files->expects('get')->with('foo')->returns('Hello World'); + $files->expects('exists')->with(__DIR__)->returns(false); $files->expects('makeDirectory')->with(__DIR__, 0777, true, true); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(false); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(false); $files->expects('replace')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php', 'Hello World'); $compiler->compile('foo'); } @@ -152,10 +156,10 @@ public function testCompileUpdatesCacheIfChanged(): void { $compiledPath = __DIR__ . '/' . hash('xxh128', 'v3foo') . '.php'; $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('foo')->andReturn('Hello World'); - $files->expects('exists')->with(__DIR__)->andReturn(true); - $files->expects('exists')->with($compiledPath)->andReturn(true); - $files->expects('hash')->with($compiledPath, 'xxh128')->andReturn(hash('xxh128', 'outdated content')); + $files->expects('get')->with('foo')->returns('Hello World'); + $files->expects('exists')->with(__DIR__)->returns(true); + $files->expects('exists')->with($compiledPath)->returns(true); + $files->expects('hash')->with($compiledPath, 'xxh128')->returns(hash('xxh128', 'outdated content')); $files->expects('replace')->with($compiledPath, 'Hello World'); $compiler->compile('foo'); } @@ -164,13 +168,13 @@ public function testCompileKeepsCacheIfUnchanged(): void { $compiledPath = __DIR__ . '/' . hash('xxh128', 'v3foo') . '.php'; $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('foo')->andReturn('Hello World'); - $files->expects('exists')->with(__DIR__)->andReturn(true); - $files->expects('exists')->with($compiledPath)->andReturn(true); - $files->expects('hash')->with($compiledPath, 'xxh128')->andReturn(hash('xxh128', 'Hello World')); - $files->expects('lastModified')->with('foo')->andReturn(100); - $files->expects('lastModified')->with($compiledPath)->andReturn(200); - $files->shouldReceive('replace')->never(); + $files->expects('get')->with('foo')->returns('Hello World'); + $files->expects('exists')->with(__DIR__)->returns(true); + $files->expects('exists')->with($compiledPath)->returns(true); + $files->expects('hash')->with($compiledPath, 'xxh128')->returns(hash('xxh128', 'Hello World')); + $files->expects('lastModified')->with('foo')->returns(100); + $files->expects('lastModified')->with($compiledPath)->returns(200); + $files->expects('replace')->never(); $compiler->compile('foo'); } @@ -183,17 +187,17 @@ public function testCompileHandlesFilesDisappearingBeforeTimestampRead( $compiledPath = __DIR__ . '/' . hash('xxh128', 'v3foo') . '.php'; $contents = 'Hello World'; $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('foo')->andReturn('Hello World'); - $files->expects('exists')->with(__DIR__)->andReturn(true); - $files->expects('exists')->with($compiledPath)->andReturn(true); - $files->expects('hash')->with($compiledPath, 'xxh128')->andReturn(hash('xxh128', $contents)); - $files->expects('lastModified')->with('foo')->andReturn($sourceModified); - $files->expects('lastModified')->with($compiledPath)->andReturn($compiledModified); + $files->expects('get')->with('foo')->returns('Hello World'); + $files->expects('exists')->with(__DIR__)->returns(true); + $files->expects('exists')->with($compiledPath)->returns(true); + $files->expects('hash')->with($compiledPath, 'xxh128')->returns(hash('xxh128', $contents)); + $files->expects('lastModified')->with('foo')->returns($sourceModified); + $files->expects('lastModified')->with($compiledPath)->returns($compiledModified); - $replaceExpectation = $files->shouldReceive('replace')->with($compiledPath, $contents); + $replaceExpectation = $files->expects('replace')->with($compiledPath, $contents); if ($shouldRepublish) { - $replaceExpectation->once(); + $replaceExpectation->times(1); } else { $replaceExpectation->never(); } @@ -258,9 +262,9 @@ public function testCompileRefreshesCacheTimestampIfUnchangedButExpired(): void public function testCompileCompilesAndGetThePath(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('foo')->andReturn('Hello World'); - $files->expects('exists')->with(__DIR__)->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(false); + $files->expects('get')->with('foo')->returns('Hello World'); + $files->expects('exists')->with(__DIR__)->returns(true); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(false); $files->expects('replace')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php', 'Hello World'); $compiler->compile('foo'); $this->assertSame('foo', $compiler->getPath()); @@ -276,9 +280,9 @@ public function testCompileSetAndGetThePath(): void public function testCompileWithPathSetBefore(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('foo')->andReturn('Hello World'); - $files->expects('exists')->with(__DIR__)->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(false); + $files->expects('get')->with('foo')->returns('Hello World'); + $files->expects('exists')->with(__DIR__)->returns(true); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(false); $files->expects('replace')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php', 'Hello World'); $compiler->setPath('foo'); $compiler->compile(); @@ -291,15 +295,15 @@ public function testCompilePathsAreIsolatedBetweenConcurrentCoroutines(): void $secondCompiledPath = __DIR__ . '/' . hash('xxh128', 'v3second') . '.php'; $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('first')->andReturnUsing(function (): string { + $files->expects('get')->with('first')->resolves(function (): string { usleep(5000); return 'First'; }); - $files->expects('get')->with('second')->andReturn('Second'); - $files->expects('exists')->twice()->with(__DIR__)->andReturn(true); - $files->expects('exists')->with($firstCompiledPath)->andReturn(false); - $files->expects('exists')->with($secondCompiledPath)->andReturn(false); + $files->expects('get')->with('second')->returns('Second'); + $files->expects('exists')->times(2)->with(__DIR__)->returns(true); + $files->expects('exists')->with($firstCompiledPath)->returns(false); + $files->expects('exists')->with($secondCompiledPath)->returns(false); $files->expects('replace')->with($firstCompiledPath, 'First'); $files->expects('replace')->with($secondCompiledPath, 'Second'); @@ -501,9 +505,9 @@ public function testRawTagsCanBeSetToLegacyValues(): void public function testIncludePathToTemplate(string $content, string $compiled): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('foo')->andReturn($content); - $files->expects('exists')->with(__DIR__)->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->andReturn(false); + $files->expects('get')->with('foo')->returns($content); + $files->expects('exists')->with(__DIR__)->returns(true); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php')->returns(false); $files->expects('replace')->with(__DIR__ . '/' . hash('xxh128', 'v3foo') . '.php', $compiled); $compiler->compile('foo'); @@ -559,9 +563,9 @@ public static function appendViewPathDataProvider(): array public function testDontIncludeEmptyPath(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('')->andReturn('Hello World'); - $files->expects('exists')->with(__DIR__)->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3') . '.php')->andReturn(false); + $files->expects('get')->with('')->returns('Hello World'); + $files->expects('exists')->with(__DIR__)->returns(true); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v3') . '.php')->returns(false); $files->expects('replace')->with(__DIR__ . '/' . hash('xxh128', 'v3') . '.php', 'Hello World'); $compiler->setPath(''); $compiler->compile(); @@ -572,9 +576,9 @@ public function testDontIncludeEmptyPath(): void public function testIncludesZeroPath(): void { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->expects('get')->with('0')->andReturn('Hello World'); - $files->expects('exists')->with(__DIR__)->andReturn(true); - $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v30') . '.php')->andReturn(false); + $files->expects('get')->with('0')->returns('Hello World'); + $files->expects('exists')->with(__DIR__)->returns(true); + $files->expects('exists')->with(__DIR__ . '/' . hash('xxh128', 'v30') . '.php')->returns(false); $files->expects('replace')->with(__DIR__ . '/' . hash('xxh128', 'v30') . '.php', 'Hello World'); $compiler->compile('0'); $this->assertSame('0', $compiler->getPath()); @@ -661,9 +665,9 @@ public function testAnonymousComponentNamespacesCanBeStored(): void /** * Create a mocked filesystem. */ - protected function getFiles(): Filesystem + protected function getFiles(): Filesystem&DoubleInterface { - return m::mock(Filesystem::class); + return Double::for(Filesystem::class); } } diff --git a/tests/View/ViewCompilerEngineTest.php b/tests/View/ViewCompilerEngineTest.php index 762401973..a17d9f532 100755 --- a/tests/View/ViewCompilerEngineTest.php +++ b/tests/View/ViewCompilerEngineTest.php @@ -13,17 +13,20 @@ use Hypervel\View\Compilers\CompilerInterface; use Hypervel\View\Engines\CompilerEngine; use Hypervel\View\ViewException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Swoole\Coroutine\CanceledException; use Symfony\Component\HttpKernel\Exception\HttpException; class ViewCompilerEngineTest extends TestCase { + use VerifiesDoubles; + public function testViewsMayBeRecompiledAndRendered(): void { $engine = $this->getEngine(); - $engine->getCompiler()->expects('getCompiledPath')->with(__DIR__ . '/Fixtures/foo.php')->andReturn(__DIR__ . '/Fixtures/basic.php'); - $engine->getCompiler()->expects('isExpired')->with(__DIR__ . '/Fixtures/foo.php')->andReturn(true); + $engine->getCompiler()->expects('getCompiledPath')->with(__DIR__ . '/Fixtures/foo.php')->returns(__DIR__ . '/Fixtures/basic.php'); + $engine->getCompiler()->expects('isExpired')->with(__DIR__ . '/Fixtures/foo.php')->returns(true); $engine->getCompiler()->expects('compile')->with(__DIR__ . '/Fixtures/foo.php'); $results = $engine->get(__DIR__ . '/Fixtures/foo.php'); @@ -34,9 +37,9 @@ public function testViewsMayBeRecompiledAndRendered(): void public function testViewsAreNotRecompiledIfTheyAreNotExpired(): void { $engine = $this->getEngine(); - $engine->getCompiler()->expects('getCompiledPath')->with(__DIR__ . '/Fixtures/foo.php')->andReturn(__DIR__ . '/Fixtures/basic.php'); - $engine->getCompiler()->expects('isExpired')->andReturn(false); - $engine->getCompiler()->shouldReceive('compile')->never(); + $engine->getCompiler()->expects('getCompiledPath')->with(__DIR__ . '/Fixtures/foo.php')->returns(__DIR__ . '/Fixtures/basic.php'); + $engine->getCompiler()->expects('isExpired')->returns(false); + $engine->getCompiler()->expects('compile')->never(); $results = $engine->get(__DIR__ . '/Fixtures/foo.php'); $this->assertSame('Hello World @@ -46,8 +49,8 @@ public function testViewsAreNotRecompiledIfTheyAreNotExpired(): void public function testRegularExceptionsAreReThrownAsViewExceptions(): void { $engine = $this->getEngine(); - $engine->getCompiler()->expects('getCompiledPath')->with(__DIR__ . '/Fixtures/foo.php')->andReturn(__DIR__ . '/Fixtures/regular-exception.php'); - $engine->getCompiler()->expects('isExpired')->andReturn(false); + $engine->getCompiler()->expects('getCompiledPath')->with(__DIR__ . '/Fixtures/foo.php')->returns(__DIR__ . '/Fixtures/regular-exception.php'); + $engine->getCompiler()->expects('isExpired')->returns(false); $this->expectExceptionObject(new ViewException('regular exception message')); @@ -59,12 +62,12 @@ public function testCancellationIsNotWrappedAndCompiledPathIsPopped(): void $path = __DIR__ . '/Fixtures/foo.php'; $compiled = __DIR__ . '/Fixtures/basic.php'; $cancellation = new CanceledException; - $files = m::mock(Filesystem::class); - $files->expects('getRequire')->with($compiled, [])->andThrow($cancellation); + $files = Double::for(Filesystem::class); + $files->expects('getRequire')->with($compiled, [])->throws($cancellation); $engine = $this->getEngine($files); - $engine->getCompiler()->expects('isExpired')->with($path)->andReturn(false); - $engine->getCompiler()->expects('getCompiledPath')->with($path)->andReturn($compiled); + $engine->getCompiler()->expects('isExpired')->with($path)->returns(false); + $engine->getCompiler()->expects('getCompiledPath')->with($path)->returns($compiled); try { $engine->get($path); @@ -79,8 +82,8 @@ public function testCancellationIsNotWrappedAndCompiledPathIsPopped(): void public function testHttpExceptionsAreNotReThrownAsViewExceptions(): void { $engine = $this->getEngine(); - $engine->getCompiler()->expects('getCompiledPath')->with(__DIR__ . '/Fixtures/foo.php')->andReturn(__DIR__ . '/Fixtures/http-exception.php'); - $engine->getCompiler()->expects('isExpired')->andReturn(false); + $engine->getCompiler()->expects('getCompiledPath')->with(__DIR__ . '/Fixtures/foo.php')->returns(__DIR__ . '/Fixtures/http-exception.php'); + $engine->getCompiler()->expects('isExpired')->returns(false); $this->expectExceptionObject(new HttpException(403, 'http exception message')); @@ -90,9 +93,9 @@ public function testHttpExceptionsAreNotReThrownAsViewExceptions(): void public function testThatViewsAreNotAskTwiceIfTheyAreExpired(): void { $engine = $this->getEngine(); - $engine->getCompiler()->expects('getCompiledPath')->times(5)->with(__DIR__ . '/Fixtures/foo.php')->andReturn(__DIR__ . '/Fixtures/basic.php'); - $engine->getCompiler()->expects('isExpired')->times(3)->andReturn(false); - $engine->getCompiler()->shouldReceive('compile')->never(); + $engine->getCompiler()->expects('getCompiledPath')->times(5)->with(__DIR__ . '/Fixtures/foo.php')->returns(__DIR__ . '/Fixtures/basic.php'); + $engine->getCompiler()->expects('isExpired')->times(3)->returns(false); + $engine->getCompiler()->expects('compile')->never(); $engine->get(__DIR__ . '/Fixtures/foo.php'); $engine->get(__DIR__ . '/Fixtures/foo.php'); @@ -112,32 +115,29 @@ public function testViewsAreRecompiledWhenCompiledViewIsMissingViaFileNotFoundEx $compiled = __DIR__ . '/Fixtures/basic.php'; $path = __DIR__ . '/Fixtures/foo.php'; - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $engine = $this->getEngine($files); - $files->expects('getRequire') - ->with($compiled, []) - ->andReturn('compiled-content'); + $calls = 0; + $files->expects('getRequire')->with($compiled, [])->times(3)->resolves(function () use (&$calls, $path): string { + if (++$calls === 2) { + throw new FileNotFoundException( + "File does not exist at path {$path}." + ); + } - $files->expects('getRequire') - ->with($compiled, []) - ->andThrow(new FileNotFoundException( - "File does not exist at path {$path}." - )); - - $files->expects('getRequire') - ->with($compiled, []) - ->andReturn('compiled-content'); + return 'compiled-content'; + }); $engine->getCompiler() ->expects('getCompiledPath') - ->twice() + ->times(2) ->with($path) - ->andReturn($compiled); + ->returns($compiled); $engine->getCompiler() ->expects('isExpired') - ->andReturn(false); + ->returns(false); $engine->getCompiler() ->expects('compile') @@ -152,32 +152,29 @@ public function testViewsAreRecompiledWhenCompiledViewIsMissingViaRequireExcepti $compiled = __DIR__ . '/Fixtures/basic.php'; $path = __DIR__ . '/Fixtures/foo.php'; - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $engine = $this->getEngine($files); - $files->expects('getRequire') - ->with($compiled, []) - ->andReturn('compiled-content'); - - $files->expects('getRequire') - ->with($compiled, []) - ->andThrow(new ErrorException( - "require({$path}): Failed to open stream: No such file or directory", - )); + $calls = 0; + $files->expects('getRequire')->with($compiled, [])->times(3)->resolves(function () use (&$calls, $path): string { + if (++$calls === 2) { + throw new ErrorException( + "require({$path}): Failed to open stream: No such file or directory", + ); + } - $files->expects('getRequire') - ->with($compiled, []) - ->andReturn('compiled-content'); + return 'compiled-content'; + }); $engine->getCompiler() ->expects('getCompiledPath') - ->twice() + ->times(2) ->with($path) - ->andReturn($compiled); + ->returns($compiled); $engine->getCompiler() ->expects('isExpired') - ->andReturn(false); + ->returns(false); $engine->getCompiler() ->expects('compile') @@ -192,34 +189,27 @@ public function testViewsAreRecompiledJustOnceWhenCompiledViewIsMissing(): void $compiled = __DIR__ . '/Fixtures/basic.php'; $path = __DIR__ . '/Fixtures/foo.php'; - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $engine = $this->getEngine($files); - $files->expects('getRequire') - ->with($compiled, []) - ->andReturn('compiled-content'); - - $files->expects('getRequire') - ->with($compiled, []) - ->andThrow(new FileNotFoundException( - "File does not exist at path {$path}." - )); + $requires = 0; + $files->expects('getRequire')->times(3)->with($compiled, [])->resolves(function () use (&$requires, $path): string { + if ($requires++ === 0) { + return 'compiled-content'; + } - $files->expects('getRequire') - ->with($compiled, []) - ->andThrow(new FileNotFoundException( - "File does not exist at path {$path}." - )); + throw new FileNotFoundException("File does not exist at path {$path}."); + }); $engine->getCompiler() ->expects('getCompiledPath') - ->twice() + ->times(2) ->with($path) - ->andReturn($compiled); + ->returns($compiled); $engine->getCompiler() ->expects('isExpired') - ->andReturn(false); + ->returns(false); $engine->getCompiler() ->expects('compile') @@ -236,27 +226,27 @@ public function testViewsAreNotRecompiledOnRegularViewException(): void $compiled = __DIR__ . '/Fixtures/basic.php'; $path = __DIR__ . '/Fixtures/foo.php'; - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $engine = $this->getEngine($files); $files->expects('getRequire') ->with($compiled, []) - ->andThrow(new Exception( + ->throws(new Exception( 'Just an regular error...' )); $engine->getCompiler() ->expects('isExpired') - ->andReturn(false); + ->returns(false); $engine->getCompiler() - ->shouldReceive('compile') + ->expects('compile') ->never(); $engine->getCompiler() ->expects('getCompiledPath') ->with($path) - ->andReturn($compiled); + ->returns($compiled); $this->expectExceptionObject(new ViewException('Just an regular error...')); $engine->get($path); @@ -267,18 +257,18 @@ public function testViewsAreNotRecompiledIfTheyWereJustCompiled(): void $compiled = __DIR__ . '/Fixtures/basic.php'; $path = __DIR__ . '/Fixtures/foo.php'; - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $engine = $this->getEngine($files); $files->expects('getRequire') ->with($compiled, []) - ->andThrow(new FileNotFoundException( + ->throws(new FileNotFoundException( "File does not exist at path {$path}." )); $engine->getCompiler() ->expects('isExpired') - ->andReturn(true); + ->returns(true); $engine->getCompiler() ->expects('compile') @@ -287,7 +277,7 @@ public function testViewsAreNotRecompiledIfTheyWereJustCompiled(): void $engine->getCompiler() ->expects('getCompiledPath') ->with($path) - ->andReturn($compiled); + ->returns($compiled); $this->expectExceptionObject(new ViewException("File does not exist at path {$path}.")); $engine->get($path); @@ -299,9 +289,9 @@ public function testExpiredViewsAreCheckedAndCompiledOnEveryRender(): void $compiled = __DIR__ . '/Fixtures/basic.php'; $engine = $this->getEngine(); - $engine->getCompiler()->expects('isExpired')->twice()->with($path)->andReturn(true); - $engine->getCompiler()->expects('compile')->twice()->with($path); - $engine->getCompiler()->expects('getCompiledPath')->twice()->with($path)->andReturn($compiled); + $engine->getCompiler()->expects('isExpired')->times(2)->with($path)->returns(true); + $engine->getCompiler()->expects('compile')->times(2)->with($path); + $engine->getCompiler()->expects('getCompiledPath')->times(2)->with($path)->returns($compiled); $engine->get($path); $engine->get($path); @@ -310,17 +300,17 @@ public function testExpiredViewsAreCheckedAndCompiledOnEveryRender(): void public function testEachCompiledVariantHasItsOwnFreshnessCheck(): void { $path = '/views/example.blade.php'; - $files = m::mock(Filesystem::class); + $files = Double::for(Filesystem::class); $engine = $this->getEngine($files); - $engine->getCompiler()->expects('getCompiledPath')->twice()->with($path) - ->andReturn('/compiled/default.php', '/compiled/custom.php'); - $engine->getCompiler()->expects('isExpired')->twice()->with($path)->andReturn(false, true); + $engine->getCompiler()->expects('getCompiledPath')->times(2)->with($path) + ->returns('/compiled/default.php', '/compiled/custom.php'); + $engine->getCompiler()->expects('isExpired')->times(2)->with($path)->returns(false, true); $engine->getCompiler()->expects('compile')->with($path); - $files->expects('getRequire')->with('/compiled/default.php', [])->andReturnUsing(static function (): void { + $files->expects('getRequire')->with('/compiled/default.php', [])->resolves(static function (): void { echo 'default'; }); - $files->expects('getRequire')->with('/compiled/custom.php', [])->andReturnUsing(static function (): void { + $files->expects('getRequire')->with('/compiled/custom.php', [])->resolves(static function (): void { echo 'custom'; }); @@ -333,8 +323,8 @@ public function testCompiledPathIsPoppedAfterSuccessfulRender(): void $path = __DIR__ . '/Fixtures/foo.php'; $engine = $this->getEngine(); - $engine->getCompiler()->expects('isExpired')->with($path)->andReturn(false); - $engine->getCompiler()->expects('getCompiledPath')->with($path)->andReturn(__DIR__ . '/Fixtures/basic.php'); + $engine->getCompiler()->expects('isExpired')->with($path)->returns(false); + $engine->getCompiler()->expects('getCompiledPath')->with($path)->returns(__DIR__ . '/Fixtures/basic.php'); $engine->get($path); @@ -346,8 +336,8 @@ public function testCompiledPathIsPoppedAfterCaughtRenderFailure(): void $path = __DIR__ . '/Fixtures/foo.php'; $engine = $this->getEngine(); - $engine->getCompiler()->expects('isExpired')->with($path)->andReturn(false); - $engine->getCompiler()->expects('getCompiledPath')->with($path)->andReturn(__DIR__ . '/Fixtures/regular-exception.php'); + $engine->getCompiler()->expects('isExpired')->with($path)->returns(false); + $engine->getCompiler()->expects('getCompiledPath')->with($path)->returns(__DIR__ . '/Fixtures/regular-exception.php'); try { $engine->get($path); @@ -364,6 +354,6 @@ public function testCompiledPathIsPoppedAfterCaughtRenderFailure(): void */ protected function getEngine(?Filesystem $filesystem = null): CompilerEngine { - return new CompilerEngine(m::mock(CompilerInterface::class), $filesystem ?: new Filesystem); + return new CompilerEngine(Double::for(CompilerInterface::class), $filesystem ?: new Filesystem); } } diff --git a/tests/View/ViewFactoryTest.php b/tests/View/ViewFactoryTest.php index 1ef4be7b3..61224756b 100755 --- a/tests/View/ViewFactoryTest.php +++ b/tests/View/ViewFactoryTest.php @@ -9,7 +9,6 @@ use Generator; use Hypervel\Container\Container as ContainerInstance; use Hypervel\Context\CoroutineContext; -use Hypervel\Contracts\Container\Container; use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; use Hypervel\Contracts\Translation\Translator; use Hypervel\Contracts\View\Engine; @@ -29,18 +28,22 @@ use Hypervel\View\View; use Hypervel\View\ViewFinderInterface; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionFunction; use RuntimeException; class ViewFactoryTest extends TestCase { + use VerifiesDoubles; + public function testCloneIsolatesFinderAndSharedEnvironment(): void { $factory = new Factory( - m::mock(EngineResolver::class), + Double::for(EngineResolver::class), new FileViewFinder(new Filesystem, [__DIR__ . '/Fixtures']), - m::mock(DispatcherContract::class) + Double::for(DispatcherContract::class) ); $clone = clone $factory; @@ -63,12 +66,11 @@ public function testMakeCreatesNewViewInstanceWithProperPathAndEngine(): void unset($_SERVER['__test.view']); $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->with('view')->andReturn('path.php'); - $engine = m::mock(Engine::class); - $factory->getEngineResolver()->expects('resolve')->with('php')->andReturn($engine); + $factory->getFinder()->expects('find')->with('view')->returns('path.php'); + $engine = Double::for(Engine::class); + $factory->getEngineResolver()->expects('resolve')->with('php')->returns($engine); $factory->getFinder()->expects('addExtension')->with('php'); $factory->setDispatcher($this->createEventDispatcher()); - $factory->setContainer(m::mock(Container::class)); $factory->creator('view', function ($view) { $_SERVER['__test.view'] = $view; }); @@ -92,8 +94,8 @@ private function createEventDispatcher(): EventDispatcher public function testExistsPassesAndFailsViews(): void { $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->with('foo')->andThrow(InvalidArgumentException::class); - $factory->getFinder()->expects('find')->with('bar')->andReturn('path.php'); + $factory->getFinder()->expects('find')->with('foo')->throws(new InvalidArgumentException); + $factory->getFinder()->expects('find')->with('bar')->returns('path.php'); $this->assertFalse($factory->exists('foo')); $this->assertTrue($factory->exists('bar')); @@ -114,13 +116,12 @@ public function testFirstCreatesNewViewInstanceWithProperPath(): void unset($_SERVER['__test.view']); $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->times(2)->with('view')->andReturn('path.php'); - $factory->getFinder()->expects('find')->with('bar')->andThrow(InvalidArgumentException::class); - $engine = m::mock(Engine::class); - $factory->getEngineResolver()->expects('resolve')->with('php')->andReturn($engine); + $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); + $factory->getEngineResolver()->expects('resolve')->with('php')->returns($engine); $factory->getFinder()->expects('addExtension')->with('php'); $factory->setDispatcher($this->createEventDispatcher()); - $factory->setContainer(m::mock(Container::class)); $factory->creator('view', function ($view) { $_SERVER['__test.view'] = $view; }); @@ -137,9 +138,9 @@ public function testFirstCreatesNewViewInstanceWithProperPath(): void public function testFirstAcceptsZeroAsAViewName(): void { $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->times(2)->with('0')->andReturn('0.php'); - $factory->getEngineResolver()->expects('resolve')->with('php')->andReturn(m::mock(Engine::class)); - $factory->getDispatcher()->expects('hasListeners')->with('creating: 0')->andReturn(false); + $factory->getFinder()->expects('find')->times(2)->with('0')->returns('0.php'); + $factory->getEngineResolver()->expects('resolve')->with('php')->returns(Double::for(Engine::class)); + $factory->getDispatcher()->expects('hasListeners')->with('creating: 0')->returns(false); $this->assertSame('0', $factory->first(['0'])->name()); } @@ -149,8 +150,8 @@ public function testFirstThrowsInvalidArgumentExceptionIfNoneFound(): void $this->expectException(InvalidArgumentException::class); $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->with('view')->andThrow(InvalidArgumentException::class); - $factory->getFinder()->expects('find')->with('bar')->andThrow(InvalidArgumentException::class); + $factory->getFinder()->expects('find')->with('view')->throws(new InvalidArgumentException); + $factory->getFinder()->expects('find')->with('bar')->throws(new InvalidArgumentException); $factory->getFinder()->expects('addExtension')->with('php'); $factory->addExtension('php', 'php'); $factory->first(['bar', 'view'], ['foo' => 'bar'], ['baz' => 'boom']); @@ -158,13 +159,13 @@ public function testFirstThrowsInvalidArgumentExceptionIfNoneFound(): void public function testRenderEachCreatesViewForEachItemInArray(): void { - $factory = m::mock(Factory::class . '[make]', $this->getFactoryArgs()); - $mockView1 = m::mock(ViewContract::class); - $factory->expects('make')->with('foo', ['key' => 'bar', 'value' => 'baz'])->andReturn($mockView1); - $mockView2 = m::mock(ViewContract::class); - $factory->expects('make')->with('foo', ['key' => 'breeze', 'value' => 'boom'])->andReturn($mockView2); - $mockView1->expects('render')->andReturn('dayle'); - $mockView2->expects('render')->andReturn('rees'); + $factory = Double::for(Factory::class)->passthru(new Factory(...$this->getFactoryArgs())); + $mockView1 = Double::for(ViewContract::class); + $factory->expects('make')->with('foo', ['key' => 'bar', 'value' => 'baz'])->returns($mockView1); + $mockView2 = Double::for(ViewContract::class); + $factory->expects('make')->with('foo', ['key' => 'breeze', 'value' => 'boom'])->returns($mockView2); + $mockView1->expects('render')->returns('dayle'); + $mockView2->expects('render')->returns('rees'); $result = $factory->renderEach('foo', ['bar' => 'baz', 'breeze' => 'boom'], 'value'); @@ -173,10 +174,10 @@ public function testRenderEachCreatesViewForEachItemInArray(): void public function testEmptyViewsCanBeReturnedFromRenderEach(): void { - $factory = m::mock(Factory::class . '[make]', $this->getFactoryArgs()); - $mockView = m::mock(ViewContract::class); - $factory->expects('make')->with('foo')->andReturn($mockView); - $mockView->expects('render')->andReturn('empty'); + $factory = Double::for(Factory::class)->passthru(new Factory(...$this->getFactoryArgs())); + $mockView = Double::for(ViewContract::class); + $factory->expects('make')->with('foo')->returns($mockView); + $mockView->expects('render')->returns('empty'); $this->assertSame('empty', $factory->renderEach('view', [], 'iterator', 'foo')); } @@ -195,11 +196,10 @@ public function testEnvironmentAddsExtensionWithCustomResolver(): void $factory->getFinder()->expects('addExtension')->with('foo'); $factory->getEngineResolver()->expects('register')->with('bar', $resolver); - $factory->getFinder()->expects('find')->with('view')->andReturn('path.foo'); - $engine = m::mock(Engine::class); - $factory->getEngineResolver()->expects('resolve')->with('bar')->andReturn($engine); - $factory->getDispatcher()->expects('hasListeners')->andReturn(false); - $factory->setContainer(m::mock(Container::class)); + $factory->getFinder()->expects('find')->with('view')->returns('path.foo'); + $engine = Double::for(Engine::class); + $factory->getEngineResolver()->expects('resolve')->with('bar')->returns($engine); + $factory->getDispatcher()->expects('hasListeners')->returns(false); $factory->addExtension('foo', 'bar', $resolver); @@ -239,18 +239,16 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessary(): void $factory->getDispatcher() ->expects('listen') - ->with('creating: name', m::type(Closure::class)); + ->with('creating: name', Argument::type(Closure::class)); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('dispatch') - ->with('creating: name', m::type('array')); - - $factory->setContainer(m::mock(Container::class)); + ->with('creating: name', Argument::type('array')); - $view = m::mock(View::class); - $view->expects('name')->andReturn('name'); + $view = Double::for(View::class); + $view->expects('name')->returns('name'); $factory->creator('name', fn () => true); @@ -263,18 +261,16 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessaryUsingNamespaced $factory->getDispatcher() ->expects('listen') - ->with('creating: namespaced::*', m::type(Closure::class)); + ->with('creating: namespaced::*', Argument::type(Closure::class)); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('dispatch') - ->with('creating: namespaced::my-package-view', m::type('array')); - - $factory->setContainer(m::mock(Container::class)); + ->with('creating: namespaced::my-package-view', Argument::type('array')); - $view = m::mock(View::class); - $view->expects('name')->andReturn('namespaced::my-package-view'); + $view = Double::for(View::class); + $view->expects('name')->returns('namespaced::my-package-view'); $factory->creator('namespaced::*', fn () => true); @@ -287,22 +283,20 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessaryUsingNamespaced $factory->getDispatcher() ->expects('listen') - ->with('creating: namespaced::*', m::type(Closure::class)); + ->with('creating: namespaced::*', Argument::type(Closure::class)); $factory->getDispatcher() ->expects('listen') - ->with('creating: welcome', m::type(Closure::class)); + ->with('creating: welcome', Argument::type(Closure::class)); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('dispatch') - ->with('creating: namespaced::my-package-view', m::type('array')); + ->with('creating: namespaced::my-package-view', Argument::type('array')); - $factory->setContainer(m::mock(Container::class)); - - $view = m::mock(View::class); - $view->expects('name')->andReturn('namespaced::my-package-view'); + $view = Double::for(View::class); + $view->expects('name')->returns('namespaced::my-package-view'); $factory->creator(['namespaced::*', 'welcome'], fn () => true); @@ -315,18 +309,16 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessaryUsingWildcards( $factory->getDispatcher() ->expects('listen') - ->with('creating: *', m::type(Closure::class)); + ->with('creating: *', Argument::type(Closure::class)); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('dispatch') - ->with('creating: name', m::type('array')); - - $factory->setContainer(m::mock(Container::class)); + ->with('creating: name', Argument::type('array')); - $view = m::mock(View::class); - $view->expects('name')->andReturn('name'); + $view = Double::for(View::class); + $view->expects('name')->returns('name'); $factory->creator('*', fn () => true); @@ -339,19 +331,17 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessaryUsingNormalized $factory->getDispatcher() ->expects('listen') - ->with('creating: components.button', m::type(Closure::class)); + ->with('creating: components.button', Argument::type(Closure::class)); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('dispatch') - ->with('creating: components/button', m::type('array')); - - $factory->setContainer(m::mock(Container::class)); + ->with('creating: components/button', Argument::type('array')); - $view = m::mock(View::class); + $view = Double::for(View::class); $view->expects('name') - ->andReturn('components/button'); + ->returns('components/button'); $factory->creator('components.button', fn () => true); @@ -364,16 +354,16 @@ public function testCallComposerDoesDispatchEventsWhenIsNecessary(): void $factory->getDispatcher() ->expects('listen') - ->with('composing: name', m::type(Closure::class)); + ->with('composing: name', Argument::type(Closure::class)); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('dispatch') - ->with('composing: name', m::type('array')); + ->with('composing: name', Argument::type('array')); - $view = m::mock(View::class); - $view->expects('name')->andReturn('name'); + $view = Double::for(View::class); + $view->expects('name')->returns('name'); $factory->composer('name', fn () => true); @@ -386,16 +376,16 @@ public function testCallComposerDoesDispatchEventsWhenIsNecessaryAndUsingTheArra $factory->getDispatcher() ->expects('listen') - ->with('composing: name', m::type(Closure::class)); + ->with('composing: name', Argument::type(Closure::class)); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('dispatch') - ->with('composing: name', m::type('array')); + ->with('composing: name', Argument::type('array')); - $view = m::mock(View::class); - $view->expects('name')->andReturn('name'); + $view = Double::for(View::class); + $view->expects('name')->returns('name'); $factory->composer(['name'], fn () => true); @@ -408,16 +398,16 @@ public function testCallComposersDoesDispatchEventsWhenIsNecessaryUsingNamespace $factory->getDispatcher() ->expects('listen') - ->with('composing: namespaced::*', m::type(Closure::class)); + ->with('composing: namespaced::*', Argument::type(Closure::class)); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('dispatch') - ->with('composing: namespaced::my-package-view', m::type('array')); + ->with('composing: namespaced::my-package-view', Argument::type('array')); - $view = m::mock(View::class); - $view->expects('name')->andReturn('namespaced::my-package-view'); + $view = Double::for(View::class); + $view->expects('name')->returns('namespaced::my-package-view'); $factory->composer('namespaced::*', fn () => true); @@ -429,20 +419,20 @@ public function testCallComposersDoesDispatchEventsWhenIsNecessaryUsingNamespace $factory = $this->getFactory(); $factory->getDispatcher() ->expects('listen') - ->with('composing: namespaced::*', m::type(Closure::class)); + ->with('composing: namespaced::*', Argument::type(Closure::class)); $factory->getDispatcher() ->expects('listen') - ->with('composing: welcome', m::type(Closure::class)); + ->with('composing: welcome', Argument::type(Closure::class)); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('dispatch') - ->with('composing: namespaced::my-package-view', m::type('array')); + ->with('composing: namespaced::my-package-view', Argument::type('array')); - $view = m::mock(View::class); - $view->expects('name')->andReturn('namespaced::my-package-view'); + $view = Double::for(View::class); + $view->expects('name')->returns('namespaced::my-package-view'); $factory->composer(['namespaced::*', 'welcome'], fn () => true); @@ -453,18 +443,18 @@ public function testCallComposersDoesDispatchEventsWhenIsNecessaryUsingWildcards { $factory = $this->getFactory(); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('listen') - ->with('composing: *', m::type(Closure::class)); + ->with('composing: *', Argument::type(Closure::class)); $factory->getDispatcher() ->expects('dispatch') - ->with('composing: name', m::type('array')); + ->with('composing: name', Argument::type('array')); - $view = m::mock(View::class); - $view->expects('name')->andReturn('name'); + $view = Double::for(View::class); + $view->expects('name')->returns('name'); $factory->composer('*', fn () => true); @@ -475,18 +465,18 @@ public function testCallComposersDoesDispatchEventsWhenIsNecessaryUsingNormalize { $factory = $this->getFactory(); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher() ->expects('listen') - ->with('composing: components.button', m::type(Closure::class)); + ->with('composing: components.button', Argument::type(Closure::class)); $factory->getDispatcher() ->expects('dispatch') - ->with('composing: components/button', m::type('array')); + ->with('composing: components/button', Argument::type('array')); - $view = m::mock(View::class); - $view->expects('name')->andReturn('components/button'); + $view = Double::for(View::class); + $view->expects('name')->returns('components/button'); $factory->composer('components.button', fn () => true); @@ -496,7 +486,7 @@ public function testCallComposersDoesDispatchEventsWhenIsNecessaryUsingNormalize public function testComposersAreProperlyRegistered(): void { $factory = $this->getFactory(); - $factory->getDispatcher()->expects('listen')->with('composing: foo', m::type(Closure::class)); + $factory->getDispatcher()->expects('listen')->with('composing: foo', Argument::type(Closure::class)); $callback = $factory->composer('foo', function () { return 'bar'; }); @@ -508,9 +498,9 @@ public function testComposersAreProperlyRegistered(): void public function testComposersCanBeMassRegistered(): void { $factory = $this->getFactory(); - $factory->getDispatcher()->expects('listen')->with('composing: bar', m::type(Closure::class)); - $factory->getDispatcher()->expects('listen')->with('composing: qux', m::type(Closure::class)); - $factory->getDispatcher()->expects('listen')->with('composing: foo', m::type(Closure::class)); + $factory->getDispatcher()->expects('listen')->with('composing: bar', Argument::type(Closure::class)); + $factory->getDispatcher()->expects('listen')->with('composing: qux', Argument::type(Closure::class)); + $factory->getDispatcher()->expects('listen')->with('composing: foo', Argument::type(Closure::class)); $composers = $factory->composers([ 'foo' => 'bar', 'baz@baz' => ['qux', 'foo'], @@ -528,7 +518,7 @@ public function testComposersCanBeMassRegistered(): void public function testClassCallbacks(): void { $factory = $this->getFactory(); - $factory->getDispatcher()->expects('listen')->with('composing: foo', m::type(Closure::class)); + $factory->getDispatcher()->expects('listen')->with('composing: foo', Argument::type(Closure::class)); $factory->setContainer(new ContainerInstance); $callback = $factory->composer('foo', ViewComposerStub::class); $callback = $callback[0]; @@ -539,7 +529,7 @@ public function testClassCallbacks(): void public function testClassCallbacksWithMethods(): void { $factory = $this->getFactory(); - $factory->getDispatcher()->expects('listen')->with('composing: foo', m::type(Closure::class)); + $factory->getDispatcher()->expects('listen')->with('composing: foo', Argument::type(Closure::class)); $factory->setContainer(new ContainerInstance); $callback = $factory->composer('foo', ViewComposerStub::class . '@doComposer'); $callback = $callback[0]; @@ -550,17 +540,17 @@ public function testClassCallbacksWithMethods(): void public function testCallComposerCallsProperEvent(): void { $factory = $this->getFactory(); - $view = m::mock(View::class); - $dispatcher = m::mock(DispatcherContract::class); + $view = Double::for(View::class); + $dispatcher = Double::for(DispatcherContract::class); $factory->setDispatcher($dispatcher); - $dispatcher->expects('listen')->with('composing: name', m::type(Closure::class)); + $dispatcher->expects('listen')->with('composing: name', Argument::type(Closure::class)); - $view->expects('name')->andReturn('name'); + $view->expects('name')->returns('name'); $factory->composer('name', fn () => true); - $factory->getDispatcher()->expects('hasListeners')->andReturn(true); + $factory->getDispatcher()->expects('hasListeners')->returns(true); $factory->getDispatcher()->expects('dispatch')->with('composing: name', [$view]); $factory->callComposer($view); @@ -569,7 +559,7 @@ public function testCallComposerCallsProperEvent(): void public function testComposersAreRegisteredWithSlashAndDot(): void { $factory = $this->getFactory(); - $factory->getDispatcher()->expects('listen')->with('composing: foo.bar', m::any())->times(2); + $factory->getDispatcher()->expects('listen')->with('composing: foo.bar', Argument::any())->times(2); $factory->composer('foo.bar', ''); $factory->composer('foo/bar', ''); } @@ -598,19 +588,19 @@ public function testYieldDefaultIsEscaped(): void public function testYieldDefaultViewIsNotEscapedTwice(): void { $factory = $this->getFactory(); - $view = m::mock(View::class); - $view->expects('render')->andReturn('

hi

<p>already escaped</p>'); + $view = Double::for(View::class); + $view->expects('render')->returns('

hi

<p>already escaped</p>'); $this->assertSame('

hi

<p>already escaped</p>', $factory->yieldContent('foo', $view)); } public function testExistingSectionDoesNotRenderDefaultView(): void { $factory = $this->getFactory(); - $factory->getDispatcher()->shouldReceive('hasListeners')->andReturn(false); + $factory->getDispatcher()->allows('hasListeners')->returns(false); $factory->startSection('foo', 'section'); - $engine = m::mock(Engine::class); - $engine->allows('get')->andReturnUsing(function () use ($factory): string { + $engine = Double::for(Engine::class); + $engine->allows('get')->resolves(function () use ($factory): string { $factory->startPush('default'); echo 'unused'; $factory->stopPush(); @@ -667,8 +657,8 @@ public function testBasicSectionDefaultIsEscaped(): void public function testBasicSectionDefaultViewIsNotEscapedTwice(): void { $factory = $this->getFactory(); - $view = m::mock(View::class); - $view->expects('render')->andReturn('

hi

<p>already escaped</p>'); + $view = Double::for(View::class); + $view->expects('render')->returns('

hi

<p>already escaped</p>'); $factory->startSection('foo', $view); $this->assertSame('

hi

<p>already escaped</p>', $factory->getSections()['foo']); $this->assertSame('

hi

<p>already escaped</p>', $factory->yieldContent('foo')); @@ -709,9 +699,9 @@ public function testSectionMultipleExtending(): void public function testComponentHandling(): void { $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->andReturn(__DIR__ . '/Fixtures/component.php'); - $factory->getEngineResolver()->expects('resolve')->andReturn(new PhpEngine(new Filesystem)); - $factory->getDispatcher()->expects('hasListeners')->times(2)->andReturn(false); + $factory->getFinder()->expects('find')->returns(__DIR__ . '/Fixtures/component.php'); + $factory->getEngineResolver()->expects('resolve')->returns(new PhpEngine(new Filesystem)); + $factory->getDispatcher()->expects('hasListeners')->times(2)->returns(false); $factory->startComponent('component', ['name' => 'Taylor']); $factory->slot('title'); @@ -726,9 +716,9 @@ public function testComponentHandling(): void public function testComponentHandlingUsingViewObject(): void { $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->andReturn(__DIR__ . '/Fixtures/component.php'); - $factory->getEngineResolver()->expects('resolve')->andReturn(new PhpEngine(new Filesystem)); - $factory->getDispatcher()->expects('hasListeners')->times(2)->andReturn(false); + $factory->getFinder()->expects('find')->returns(__DIR__ . '/Fixtures/component.php'); + $factory->getEngineResolver()->expects('resolve')->returns(new PhpEngine(new Filesystem)); + $factory->getDispatcher()->expects('hasListeners')->times(2)->returns(false); $factory->startComponent($factory->make('component'), ['name' => 'Taylor']); $factory->slot('title'); @@ -743,9 +733,9 @@ public function testComponentHandlingUsingViewObject(): void public function testComponentHandlingUsingClosure(): void { $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->andReturn(__DIR__ . '/Fixtures/component.php'); - $factory->getEngineResolver()->expects('resolve')->andReturn(new PhpEngine(new Filesystem)); - $factory->getDispatcher()->expects('hasListeners')->times(2)->andReturn(false); + $factory->getFinder()->expects('find')->returns(__DIR__ . '/Fixtures/component.php'); + $factory->getEngineResolver()->expects('resolve')->returns(new PhpEngine(new Filesystem)); + $factory->getDispatcher()->expects('hasListeners')->times(2)->returns(false); $factory->startComponent(function (array $data) use ($factory): ViewContract { $this->assertArrayHasKey('name', $data); $this->assertSame('Taylor', $data['name']); @@ -791,8 +781,8 @@ public function testFlushStateResetsSlots(): void public function testTranslation(): void { $container = new ContainerInstance; - $translator = m::mock(Translator::class); - $translator->expects('get')->with('Foo', ['name' => 'taylor'])->andReturn('Bar'); + $translator = Double::for(Translator::class); + $translator->expects('get')->with('Foo', ['name' => 'taylor'])->returns('Bar'); $container->instance('translator', $translator); $factory = $this->getFactory(); $factory->setContainer($container); @@ -936,10 +926,9 @@ public function testGetSection(): void public function testMakeWithSlashAndDot(): void { $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->times(2)->with('foo.bar')->andReturn('path.php'); - $factory->getEngineResolver()->expects('resolve')->times(2)->with('php')->andReturn(m::mock(Engine::class)); - $factory->getDispatcher()->expects('hasListeners')->times(2)->andReturn(false); - $factory->setContainer(m::mock(Container::class)); + $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->getDispatcher()->expects('hasListeners')->times(2)->returns(false); $factory->make('foo/bar'); $factory->make('foo.bar'); } @@ -947,10 +936,9 @@ public function testMakeWithSlashAndDot(): void public function testNamespacedViewNamesAreNormalizedProperly(): void { $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->times(2)->with('vendor/package::foo.bar')->andReturn('path.php'); - $factory->getEngineResolver()->expects('resolve')->times(2)->with('php')->andReturn(m::mock(Engine::class)); - $factory->getDispatcher()->expects('hasListeners')->times(2)->andReturn(false); - $factory->setContainer(m::mock(Container::class)); + $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->getDispatcher()->expects('hasListeners')->times(2)->returns(false); $factory->make('vendor/package::foo/bar'); $factory->make('vendor/package::foo.bar'); } @@ -960,7 +948,7 @@ public function testExceptionIsThrownForUnknownExtension(): void $this->expectException(InvalidArgumentException::class); $factory = $this->getFactory(); - $factory->getFinder()->expects('find')->with('view')->andReturn('view.foo'); + $factory->getFinder()->expects('find')->with('view')->returns('view.foo'); $factory->make('view'); } @@ -968,15 +956,15 @@ public function testExceptionsInSectionsAreThrown(): void { $this->expectExceptionObject(new ErrorException('section exception message')); - $engine = new CompilerEngine(m::mock(CompilerInterface::class), new Filesystem); - $engine->getCompiler()->expects('getCompiledPath')->times(2)->andReturnUsing(function (string $path): string { + $engine = new CompilerEngine(Double::for(CompilerInterface::class), new Filesystem); + $engine->getCompiler()->expects('getCompiledPath')->times(2)->resolves(function (string $path): string { return $path; }); - $engine->getCompiler()->expects('isExpired')->times(2)->andReturn(false); + $engine->getCompiler()->expects('isExpired')->times(2)->returns(false); $factory = $this->getFactory(); - $factory->getEngineResolver()->expects('resolve')->times(2)->andReturn($engine); - $factory->getFinder()->expects('find')->with('layout')->andReturn(__DIR__ . '/Fixtures/section-exception-layout.php'); - $factory->getFinder()->expects('find')->with('view')->andReturn(__DIR__ . '/Fixtures/section-exception.php'); + $factory->getEngineResolver()->expects('resolve')->times(2)->returns($engine); + $factory->getFinder()->expects('find')->with('layout')->returns(__DIR__ . '/Fixtures/section-exception-layout.php'); + $factory->getFinder()->expects('find')->with('view')->returns(__DIR__ . '/Fixtures/section-exception.php'); $factory->getDispatcher()->expects('hasListeners')->times(4); // 2 "creating" + 2 "composing"... $factory->make('view')->render(); @@ -1180,10 +1168,10 @@ public function testIncrementingLoopIndicesOfUncountable(): void public function testFailedRenderFlushesLoopState(): void { $factory = $this->getFactory(); - $factory->getDispatcher()->shouldReceive('hasListeners')->andReturn(false); + $factory->getDispatcher()->allows('hasListeners')->returns(false); - $engine = m::mock(Engine::class); - $engine->expects('get')->andReturnUsing(function () use ($factory): never { + $engine = Double::for(Engine::class); + $engine->expects('get')->resolves(function () use ($factory): never { $factory->addLoop([1]); throw new RuntimeException('render failed'); @@ -1214,9 +1202,9 @@ public function testMacro(): void protected function getFactory(): Factory { return new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - m::mock(DispatcherContract::class) + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + Double::for(DispatcherContract::class) ); } @@ -1228,9 +1216,9 @@ protected function getFactory(): Factory protected function getFactoryArgs(): array { return [ - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - m::mock(DispatcherContract::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + Double::for(DispatcherContract::class), ]; } } diff --git a/tests/View/ViewFileViewFinderTest.php b/tests/View/ViewFileViewFinderTest.php index e6a527208..c38d77053 100755 --- a/tests/View/ViewFileViewFinderTest.php +++ b/tests/View/ViewFileViewFinderTest.php @@ -8,15 +8,18 @@ use Hypervel\Tests\TestCase; use Hypervel\View\FileViewFinder; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class ViewFileViewFinderTest extends TestCase { + use VerifiesDoubles; + public function testBasicViewFinding(): void { $finder = $this->getFinder(); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.blade.php')->andReturn(true); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.blade.php')->returns(true); $this->assertEquals(__DIR__ . '/foo.blade.php', $finder->find(view: 'foo')); } @@ -24,8 +27,8 @@ public function testBasicViewFinding(): void public function testCascadingFileLoading(): void { $finder = $this->getFinder(); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.blade.php')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.php')->andReturn(true); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.blade.php')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.php')->returns(true); $this->assertEquals(__DIR__ . '/foo.php', $finder->find('foo')); } @@ -34,11 +37,11 @@ public function testDirectoryCascadingFileLoading(): void { $finder = $this->getFinder(); $finder->addLocation(__DIR__ . '/nested'); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.blade.php')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.php')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.css')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.html')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/nested/foo.blade.php')->andReturn(true); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.blade.php')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.php')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.css')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.html')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/nested/foo.blade.php')->returns(true); $this->assertEquals(__DIR__ . '/nested/foo.blade.php', $finder->find('foo')); } @@ -47,7 +50,7 @@ public function testNamespacedBasicFileLoading(): void { $finder = $this->getFinder(); $finder->addNamespace('foo', __DIR__ . '/foo'); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.blade.php')->andReturn(true); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.blade.php')->returns(true); $this->assertEquals(__DIR__ . '/foo/bar/baz.blade.php', $finder->find('foo::bar.baz')); } @@ -56,8 +59,8 @@ public function testCascadingNamespacedFileLoading(): void { $finder = $this->getFinder(); $finder->addNamespace('foo', __DIR__ . '/foo'); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.blade.php')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.php')->andReturn(true); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.blade.php')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.php')->returns(true); $this->assertEquals(__DIR__ . '/foo/bar/baz.php', $finder->find('foo::bar.baz')); } @@ -66,11 +69,11 @@ public function testDirectoryCascadingNamespacedFileLoading(): void { $finder = $this->getFinder(); $finder->addNamespace('foo', [__DIR__ . '/foo', __DIR__ . '/bar']); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.blade.php')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.php')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.css')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.html')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/bar/bar/baz.blade.php')->andReturn(true); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.blade.php')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.php')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.css')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo/bar/baz.html')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/bar/bar/baz.blade.php')->returns(true); $this->assertEquals(__DIR__ . '/bar/bar/baz.blade.php', $finder->find('foo::bar.baz')); } @@ -80,10 +83,10 @@ public function testExceptionThrownWhenViewNotFound(): void $this->expectException(InvalidArgumentException::class); $finder = $this->getFinder(); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.blade.php')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.php')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.css')->andReturn(false); - $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.html')->andReturn(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.blade.php')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.php')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.css')->returns(false); + $finder->getFilesystem()->expects('exists')->with(__DIR__ . '/foo.html')->returns(false); $finder->find('foo'); } @@ -179,6 +182,6 @@ public function testNormalizedNamespaceHints(): void */ protected function getFinder(): FileViewFinder { - return new FileViewFinder(m::mock(Filesystem::class), [__DIR__]); + return new FileViewFinder(Double::for(Filesystem::class), [__DIR__]); } } diff --git a/tests/View/ViewTest.php b/tests/View/ViewTest.php index 28b13831a..044c7ffd5 100755 --- a/tests/View/ViewTest.php +++ b/tests/View/ViewTest.php @@ -19,8 +19,9 @@ use Hypervel\View\Factory; use Hypervel\View\View; use Hypervel\View\ViewFinderInterface; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -28,6 +29,8 @@ class ViewTest extends TestCase { + use VerifiesDoubles; + public function testDataCanBeSetOnView(): void { $view = $this->getView(); @@ -46,9 +49,9 @@ public function testRenderProperlyRendersView(): void $view->getFactory()->expects('incrementRender')->ordered(); $view->getFactory()->expects('callComposer')->ordered()->with($view); $view->getFactory()->expects('notifyRendering')->ordered()->with($view); - $view->getFactory()->shouldNotReceive('notifyRendered'); - $view->getFactory()->expects('mergeSharedData')->with(['foo' => 'bar'])->andReturn(['foo' => 'bar', 'shared' => 'foo']); - $view->getEngine()->expects('get')->with('path', ['foo' => 'bar', 'shared' => 'foo'])->andReturn('contents'); + $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'); $view->getFactory()->expects('decrementRender')->ordered(); $view->getFactory()->expects('flushStateIfDoneRendering'); @@ -69,8 +72,8 @@ public function testRenderPreservesCancellationWhileFlushingFactoryState(): void $view->getFactory()->expects('incrementRender'); $view->getFactory()->expects('callComposer')->with($view); $view->getFactory()->expects('notifyRendering')->with($view); - $view->getFactory()->expects('mergeSharedData')->with([])->andReturn([]); - $view->getEngine()->expects('get')->with('path', [])->andThrow($cancellation); + $view->getFactory()->expects('mergeSharedData')->with([])->returns([]); + $view->getEngine()->expects('get')->with('path', [])->throws($cancellation); $view->getFactory()->expects('flushState'); try { @@ -87,8 +90,8 @@ public function testRenderHandlingCallbackReturnValues(): void $view->getFactory()->expects('incrementRender')->times(4); $view->getFactory()->expects('callComposer')->times(4); $view->getFactory()->expects('notifyRendering')->times(4)->with($view); - $view->getFactory()->expects('mergeSharedData')->times(4)->with([])->andReturn(['shared' => 'foo']); - $view->getEngine()->expects('get')->times(4)->andReturn('contents'); + $view->getFactory()->expects('mergeSharedData')->times(4)->with([])->returns(['shared' => 'foo']); + $view->getEngine()->expects('get')->times(4)->returns('contents'); $view->getFactory()->expects('decrementRender')->times(4); $view->getFactory()->expects('flushStateIfDoneRendering')->times(4); @@ -112,14 +115,14 @@ public function testRenderHandlingCallbackReturnValues(): void public function testRenderSectionsReturnsEnvironmentSections(): void { $view = new TestView( - $factory = m::mock(Factory::class), - m::mock(Engine::class), + $factory = Double::for(Factory::class), + Double::for(Engine::class), 'view', 'path', [], ); - $factory->expects('getSections')->with()->andReturn($sections = ['foo' => 'bar']); + $factory->expects('getSections')->with()->returns($sections = ['foo' => 'bar']); $factory->expects('flushStateIfDoneRendering')->with(); $this->assertEquals($sections, $view->renderSections()); @@ -128,13 +131,13 @@ public function testRenderSectionsReturnsEnvironmentSections(): void public function testSectionsAreNotFlushedWhenNotDoneRendering(): void { $view = $this->getView(['foo' => 'bar']); - $view->getFactory()->expects('incrementRender')->twice(); - $view->getFactory()->expects('callComposer')->twice()->with($view); - $view->getFactory()->expects('notifyRendering')->twice()->with($view); - $view->getFactory()->expects('mergeSharedData')->twice()->with(['foo' => 'bar'])->andReturn(['foo' => 'bar', 'shared' => 'foo']); - $view->getEngine()->expects('get')->twice()->with('path', ['foo' => 'bar', 'shared' => 'foo'])->andReturn('contents'); - $view->getFactory()->expects('decrementRender')->twice(); - $view->getFactory()->expects('flushStateIfDoneRendering')->twice(); + $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('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); + $view->getFactory()->expects('flushStateIfDoneRendering')->times(2); $this->assertSame('contents', $view->render()); $this->assertSame('contents', (string) $view); @@ -229,13 +232,13 @@ public function testViewGatherDataWithRenderable(): void $view->getFactory()->expects('incrementRender')->ordered(); $view->getFactory()->expects('callComposer')->ordered()->with($view); $view->getFactory()->expects('notifyRendering')->ordered()->with($view); - $view->getEngine()->expects('get')->andReturn('contents'); + $view->getEngine()->expects('get')->returns('contents'); $view->getFactory()->expects('decrementRender')->ordered(); $view->getFactory()->expects('flushStateIfDoneRendering'); - $view->renderable = m::mock(Renderable::class); - $view->renderable->expects('render')->andReturn('text'); - $view->getFactory()->expects('mergeSharedData')->with(['renderable' => $view->renderable])->andReturn([ + $view->renderable = Double::for(Renderable::class); + $view->renderable->expects('render')->returns('text'); + $view->getFactory()->expects('mergeSharedData')->with(['renderable' => $view->renderable])->returns([ 'shared' => 'foo', 'renderable' => $view->renderable, ]); @@ -248,12 +251,12 @@ public function testViewRenderSections(): void $view->getFactory()->expects('incrementRender')->ordered(); $view->getFactory()->expects('callComposer')->ordered()->with($view); $view->getFactory()->expects('notifyRendering')->ordered()->with($view); - $view->getFactory()->expects('mergeSharedData')->with([])->andReturn(['shared' => 'foo']); - $view->getEngine()->expects('get')->andReturn('contents'); + $view->getFactory()->expects('mergeSharedData')->with([])->returns(['shared' => 'foo']); + $view->getEngine()->expects('get')->returns('contents'); $view->getFactory()->expects('decrementRender')->ordered(); $view->getFactory()->expects('flushStateIfDoneRendering'); - $view->getFactory()->expects('getSections')->andReturn(['foo', 'bar']); + $view->getFactory()->expects('getSections')->returns(['foo', 'bar']); $sections = $view->renderSections(); $this->assertSame('foo', $sections[0]); $this->assertSame('bar', $sections[1]); @@ -283,9 +286,9 @@ public function testWithErrors(): void public function testRenderingObserverIsCalled(): void { $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $observedView = null; @@ -293,9 +296,9 @@ public function testRenderingObserverIsCalled(): void $observedView = $view; }); - $engine = m::mock(Engine::class); - $engine->expects('get')->andReturn('contents'); - $events->shouldReceive('hasListeners')->andReturn(false); + $engine = Double::for(Engine::class); + $engine->expects('get')->returns('contents'); + $events->allows('hasListeners')->returns(false); $view = new View($factory, $engine, 'test', 'path'); $view->render(); @@ -306,9 +309,9 @@ public function testRenderingObserverIsCalled(): void public function testRenderingObserversNotClearedByFlushState(): void { $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $observerCalled = false; @@ -318,9 +321,9 @@ public function testRenderingObserversNotClearedByFlushState(): void $factory->flushState(); - $engine = m::mock(Engine::class); - $engine->expects('get')->andReturn('contents'); - $events->shouldReceive('hasListeners')->andReturn(false); + $engine = Double::for(Engine::class); + $engine->expects('get')->returns('contents'); + $events->allows('hasListeners')->returns(false); $view = new View($factory, $engine, 'test', 'path'); $view->render(); @@ -331,9 +334,9 @@ public function testRenderingObserversNotClearedByFlushState(): void public function testMultipleRenderingObserversAreAllCalled(): void { $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $order = []; @@ -344,9 +347,9 @@ public function testMultipleRenderingObserversAreAllCalled(): void $order[] = 'second'; }); - $engine = m::mock(Engine::class); - $engine->expects('get')->andReturn('contents'); - $events->shouldReceive('hasListeners')->andReturn(false); + $engine = Double::for(Engine::class); + $engine->expects('get')->returns('contents'); + $events->allows('hasListeners')->returns(false); $view = new View($factory, $engine, 'test', 'path'); $view->render(); @@ -357,9 +360,9 @@ public function testMultipleRenderingObserversAreAllCalled(): void public function testRenderedObserverRunsAfterEngineAtTheSameRenderDepth(): void { $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $order = []; @@ -376,13 +379,13 @@ public function testRenderedObserverRunsAfterEngineAtTheSameRenderDepth(): void $this->assertFalse($factory->doneRendering()); }); - $engine = m::mock(Engine::class); - $engine->expects('get')->andReturnUsing(function () use (&$order): string { + $engine = Double::for(Engine::class); + $engine->expects('get')->resolves(function () use (&$order): string { $order[] = 'engine'; return 'contents'; }); - $events->shouldReceive('hasListeners')->andReturnFalse(); + $events->allows('hasListeners')->returns(false); $view = new View($factory, $engine, 'test', 'path'); @@ -396,9 +399,9 @@ public function testRenderedObserverRunsAfterEngineAtTheSameRenderDepth(): void public function testRenderSectionsUsesCompletionObservers(): void { $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $order = []; @@ -412,13 +415,13 @@ public function testRenderSectionsUsesCompletionObservers(): void $this->assertNull($exception); }); - $engine = m::mock(Engine::class); - $engine->expects('get')->andReturnUsing(function () use (&$order): string { + $engine = Double::for(Engine::class); + $engine->expects('get')->resolves(function () use (&$order): string { $order[] = 'engine'; return 'contents'; }); - $events->shouldReceive('hasListeners')->andReturnFalse(); + $events->allows('hasListeners')->returns(false); $this->assertSame([], (new View($factory, $engine, 'test', 'path'))->renderSections()); $this->assertSame(['rendering', 'engine', 'rendered'], $order); @@ -431,9 +434,9 @@ public function testRenderingFailureRemainsPrimaryAfterEveryRenderedObserverRuns $renderingException = new RuntimeException('rendering failed'); $completionException = new RuntimeException('completion failed'); $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $observed = []; @@ -453,11 +456,11 @@ public function testRenderingFailureRemainsPrimaryAfterEveryRenderedObserverRuns } }); - $engine = m::mock(Engine::class); - $engine->shouldNotReceive('get'); - $events->shouldReceive('hasListeners')->andReturnFalse(); + $engine = Double::for(Engine::class); + $engine->expects('get')->never(); + $events->allows('hasListeners')->returns(false); $reported = []; - $this->bindReportingHandler()->shouldReceive('report')->andReturnUsing(function (Throwable $throwable) use (&$reported): void { + $this->bindReportingHandler()->allows('report')->resolves(function (Throwable $throwable) use (&$reported): void { $reported[] = $throwable; }); @@ -477,9 +480,9 @@ public function testEngineFailureIsPassedToRenderedObservers(): void { $renderingException = new RuntimeException('engine failed'); $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $observedException = null; @@ -487,9 +490,9 @@ public function testEngineFailureIsPassedToRenderedObservers(): void $observedException = $exception; }); - $engine = m::mock(Engine::class); - $engine->expects('get')->andThrow($renderingException); - $events->shouldReceive('hasListeners')->andReturnFalse(); + $engine = Double::for(Engine::class); + $engine->expects('get')->throws($renderingException); + $events->allows('hasListeners')->returns(false); try { (new View($factory, $engine, 'test', 'path'))->render(); @@ -506,9 +509,9 @@ public function testFirstRenderedObserverFailureIsThrownAfterEveryObserverRunsAn $firstException = new RuntimeException('first completion failed'); $secondException = new RuntimeException('second completion failed'); $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $order = []; @@ -526,10 +529,10 @@ public function testFirstRenderedObserverFailureIsThrownAfterEveryObserverRunsAn $order[] = 'third'; }); - $engine = m::mock(Engine::class); - $engine->expects('get')->andReturn('contents'); - $events->shouldReceive('hasListeners')->andReturnFalse(); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($secondException); + $engine = Double::for(Engine::class); + $engine->expects('get')->returns('contents'); + $events->allows('hasListeners')->returns(false); + $this->bindReportingHandler()->expects('report')->with($secondException); try { (new View($factory, $engine, 'test', 'path'))->render(); @@ -550,9 +553,9 @@ public function testPreRenderCancellationIsPassedToCompletionObserversAndClearsS $cancellation = new RuntimeException('Render cleanup failed.', previous: $cancellation); } $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $factory->inject('content', 'value'); @@ -565,9 +568,9 @@ public function testPreRenderCancellationIsPassedToCompletionObserversAndClearsS $observed = $exception; }); - $engine = m::mock(Engine::class); - $engine->shouldNotReceive('get'); - $events->shouldReceive('hasListeners')->andReturnFalse(); + $engine = Double::for(Engine::class); + $engine->expects('get')->never(); + $events->allows('hasListeners')->returns(false); try { (new View($factory, $engine, 'test', 'path'))->render(); @@ -591,9 +594,9 @@ public function testRenderSectionsEngineCancellationIsPassedToCompletionObserver $cancellation = new RuntimeException('Engine cleanup failed.', previous: $cancellation); } $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $observed = null; @@ -601,9 +604,9 @@ public function testRenderSectionsEngineCancellationIsPassedToCompletionObserver $observed = $exception; }); - $engine = m::mock(Engine::class); - $engine->expects('get')->andThrow($cancellation); - $events->shouldReceive('hasListeners')->andReturnFalse(); + $engine = Double::for(Engine::class); + $engine->expects('get')->throws($cancellation); + $events->allows('hasListeners')->returns(false); try { (new View($factory, $engine, 'test', 'path'))->renderSections(); @@ -625,9 +628,9 @@ public function testRenderedObserverCancellationNotifiesRemainingObserversAndRep $cancellation = new RuntimeException('Observer cleanup failed.', previous: $cancellation); } $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $order = []; @@ -642,10 +645,10 @@ public function testRenderedObserverCancellationNotifiesRemainingObserversAndRep $order[] = 'second'; }); - $engine = m::mock(Engine::class); - $engine->expects('get')->andReturn('contents'); - $events->shouldReceive('hasListeners')->andReturnFalse(); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($earlierFailure); + $engine = Double::for(Engine::class); + $engine->expects('get')->returns('contents'); + $events->allows('hasListeners')->returns(false); + $this->bindReportingHandler()->expects('report')->with($earlierFailure); try { (new View($factory, $engine, 'test', 'path'))->render(); @@ -667,9 +670,9 @@ public function testRenderedObserverCancellationSupersedesAndReportsTheRendering $cancellation = new RuntimeException('Observer cleanup failed.', previous: $cancellation); } $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $factory->observeRendering(function () use ($renderingException): never { @@ -681,10 +684,10 @@ public function testRenderedObserverCancellationSupersedesAndReportsTheRendering throw $cancellation; }); - $engine = m::mock(Engine::class); - $engine->shouldNotReceive('get'); - $events->shouldReceive('hasListeners')->andReturnFalse(); - $this->bindReportingHandler()->shouldReceive('report')->once()->with($renderingException); + $engine = Double::for(Engine::class); + $engine->expects('get')->never(); + $events->allows('hasListeners')->returns(false); + $this->bindReportingHandler()->expects('report')->with($renderingException); try { (new View($factory, $engine, 'test', 'path'))->render(); @@ -697,9 +700,9 @@ public function testRenderedObserverCancellationSupersedesAndReportsTheRendering public function testRenderedObserversAreNotClearedByFlushState(): void { $factory = new Factory( - m::mock(EngineResolver::class), - m::mock(ViewFinderInterface::class), - $events = m::mock(Dispatcher::class), + Double::for(EngineResolver::class), + Double::for(ViewFinderInterface::class), + $events = Double::for(Dispatcher::class), ); $observerCalled = false; @@ -708,9 +711,9 @@ public function testRenderedObserversAreNotClearedByFlushState(): void }); $factory->flushState(); - $engine = m::mock(Engine::class); - $engine->expects('get')->andReturn('contents'); - $events->shouldReceive('hasListeners')->andReturnFalse(); + $engine = Double::for(Engine::class); + $engine->expects('get')->returns('contents'); + $events->allows('hasListeners')->returns(false); (new View($factory, $engine, 'test', 'path'))->render(); @@ -722,12 +725,12 @@ public function testRenderedObserversAreNotClearedByFlushState(): void */ protected function getView(mixed $data = []): View { - $factory = m::mock(Factory::class); - $factory->shouldReceive('hasRenderedObservers')->andReturnFalse()->byDefault(); + $factory = Double::for(Factory::class); + $factory->allows('hasRenderedObservers')->returns(false); return new View( $factory, - m::mock(Engine::class), + Double::for(Engine::class), 'view', 'path', $data @@ -737,11 +740,11 @@ protected function getView(mixed $data = []): View /** * Bind a mocked exception handler for displaced failure reports. */ - private function bindReportingHandler(): MockInterface + private function bindReportingHandler(): ExceptionHandler&DoubleInterface { $container = new Container; Container::setInstance($container); - $handler = m::mock(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class); $container->instance(ExceptionHandler::class, $handler); return $handler; From 5568bb0030a79b001caf1065633a533c74e6a5d0 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:21:45 +0000 Subject: [PATCH 8/8] test: retain behavioral coverage after Double conversion Exercise translation registration both before and after translator resolution, and verify that changing a password during an authenticated request refreshes the stored session hash. Validate serialized SQS command names and restored job types, with a concrete message-group state assertion. Require the nullable route lookups so lenient defaults cannot hide a wrong parameter, and inspect unmatched relationship state without lazy-loading it. Make the existing attach-touch test distinguish creation and attachment timestamps. Clarify that backdated Redis membership scores isolate expiry pruning from orphan cleanup rather than adding duplicate scan instrumentation. Validation: all seven changed test classes pass, including isolated Redis integration coverage. Formatting and whitespace checks pass; production code is unchanged. --- .../ContextualAttributeBindingTest.php | 4 +-- .../DatabaseEloquentIntegrationTest.php | 2 +- .../Cache/Redis/RedisStoreTest.php | 3 ++- .../Database/EloquentBelongsToManyTest.php | 6 ++++- .../Session/AuthenticateSessionTest.php | 21 ++++++++++++++++ tests/Queue/QueueSqsQueueTest.php | 16 +++++++++--- tests/Support/SupportServiceProviderTest.php | 25 ++++++++++++++++--- 7 files changed, 65 insertions(+), 12 deletions(-) diff --git a/tests/Container/ContextualAttributeBindingTest.php b/tests/Container/ContextualAttributeBindingTest.php index 15cafbb1e..bab66f9d2 100644 --- a/tests/Container/ContextualAttributeBindingTest.php +++ b/tests/Container/ContextualAttributeBindingTest.php @@ -433,8 +433,8 @@ public function testRouteParameterCanExtractSupportedPropertyPaths(): void $request->allows('route')->with('array-access')->returns(new ArrayObject(['id' => 20])); $request->allows('route')->with('object')->returns((object) ['nested' => (object) ['id' => 30]]); $request->allows('route')->with('model')->returns($model); - $request->allows('route')->with('missing')->returns(['other' => 50]); - $request->allows('route')->with('null')->returns(null); + $request->expects('route')->with('missing')->returns(['other' => 50]); + $request->expects('route')->with('null')->returns(null); $container->singleton('request', fn (): Request => $request->instance()); $resolved = $container->make(RouteParameterPropertyTest::class); diff --git a/tests/Database/DatabaseEloquentIntegrationTest.php b/tests/Database/DatabaseEloquentIntegrationTest.php index b2d32f061..da055957b 100644 --- a/tests/Database/DatabaseEloquentIntegrationTest.php +++ b/tests/Database/DatabaseEloquentIntegrationTest.php @@ -496,7 +496,7 @@ public function testBelongsToManyMatchesStringablePivotKeysToTheirParents(): voi $this->assertSame(1, $models[0]->friends->count()); $this->assertContains($result, $models[0]->friends); - $this->assertCount(0, $models[1]->friends); + $this->assertFalse($models[1]->relationLoaded('friends')); } public function testBelongsToManyWithPivotValuesFiltersAndInsertsDefaults(): void diff --git a/tests/Integration/Cache/Redis/RedisStoreTest.php b/tests/Integration/Cache/Redis/RedisStoreTest.php index 34637b830..0eb6f4f32 100644 --- a/tests/Integration/Cache/Redis/RedisStoreTest.php +++ b/tests/Integration/Cache/Redis/RedisStoreTest.php @@ -394,7 +394,8 @@ public function testFlushStaleTagsRemovesExpiredEntriesAndStopsScanning(): void $store->clear(); - // An entry that expired five minutes ago, and one that is still fresh... + // Backdate membership scores while leaving Redis values alive, so pruning + // must remove expired scores rather than relying on orphan cleanup. CarbonImmutable::setTestNow(CarbonImmutable::now()->subMinutes(5)); try { diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 4d6ee9be9..7499e0cd1 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -1080,13 +1080,17 @@ public function testToggleMethod(): void public function testTouchingParent(): void { + CarbonImmutable::setTestNow('2017-10-10 08:10:10'); + $post = Post::create(['title' => Str::random()]); $tag = TouchingTag::create(['name' => Str::random()]); + CarbonImmutable::setTestNow('2017-10-10 09:10:10'); + $post->touchingTags()->attach([$tag->id]); - $this->assertNotSame('2017-10-10 10:10:10', $post->fresh()->updated_at->toDateTimeString()); + $this->assertSame('2017-10-10 09:10:10', $post->fresh()->updated_at->toDateTimeString()); CarbonImmutable::setTestNow('2017-10-10 10:10:10'); diff --git a/tests/Integration/Session/AuthenticateSessionTest.php b/tests/Integration/Session/AuthenticateSessionTest.php index beba3e7f9..ba111f38c 100644 --- a/tests/Integration/Session/AuthenticateSessionTest.php +++ b/tests/Integration/Session/AuthenticateSessionTest.php @@ -12,9 +12,11 @@ use Hypervel\Contracts\Http\Kernel; use Hypervel\Foundation\Auth\User; use Hypervel\Foundation\Testing\RefreshDatabase; +use Hypervel\Http\Request; use Hypervel\Routing\Router; use Hypervel\Session\Middleware\AuthenticateSession; use Hypervel\Support\Facades\Auth; +use Hypervel\Support\Facades\Hash; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\Attributes\WithMigration; use Hypervel\Testbench\Factories\UserFactory; @@ -91,6 +93,25 @@ public function testItStoresThePasswordHashInTheSession(): void ->assertSessionHas('password_hash_web', $this->hashFor($user)); } + public function testItRefreshesTheSessionHashAfterThePasswordChanges(): void + { + $user = UserFactory::new()->create(); + $originalHash = $this->hashFor($user); + $updatedPassword = Hash::make('updated-password'); + + $this->app->make(Router::class)->post('change-password', function (Request $request) use ($updatedPassword): string { + $request->user()->forceFill(['password' => $updatedPassword])->save(); + + return 'updated'; + })->middleware(['web', AuthenticateSession::class]); + + $response = $this->actingAs($user) + ->withSession(['password_hash_web' => $originalHash]) + ->post('change-password'); + + $response->assertOk()->assertSessionHas('password_hash_web', $this->hashFor($user->refresh())); + } + #[DataProvider('authenticatedRememberCookies')] public function testItKeepsTheSessionWhenThePasswordHashMatches(bool $malformedCookie): void { diff --git a/tests/Queue/QueueSqsQueueTest.php b/tests/Queue/QueueSqsQueueTest.php index 41cfeea5b..a9460890b 100644 --- a/tests/Queue/QueueSqsQueueTest.php +++ b/tests/Queue/QueueSqsQueueTest.php @@ -211,10 +211,18 @@ protected function expectSqsCommand(string $name, array|callable|null $parameter protected function isPayloadOf(string $job): Closure { return function (string $body) use ($job): bool { - $payload = json_decode($body, true); + $payload = json_decode($body, true, flags: JSON_THROW_ON_ERROR); - return ($payload['displayName'] ?? null) === $job - && (class_exists($job) || $payload['data'] === $this->mockedData); + if ($payload['displayName'] !== $job) { + return false; + } + + if (! class_exists($job)) { + return $payload['data'] === $this->mockedData; + } + + return $payload['data']['commandName'] === $job + && unserialize($payload['data']['command']) instanceof $job; }; } @@ -625,6 +633,8 @@ public function testPushProperlyPushesJobObjectOntoSqsFairQueue(): void $this->expectSqsCommand('sendMessage', ['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->isPayloadOf(FakeSqsJob::class), 'MessageGroupId' => $this->mockedMessageGroupId], $this->mockedSendMessageResponseModel); $id = $queue->push($job, $this->mockedData, $this->queueName); $this->assertEquals($this->mockedMessageId, $id); + $payload = json_decode($this->handler->getLastCommand()['MessageBody'], true, flags: JSON_THROW_ON_ERROR); + $this->assertSame($this->mockedMessageGroupId, unserialize($payload['data']['command'])->messageGroup); $container->received('bound')->with('events')->times(3); } diff --git a/tests/Support/SupportServiceProviderTest.php b/tests/Support/SupportServiceProviderTest.php index 721f80a24..db582fafd 100644 --- a/tests/Support/SupportServiceProviderTest.php +++ b/tests/Support/SupportServiceProviderTest.php @@ -15,6 +15,7 @@ use Hypervel\Translation\Translator; use JMac\Testing\Double; use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use PHPUnit\Framework\Attributes\TestWith; use WeakReference; class SupportServiceProviderTest extends TestCase @@ -549,26 +550,42 @@ public function testConfigureUsingSkipsWhenConfigIsCached(): void (new ServiceProviderForTestingComputed($app->instance()))->register(); } - public function testLoadTranslationsFromWithoutNamespace(): void + #[TestWith([false])] + #[TestWith([true])] + public function testLoadTranslationsFromWithoutNamespace(bool $alreadyResolved): void { $translator = Double::for(Translator::class); $translator->expects('addPath')->with(__DIR__ . '/translations'); - $this->app->instance('translator', $translator); + $this->app->singleton('translator', fn (): Translator => $translator); + + if ($alreadyResolved) { + $this->app->make('translator'); + } $provider = new ServiceProviderForTestingOne($this->app); $provider->loadTranslationsFrom(__DIR__ . '/translations'); + + $this->app->make('translator'); } - public function testLoadTranslationsFromWithNamespace(): void + #[TestWith([false])] + #[TestWith([true])] + public function testLoadTranslationsFromWithNamespace(bool $alreadyResolved): void { $translator = Double::for(Translator::class); $translator->expects('addNamespace')->with('namespace', __DIR__ . '/translations'); - $this->app->instance('translator', $translator); + $this->app->singleton('translator', fn (): Translator => $translator); + + if ($alreadyResolved) { + $this->app->make('translator'); + } $provider = new ServiceProviderForTestingOne($this->app); $provider->loadTranslationsFrom(__DIR__ . '/translations', 'namespace'); + + $this->app->make('translator'); } public function testCanRemoveProvider(): void