From 05ed4b1a6e37337f7be61ac7a25d56570294d5dc Mon Sep 17 00:00:00 2001 From: Christopher Gammie Date: Sat, 14 Nov 2026 11:35:13 +0000 Subject: [PATCH 1/3] refactor: use it_ test names, PHPUnit attributes and tearDown in all tests Add a unit-testing skill and convert every test to an it_ snake_case name with a #[Test] attribute. Unset setUp() properties in tearDown(). Co-Authored-By: Claude Opus 5.5 --- .claude/skills/unit-testing/SKILL.md | 313 ++++++++++++++++++ .../MathDomainEventDispatcherTest.php | 4 +- tests/Integration/Bus/MathCommandBusTest.php | 4 +- tests/Integration/Bus/MathEventBusTest.php | 4 +- tests/Integration/Bus/MathQueryBusTest.php | 4 +- .../MathEventPublisherTest.php | 4 +- .../TestClosurePublisherTest.php | 4 +- .../Infrastructure/Queue/MathQueueTest.php | 4 +- .../Queue/TestClosureQueueTest.php | 4 +- .../Application/ApplicationExceptionTest.php | 4 +- .../Application/Bus/CommandDispatcherTest.php | 7 +- .../Bus/CommandHandlerContainerTest.php | 7 +- .../Application/Bus/CommandHandlerTest.php | 7 +- .../Application/Bus/CommandQueuerTest.php | 4 +- .../Middleware/ExecuteInUnitOfWorkTest.php | 10 +- .../Middleware/FlushDeferredEventsTest.php | 16 +- .../Bus/Middleware/LogMessageDispatchTest.php | 12 +- .../Middleware/SetupBeforeDispatchTest.php | 19 +- .../Middleware/TearDownAfterDispatchTest.php | 10 +- .../Bus/Middleware/ValidateMessageTest.php | 19 +- .../Application/Bus/QueryDispatcherTest.php | 7 +- .../Bus/QueryHandlerContainerTest.php | 7 +- .../Unit/Application/Bus/QueryHandlerTest.php | 7 +- tests/Unit/Application/Bus/ValidatorTest.php | 13 +- .../DeferredDispatcherTest.php | 31 +- .../DomainEventDispatching/DispatcherTest.php | 19 +- .../ListenerContainerTest.php | 10 +- .../Middleware/LogDomainEventDispatchTest.php | 16 +- .../UnitOfWorkAwareDispatcherTest.php | 36 +- .../EventHandlerContainerTest.php | 16 +- .../InboundEventBus/EventHandlerTest.php | 7 +- .../InboundEventDispatcherTest.php | 7 +- .../Middleware/SetupBeforeEventTest.php | 13 +- .../Middleware/TearDownAfterEventTest.php | 7 +- .../SwallowInboundEventTest.php | 10 +- .../UnitOfWork/UnitOfWorkManagerTest.php | 43 ++- tests/Unit/Bus/PsrPipeContainerTest.php | 7 +- tests/Unit/Domain/EntityTest.php | 16 +- .../Domain/EntityWithNullableGuidTest.php | 33 +- tests/Unit/Domain/EntityWithTypedIdTest.php | 16 +- tests/Unit/Domain/IdentifierOrEntityTest.php | 10 +- .../PsrLogExceptionReporterTest.php | 15 +- .../InfrastructureExceptionTest.php | 4 +- .../OutboundEventBus/ClosurePublisherTest.php | 15 +- .../ComponentPublisherTest.php | 7 +- .../PublisherHandlerContainerTest.php | 13 +- .../OutboundEventBus/PublisherHandlerTest.php | 4 +- .../Infrastructure/Queue/ClosureQueueTest.php | 12 +- .../Queue/ComponentQueueTest.php | 7 +- .../Queue/EnqueuerContainerTest.php | 7 +- .../Infrastructure/Queue/EnqueuerTest.php | 4 +- .../Testing/FakeDomainEventDispatcherTest.php | 13 +- .../Testing/FakeExceptionReporterTest.php | 19 +- .../FakeOutboundEventPublisherTest.php | 13 +- tests/Unit/Testing/FakeQueueTest.php | 13 +- tests/Unit/Testing/FakeUnitOfWorkTest.php | 13 +- tests/Unit/Toolkit/ContractsTest.php | 13 +- tests/Unit/Toolkit/EnumStringTest.php | 4 +- tests/Unit/Toolkit/EnumValueTest.php | 4 +- tests/Unit/Toolkit/Identifiers/GuidTest.php | 40 ++- .../Toolkit/Identifiers/GuidTypeMapTest.php | 27 +- .../Toolkit/Identifiers/IntegerIdTest.php | 25 +- .../Identifiers/PossiblyNumericIdTest.php | 4 +- .../Unit/Toolkit/Identifiers/StringIdTest.php | 25 +- .../Toolkit/Identifiers/UuidFactoryTest.php | 58 +++- tests/Unit/Toolkit/Identifiers/UuidTest.php | 39 ++- tests/Unit/Toolkit/Identifiers/UuidV4Test.php | 31 +- tests/Unit/Toolkit/Identifiers/UuidV7Test.php | 31 +- .../Unit/Toolkit/Iterables/IsLazyListTest.php | 7 +- .../Toolkit/Iterables/IsNonEmptyListTest.php | 4 +- tests/Unit/Toolkit/ModuleBasenameTest.php | 21 +- .../Pipeline/AccumulationProcessorTest.php | 13 +- .../Pipeline/InterruptibleProcessorTest.php | 7 +- tests/Unit/Toolkit/Pipeline/LazyPipeTest.php | 13 +- .../Pipeline/MiddlewareProcessorTest.php | 13 +- .../Toolkit/Pipeline/PipeContainerTest.php | 4 +- .../Toolkit/Pipeline/PipelineBuilderTest.php | 10 +- tests/Unit/Toolkit/Pipeline/PipelineTest.php | 13 +- .../Toolkit/Pipeline/SimpleProcessorTest.php | 7 +- tests/Unit/Toolkit/Result/ErrorTest.php | 13 +- .../Result/FailedResultExceptionTest.php | 10 +- .../Toolkit/Result/KeyedSetOfErrorsTest.php | 22 +- .../Unit/Toolkit/Result/ListOfErrorsTest.php | 61 ++-- tests/Unit/Toolkit/Result/MetaTest.php | 28 +- tests/Unit/Toolkit/Result/ResultTest.php | 56 ++-- 85 files changed, 1181 insertions(+), 372 deletions(-) create mode 100644 .claude/skills/unit-testing/SKILL.md diff --git a/.claude/skills/unit-testing/SKILL.md b/.claude/skills/unit-testing/SKILL.md new file mode 100644 index 00000000..27732b12 --- /dev/null +++ b/.claude/skills/unit-testing/SKILL.md @@ -0,0 +1,313 @@ +--- +name: unit-testing +description: Use when writing or changing PHPUnit tests under tests/ — file layout, naming, attributes, mocks vs stubs vs the shipped Testing fakes, assertions, exceptions, fixtures for abstract classes, and PHPStan-compliant test types. +--- + +# Skill: Unit Testing + +Write tests for individual classes and methods in this PHP DDD library. Unit tests should be focused on testing a +single unit of behavior in isolation, without relying on external dependencies. + +## When to use + +Use this skill when: + +- Writing a new unit test for a class or method +- Adding test coverage to an existing class or method +- Updating unit tests after a class or method changes + +The same practices apply to the `Integration` suite. Put a test in `tests/Unit` when it exercises one class with its +collaborators replaced by stubs, mocks or fakes. Put it in `tests/Integration` when it exercises several real classes +wired together, e.g. a dispatcher autowiring handlers and middleware from a PSR container and running the full +pipeline. + +## File Layout + +- Tests mirror `src/`: the test for `src/Bus/Foo.php` is `tests/Unit/Bus/FooTest.php`, in namespace + `CloudCreativity\Modules\Tests\Unit\Bus`. File names must end in `Test.php`. +- Every file starts with the MIT copyright header used in existing files, then `declare(strict_types=1);`. +- Test classes are `final` and extend `PHPUnit\Framework\TestCase`. + +```php + + */ +public static function valueProvider(): array +{ + return [ + 'empty' => ['', false], + 'non-empty' => ['foo', true], + ]; +} + +#[Test] +#[DataProvider('valueProvider')] +public function it_checks_the_value(string $value, bool $expected): void +{ + // ... +} +``` + +### Tear Down + +Whenever any properties are set on the test class in the `setUp()` method, **always** unset them in the `tearDown()` +method, then call the parent: + +```php +protected function tearDown(): void +{ + unset($this->property1, $this->property2); + parent::tearDown(); +} +``` + +### Arrange, Act, Assert (AAA) Pattern + +Follow the Arrange, Act, Assert (AAA) pattern when writing unit tests. This pattern helps to structure tests in a clear +and consistent way. For example: + +```php +#[Test] +public function it_does_something(): void +{ + // Arrange + $objectUnderTest = new MyClass(); + // Act + $result = $objectUnderTest->someMethod(); + // Assert + $this->assertSame('expected value', $result); +} +``` + +Never write a test that mixes the Arrange, Act, and Assert steps together, or does AAA more than once in a test. + +Expectations are the one exception to the order: `expectException()`, `expectExceptionMessage()` and mock +`expects(...)` calls are assertions, but they must be set up *before* the act step. Put them at the end of the arrange +step, just before the act. + +> The `// Arrange` etc comments are for illustrative purposes only; do not add to tests. + +### Be Thorough + +Ensure all public methods on the class under test are covered by unit tests. This includes edge cases and error +conditions. Aim for high code coverage, but prioritize meaningful tests that cover important behavior over achieving +100% coverage. + +When a unit throws exceptions, write tests to assert that the correct exceptions are thrown under the expected +conditions. For example: + +```php +#[Test] +public function it_throws_exception_when_invalid(): void +{ + $objectUnderTest = new MyClass(); + + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Invalid input provided.'); + + $objectUnderTest->someMethod('invalid input'); +} +``` + +Always use `expectException()` and `expectExceptionMessage()` to assert both the correct exception class and message is +thrown. Asserting the message ensures the exception is thrown for the expected reason, rather than a different error +condition. + +Precondition checks made with `CloudCreativity\Modules\Toolkit\Contracts::assert()` throw +`CloudCreativity\Modules\Toolkit\ContractException`. They are part of the class's public behavior and should be +tested. Internal invariants checked with PHP's native `assert()` throw `AssertionError`, and only because the tests run +with `zend.assertions=1`. They guard against programming errors, so don't write tests for them unless asked. + +### Asserting Values + +Use `assertSame()` for scalars, arrays of scalars, and when the exact same object instance is expected (e.g. a +collaborator that is passed through unchanged). + +When asserting value objects and DTOs (e.g. `Result`, `Error`, identifiers), use `assertEquals()` to compare the +expected and actual objects. This compares the properties of the objects rather than their references: + +```php +$expected = new MyValueObject('value'); +$actual = $objectUnderTest->getValueObject(); +$this->assertEquals($expected, $actual); +``` + +This is preferred over testing individual properties of a value object, as it ensures the entire value object is +correct and reduces the chance of missing an important property in the assertion. + +Where a value object implements an `equals(self $other): bool` method (e.g. the identifiers in `Toolkit/Identifiers`), +use PHPUnit's `assertObjectEquals()` and `assertObjectNotEquals()` to compare the objects using their `equals()` +method: + +```php +$this->assertObjectEquals($expected, $actual); +``` + +### Test Doubles + +Isolate the unit under test by replacing its collaborators with test doubles. In order of preference: + +1. **Real instances** of value objects, DTOs and other simple concrete classes. Never mock or stub these. Every class + in this library is `final` (enforced by pint), so concrete classes can't be mocked anyway. +2. **The shipped fakes** in `src/Testing/` for the driven ports and PSR interfaces they implement: `FakeContainer`, + `FakeQueue`, `FakeUnitOfWork`, `FakeDomainEventDispatcher`, `FakeOutboundEventPublisher`, `FakeExceptionReporter` + and `FakeLogger`. They record what was done to them, so you can assert on their state after the act step. +3. **Stubs** (`createStub()`) for interfaces that only need to exist or return values, e.g. a `Command`, `Query` or + `IntegrationEvent` message passed through the code under test. +4. **Mocks** (`createMock()`) only when the test asserts how a collaborator is called. Always configure them with + `expects(...)`. A mock with no expectations should be a stub: PHPUnit 12 raises a notice for it, and this repo fails + on notices. + +Mock and stub the interfaces in `src/Contracts/`, not the concrete classes. Type mock properties with a native +intersection type so PHPStan knows about both APIs: + +```php +private Validator&MockObject $validator; + +protected function setUp(): void +{ + parent::setUp(); + $this->validator = $this->createMock(Validator::class); +} + +#[Test] +public function it_validates_the_command(): void +{ + $command = $this->createStub(Command::class); + + $this->validator + ->expects($this->once()) + ->method('validate') + ->with($this->identicalTo($command)) + ->willReturn(new ListOfErrors()); + + // act and assert +} +``` + +### Testing Abstract Classes + +Many classes in this library (dispatchers, handler containers, middleware) are `abstract` and meant to be extended by +consumers. Test them through a subclass: + +- **Anonymous class** in the test (or in `setUp()`), when the subclass is small and only used by that test class: + + ```php + $this->middleware = new class ($this->validator) extends ValidateMessage { + protected function rules(): iterable + { + return ['foo', 'bar']; + } + }; + ``` + +- **Fixture class** next to the test (e.g. `tests/Unit/Domain/TestEntity.php`), when the subclass is larger, needs PHP + attributes such as `#[WithCommand]` or `#[Through]` (which are read by reflection), or is shared across test + classes. Fixtures shared across suites live in the root of `tests/` (e.g. `tests/TestBackedEnum.php`). Fixture file + names must not end in `Test.php`. + +### Test Sub-Headings + +When a test class is long, use sub-headings in comments to group the tests for each method of the class under test. +This makes the test class easier to read and navigate. For example: + +```php +// ------------------------------------------------------------------------- +// dispatch() +// ------------------------------------------------------------------------- + +#[Test] +public function it_dispatches_a_command(): void +``` + +### Arrange State Directly + +Build the object under test directly in the state the test needs. Don't get it there by calling its other public +methods, because then the test also depends on those methods working, and it breaks the AAA pattern. For entities and +aggregates it also makes it harder to assert which domain events are, or are not, dispatched. + +Incorrect - a state transition as part of arrange: + +```php +#[Test] +public function it_cannot_be_locked_when_already_locked(): void +{ + $entity = $this->makeEntity(); + $entity->lock(); + + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Entity is already locked.'); + + $entity->lock(); +} +``` + +Correct - the entity is constructed in the state ready for the test: + +```php +#[Test] +public function it_cannot_be_locked_when_already_locked(): void +{ + $entity = $this->makeEntity(locked: true); + + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Entity is already locked.'); + + $entity->lock(); +} +``` + +## Before Finishing + +Run these and fix any failures: + +```bash +vendor/bin/phpunit tests/Unit/Path/To/FooTest.php # the test(s) you wrote +composer static # phpstan level 10, includes tests/ +composer style:fix # pint +``` diff --git a/tests/Integration/Application/DomainEventDispatching/MathDomainEventDispatcherTest.php b/tests/Integration/Application/DomainEventDispatching/MathDomainEventDispatcherTest.php index 6328a078..b5ae3772 100644 --- a/tests/Integration/Application/DomainEventDispatching/MathDomainEventDispatcherTest.php +++ b/tests/Integration/Application/DomainEventDispatching/MathDomainEventDispatcherTest.php @@ -15,11 +15,13 @@ use CloudCreativity\Modules\Application\DomainEventDispatching\Middleware\LogDomainEventDispatch; use CloudCreativity\Modules\Application\UnitOfWork\UnitOfWorkManager; use CloudCreativity\Modules\Testing\FakeContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class MathDomainEventDispatcherTest extends TestCase { - public function test(): void + #[Test] + public function it_dispatches_domain_events(): void { $container = new FakeContainer(); $listener = new TestDomainListener(); diff --git a/tests/Integration/Bus/MathCommandBusTest.php b/tests/Integration/Bus/MathCommandBusTest.php index 54e2dd4d..423b2113 100644 --- a/tests/Integration/Bus/MathCommandBusTest.php +++ b/tests/Integration/Bus/MathCommandBusTest.php @@ -16,11 +16,13 @@ use CloudCreativity\Modules\Application\UnitOfWork\UnitOfWorkManager; use CloudCreativity\Modules\Bus\Middleware\LogMessageDispatch; use CloudCreativity\Modules\Testing\FakeContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class MathCommandBusTest extends TestCase { - public function test(): void + #[Test] + public function it_dispatches_commands(): void { $container = new FakeContainer(); $container->bind(AddCommandHandler::class, fn () => new AddCommandHandler(3)); diff --git a/tests/Integration/Bus/MathEventBusTest.php b/tests/Integration/Bus/MathEventBusTest.php index b22873ee..b822efa2 100644 --- a/tests/Integration/Bus/MathEventBusTest.php +++ b/tests/Integration/Bus/MathEventBusTest.php @@ -16,11 +16,13 @@ use CloudCreativity\Modules\Application\UnitOfWork\UnitOfWorkManager; use CloudCreativity\Modules\Bus\Middleware\LogMessageDispatch; use CloudCreativity\Modules\Testing\FakeContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class MathEventBusTest extends TestCase { - public function test(): void + #[Test] + public function it_dispatches_events(): void { $a = new NumbersAddedHandler(); $b = new NumbersSubtractedHandler(); diff --git a/tests/Integration/Bus/MathQueryBusTest.php b/tests/Integration/Bus/MathQueryBusTest.php index 6c8589d2..84b06051 100644 --- a/tests/Integration/Bus/MathQueryBusTest.php +++ b/tests/Integration/Bus/MathQueryBusTest.php @@ -15,11 +15,13 @@ use Closure; use CloudCreativity\Modules\Bus\Middleware\LogMessageDispatch; use CloudCreativity\Modules\Testing\FakeContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class MathQueryBusTest extends TestCase { - public function test(): void + #[Test] + public function it_dispatches_queries(): void { $container = new FakeContainer(); $container->bind(SubtractQueryHandler::class, fn () => new SubtractQueryHandler(3)); diff --git a/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php b/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php index 62c30dd7..439f1b3a 100644 --- a/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php +++ b/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php @@ -17,11 +17,13 @@ use CloudCreativity\Modules\Tests\Integration\Bus\NumbersAdded; use CloudCreativity\Modules\Tests\Integration\Bus\NumbersDivided; use CloudCreativity\Modules\Tests\Integration\Bus\NumbersSubtracted; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class MathEventPublisherTest extends TestCase { - public function test(): void + #[Test] + public function it_publishes_events(): void { $a = new NumbersAddedPublisher(); $b = new NumbersSubtractedPublisher(); diff --git a/tests/Integration/Infrastructure/OutboundEventBus/TestClosurePublisherTest.php b/tests/Integration/Infrastructure/OutboundEventBus/TestClosurePublisherTest.php index 97749561..8932b90b 100644 --- a/tests/Integration/Infrastructure/OutboundEventBus/TestClosurePublisherTest.php +++ b/tests/Integration/Infrastructure/OutboundEventBus/TestClosurePublisherTest.php @@ -15,11 +15,13 @@ use CloudCreativity\Modules\Infrastructure\OutboundEventBus\Middleware\LogOutboundEvent; use CloudCreativity\Modules\Testing\FakeContainer; use CloudCreativity\Modules\Tests\Integration\Bus\NumbersAdded; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class TestClosurePublisherTest extends TestCase { - public function test(): void + #[Test] + public function it_publishes_an_event(): void { $published = []; diff --git a/tests/Integration/Infrastructure/Queue/MathQueueTest.php b/tests/Integration/Infrastructure/Queue/MathQueueTest.php index 03b237fc..e0c9a277 100644 --- a/tests/Integration/Infrastructure/Queue/MathQueueTest.php +++ b/tests/Integration/Infrastructure/Queue/MathQueueTest.php @@ -17,11 +17,13 @@ use CloudCreativity\Modules\Tests\Integration\Bus\AddCommand; use CloudCreativity\Modules\Tests\Integration\Bus\FloorCommand; use CloudCreativity\Modules\Tests\Integration\Bus\MultiplyCommand; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class MathQueueTest extends TestCase { - public function test(): void + #[Test] + public function it_queues_commands(): void { $a = new AddCommandEnqueuer(); $b = new MultiplyCommandEnqueuer(); diff --git a/tests/Integration/Infrastructure/Queue/TestClosureQueueTest.php b/tests/Integration/Infrastructure/Queue/TestClosureQueueTest.php index aba5dc8c..446cf2c1 100644 --- a/tests/Integration/Infrastructure/Queue/TestClosureQueueTest.php +++ b/tests/Integration/Infrastructure/Queue/TestClosureQueueTest.php @@ -15,11 +15,13 @@ use CloudCreativity\Modules\Infrastructure\Queue\Middleware\LogPushedToQueue; use CloudCreativity\Modules\Testing\FakeContainer; use CloudCreativity\Modules\Tests\Integration\Bus\AddCommand; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class TestClosureQueueTest extends TestCase { - public function test(): void + #[Test] + public function it_queues_a_command(): void { $queued = []; diff --git a/tests/Unit/Application/ApplicationExceptionTest.php b/tests/Unit/Application/ApplicationExceptionTest.php index f02d7590..a7172c5a 100644 --- a/tests/Unit/Application/ApplicationExceptionTest.php +++ b/tests/Unit/Application/ApplicationExceptionTest.php @@ -13,12 +13,14 @@ namespace CloudCreativity\Modules\Tests\Unit\Application; use CloudCreativity\Modules\Application\ApplicationException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; final class ApplicationExceptionTest extends TestCase { - public function test(): void + #[Test] + public function it_is_a_runtime_exception(): void { $ex = new ApplicationException(); $this->assertInstanceOf(RuntimeException::class, $ex); diff --git a/tests/Unit/Application/Bus/CommandDispatcherTest.php b/tests/Unit/Application/Bus/CommandDispatcherTest.php index 42942aa9..0478579a 100644 --- a/tests/Unit/Application/Bus/CommandDispatcherTest.php +++ b/tests/Unit/Application/Bus/CommandDispatcherTest.php @@ -18,6 +18,7 @@ use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -50,7 +51,8 @@ protected function tearDown(): void parent::tearDown(); } - public function test(): void + #[Test] + public function it_dispatches_a_command(): void { $command = $this->createMock(Command::class); @@ -71,7 +73,8 @@ public function test(): void $this->assertSame($expected, $actual); } - public function testWithMiddleware(): void + #[Test] + public function it_dispatches_a_command_through_middleware(): void { $command1 = new TestCommand(); $command2 = new TestCommand(); diff --git a/tests/Unit/Application/Bus/CommandHandlerContainerTest.php b/tests/Unit/Application/Bus/CommandHandlerContainerTest.php index eaf35e6f..c024c998 100644 --- a/tests/Unit/Application/Bus/CommandHandlerContainerTest.php +++ b/tests/Unit/Application/Bus/CommandHandlerContainerTest.php @@ -16,12 +16,14 @@ use CloudCreativity\Modules\Bus\CommandHandler; use CloudCreativity\Modules\Bus\CommandHandlerContainer; use CloudCreativity\Modules\Contracts\Messaging\Command; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; final class CommandHandlerContainerTest extends TestCase { - public function testItResolvesUsingClosureBindings(): void + #[Test] + public function it_resolves_using_closure_bindings(): void { $a = new class () extends TestCommandHandler {}; $b = $this->createStub(TestCommandHandler::class); @@ -43,7 +45,8 @@ public function testItResolvesUsingClosureBindings(): void $container->get($command3::class); } - public function testItResolvesViaPsrContainer(): void + #[Test] + public function it_resolves_via_psr_container(): void { $a = new class () extends TestCommandHandler {}; $b = $this->createStub(TestCommandHandler::class); diff --git a/tests/Unit/Application/Bus/CommandHandlerTest.php b/tests/Unit/Application/Bus/CommandHandlerTest.php index ee8fc2c4..96443c4c 100644 --- a/tests/Unit/Application/Bus/CommandHandlerTest.php +++ b/tests/Unit/Application/Bus/CommandHandlerTest.php @@ -14,11 +14,13 @@ use CloudCreativity\Modules\Bus\CommandHandler; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class CommandHandlerTest extends TestCase { - public function test(): void + #[Test] + public function it_executes_the_command_and_returns_its_middleware(): void { $command = new TestCommand(); @@ -40,7 +42,8 @@ public function test(): void $this->assertSame($middleware, $handler->middleware()); } - public function testItDoesNotHaveExecuteMethod(): void + #[Test] + public function it_does_not_have_execute_method(): void { $handler = new CommandHandler(new \DateTime()); $command = new TestCommand(); diff --git a/tests/Unit/Application/Bus/CommandQueuerTest.php b/tests/Unit/Application/Bus/CommandQueuerTest.php index 61afe652..95897241 100644 --- a/tests/Unit/Application/Bus/CommandQueuerTest.php +++ b/tests/Unit/Application/Bus/CommandQueuerTest.php @@ -14,6 +14,7 @@ use CloudCreativity\Modules\Application\Bus\CommandQueuer; use CloudCreativity\Modules\Contracts\Application\Ports\Queue; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -38,7 +39,8 @@ protected function tearDown(): void parent::tearDown(); } - public function test(): void + #[Test] + public function it_queues_the_command(): void { $this->queue ->expects($this->once()) diff --git a/tests/Unit/Application/Bus/Middleware/ExecuteInUnitOfWorkTest.php b/tests/Unit/Application/Bus/Middleware/ExecuteInUnitOfWorkTest.php index e090764f..dbfd66c2 100644 --- a/tests/Unit/Application/Bus/Middleware/ExecuteInUnitOfWorkTest.php +++ b/tests/Unit/Application/Bus/Middleware/ExecuteInUnitOfWorkTest.php @@ -16,6 +16,7 @@ use CloudCreativity\Modules\Contracts\Application\UnitOfWork\UnitOfWorkManager; use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Throwable; @@ -26,7 +27,8 @@ final class ExecuteInUnitOfWorkTest extends TestCase */ private array $sequence = []; - public function testItCommitsUnitOfWorkOnSuccess(): void + #[Test] + public function it_commits_unit_of_work_on_success(): void { $command = $this->createMock(Command::class); $expected = Result::ok(); @@ -57,7 +59,8 @@ public function testItCommitsUnitOfWorkOnSuccess(): void $this->assertSame($expected, $actual); } - public function testItDoesNotCommitUnitOfWorkOnFailure(): void + #[Test] + public function it_does_not_commit_unit_of_work_on_failure(): void { $command = $this->createMock(Command::class); $expected = Result::failed('Something went wrong.'); @@ -88,7 +91,8 @@ public function testItDoesNotCommitUnitOfWorkOnFailure(): void $this->assertSame($expected, $actual); } - public function testItDoesNotCatchExceptions(): void + #[Test] + public function it_does_not_catch_exceptions(): void { $command = $this->createMock(Command::class); $expected = new \RuntimeException('Boom! Something went wrong.'); diff --git a/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php b/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php index 1512ad54..f616d1b4 100644 --- a/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php +++ b/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php @@ -16,6 +16,7 @@ use CloudCreativity\Modules\Contracts\Application\DomainEventDispatching\DeferredDispatcher; use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -39,7 +40,14 @@ protected function setUp(): void ); } - public function testItFlushesDeferredEvents(): void + protected function tearDown(): void + { + unset($this->middleware, $this->dispatcher); + parent::tearDown(); + } + + #[Test] + public function it_flushes_deferred_events(): void { $command = $this->createMock(Command::class); $expected = Result::ok(); @@ -65,7 +73,8 @@ public function testItFlushesDeferredEvents(): void $this->assertSame($expected, $actual); } - public function testItForgetsDeferredEventsOnFailedResult(): void + #[Test] + public function it_forgets_deferred_events_on_failed_result(): void { $command = $this->createMock(Command::class); $expected = Result::failed('Something went wrong.'); @@ -91,7 +100,8 @@ public function testItForgetsDeferredEventsOnFailedResult(): void } - public function testItForgetsDeferredEventsOnException(): void + #[Test] + public function it_forgets_deferred_events_on_exception(): void { $command = $this->createMock(Command::class); $expected = new \LogicException('Boom!'); diff --git a/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php b/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php index 89d4ffab..6a589bdc 100644 --- a/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php +++ b/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php @@ -19,6 +19,7 @@ use CloudCreativity\Modules\Contracts\Messaging\Query; use CloudCreativity\Modules\Toolkit\Result\Result; use LogicException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -52,11 +53,12 @@ protected function setUp(): void protected function tearDown(): void { - parent::tearDown(); unset($this->logger, $this->message, $this->logs); + parent::tearDown(); } - public function testWithDefaultLevels(): void + #[Test] + public function it_logs_with_the_default_levels(): void { $expected = Result::ok(); $name = $this->message::class; @@ -74,7 +76,8 @@ public function testWithDefaultLevels(): void ], $this->logs); } - public function testWithCustomLevels(): void + #[Test] + public function it_logs_with_custom_levels(): void { $expected = Result::failed('Something went wrong.'); $name = $this->message::class; @@ -92,7 +95,8 @@ public function testWithCustomLevels(): void ], $this->logs); } - public function testItLogsAfterTheNextClosureIsInvoked(): void + #[Test] + public function it_logs_after_the_next_closure_is_invoked(): void { $expected = new LogicException(); $message = $this->createMock(Query::class); diff --git a/tests/Unit/Application/Bus/Middleware/SetupBeforeDispatchTest.php b/tests/Unit/Application/Bus/Middleware/SetupBeforeDispatchTest.php index 50c3feaf..32159d7f 100644 --- a/tests/Unit/Application/Bus/Middleware/SetupBeforeDispatchTest.php +++ b/tests/Unit/Application/Bus/Middleware/SetupBeforeDispatchTest.php @@ -17,6 +17,7 @@ use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Contracts\Messaging\Query; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -27,7 +28,8 @@ final class SetupBeforeDispatchTest extends TestCase */ private array $sequence = []; - public function testItSetsUpAndSucceedsWithoutTeardown(): void + #[Test] + public function it_sets_up_and_succeeds_without_teardown(): void { $message = $this->createMock(Command::class); $result = Result::ok(); @@ -47,7 +49,8 @@ public function testItSetsUpAndSucceedsWithoutTeardown(): void $this->assertSame(['setup', 'next'], $this->sequence); } - public function testItSetsUpAndSucceedsWithTeardown(): void + #[Test] + public function it_sets_up_and_succeeds_with_teardown(): void { $message = $this->createMock(Query::class); $result = Result::ok(); @@ -69,7 +72,8 @@ public function testItSetsUpAndSucceedsWithTeardown(): void $this->assertSame(['setup', 'next', 'teardown'], $this->sequence); } - public function testItSetsUpAndFailsWithoutTeardown(): void + #[Test] + public function it_sets_up_and_fails_without_teardown(): void { $message = $this->createMock(Command::class); $result = Result::failed('Something went wrong.'); @@ -89,7 +93,8 @@ public function testItSetsUpAndFailsWithoutTeardown(): void $this->assertSame(['setup', 'next'], $this->sequence); } - public function testItSetsUpAndFailsWithTeardown(): void + #[Test] + public function it_sets_up_and_fails_with_teardown(): void { $message = $this->createMock(Command::class); $result = Result::failed('Something went wrong.'); @@ -111,7 +116,8 @@ public function testItSetsUpAndFailsWithTeardown(): void $this->assertSame(['setup', 'next', 'teardown'], $this->sequence); } - public function testItSetsUpAndThrowsExceptionWithoutTeardown(): void + #[Test] + public function it_sets_up_and_throws_exception_without_teardown(): void { $message = $this->createMock(Command::class); $exception = new RuntimeException('Something went wrong.'); @@ -137,7 +143,8 @@ public function testItSetsUpAndThrowsExceptionWithoutTeardown(): void $this->assertSame(['setup', 'next'], $this->sequence); } - public function testItSetsUpAndThrowsExceptionWithTeardown(): void + #[Test] + public function it_sets_up_and_throws_exception_with_teardown(): void { $message = $this->createMock(Query::class); $exception = new RuntimeException('Something went wrong.'); diff --git a/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php b/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php index 00dbab7f..fd45f2f7 100644 --- a/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php +++ b/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php @@ -16,12 +16,14 @@ use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Contracts\Messaging\Query; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; final class TearDownAfterDispatchTest extends TestCase { - public function testItInvokesCallbackAfterSuccess(): void + #[Test] + public function it_invokes_callback_after_success(): void { $message = $this->createMock(Command::class); $result = Result::ok(); @@ -41,7 +43,8 @@ public function testItInvokesCallbackAfterSuccess(): void $this->assertSame(['next', 'teardown'], $sequence); } - public function testItInvokesCallbackAfterFailure(): void + #[Test] + public function it_invokes_callback_after_failure(): void { $message = $this->createMock(Query::class); $result = Result::failed('Something went wrong.'); @@ -61,7 +64,8 @@ public function testItInvokesCallbackAfterFailure(): void $this->assertSame(['next', 'teardown'], $sequence); } - public function testItInvokesCallbackAfterException(): void + #[Test] + public function it_invokes_callback_after_exception(): void { $message = $this->createMock(Command::class); $exception = new RuntimeException('Something went wrong.'); diff --git a/tests/Unit/Application/Bus/Middleware/ValidateMessageTest.php b/tests/Unit/Application/Bus/Middleware/ValidateMessageTest.php index db3c9d44..33ef1f2d 100644 --- a/tests/Unit/Application/Bus/Middleware/ValidateMessageTest.php +++ b/tests/Unit/Application/Bus/Middleware/ValidateMessageTest.php @@ -21,6 +21,7 @@ use CloudCreativity\Modules\Toolkit\Result\Error; use CloudCreativity\Modules\Toolkit\Result\ListOfErrors; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -50,7 +51,14 @@ protected function rules(): iterable }; } - public function testItSucceeds(): void + protected function tearDown(): void + { + unset($this->validator, $this->middleware); + parent::tearDown(); + } + + #[Test] + public function it_succeeds(): void { $rules = []; $command = $this->createStub(Command::class); @@ -90,7 +98,8 @@ public function testItSucceeds(): void $this->assertSame($expected, $actual); } - public function testItFails(): void + #[Test] + public function it_fails(): void { $this->validator ->expects($this->once()) @@ -119,7 +128,8 @@ public function testItFails(): void $this->assertSame($errors, $result->errors()); } - public function testItStopsOnFirstFailureViaBail(): void + #[Test] + public function it_stops_on_first_failure_via_bail(): void { $this->middleware = new class ($this->validator) extends ValidateMessage implements Bail { /** @@ -158,7 +168,8 @@ protected function rules(): iterable $this->assertSame($errors, $result->errors()); } - public function testItStopsOnFirstFailure(): void + #[Test] + public function it_stops_on_first_failure(): void { $command = $this->createStub(Command::class); diff --git a/tests/Unit/Application/Bus/QueryDispatcherTest.php b/tests/Unit/Application/Bus/QueryDispatcherTest.php index 1801b7ac..e7d822e4 100644 --- a/tests/Unit/Application/Bus/QueryDispatcherTest.php +++ b/tests/Unit/Application/Bus/QueryDispatcherTest.php @@ -18,6 +18,7 @@ use CloudCreativity\Modules\Contracts\Messaging\Query; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -56,7 +57,8 @@ protected function tearDown(): void parent::tearDown(); } - public function test(): void + #[Test] + public function it_dispatches_a_query(): void { $query = $this->createMock(Query::class); @@ -77,7 +79,8 @@ public function test(): void $this->assertSame($expected, $actual); } - public function testWithMiddleware(): void + #[Test] + public function it_dispatches_a_query_through_middleware(): void { $query1 = new TestQuery(); $query2 = new TestQuery(); diff --git a/tests/Unit/Application/Bus/QueryHandlerContainerTest.php b/tests/Unit/Application/Bus/QueryHandlerContainerTest.php index 9f7388da..3a040dae 100644 --- a/tests/Unit/Application/Bus/QueryHandlerContainerTest.php +++ b/tests/Unit/Application/Bus/QueryHandlerContainerTest.php @@ -16,12 +16,14 @@ use CloudCreativity\Modules\Bus\QueryHandler; use CloudCreativity\Modules\Bus\QueryHandlerContainer; use CloudCreativity\Modules\Contracts\Messaging\Query; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; final class QueryHandlerContainerTest extends TestCase { - public function testItResolvesClosureBindings(): void + #[Test] + public function it_resolves_closure_bindings(): void { $a = new class () extends TestQueryHandler {}; $b = $this->createStub(TestQueryHandler::class); @@ -43,7 +45,8 @@ public function testItResolvesClosureBindings(): void $container->get($query3::class); } - public function testItResolvesViaPsrContainer(): void + #[Test] + public function it_resolves_via_psr_container(): void { $a = new class () extends TestQueryHandler {}; $b = $this->createStub(TestQueryHandler::class); diff --git a/tests/Unit/Application/Bus/QueryHandlerTest.php b/tests/Unit/Application/Bus/QueryHandlerTest.php index 01b5c749..0f1120ad 100644 --- a/tests/Unit/Application/Bus/QueryHandlerTest.php +++ b/tests/Unit/Application/Bus/QueryHandlerTest.php @@ -14,11 +14,13 @@ use CloudCreativity\Modules\Bus\QueryHandler; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class QueryHandlerTest extends TestCase { - public function test(): void + #[Test] + public function it_executes_the_query_and_returns_its_middleware(): void { $query = new TestQuery(); @@ -40,7 +42,8 @@ public function test(): void $this->assertSame($middleware, $handler->middleware()); } - public function testItDoesNotHaveExecuteMethod(): void + #[Test] + public function it_does_not_have_execute_method(): void { $handler = new QueryHandler(new \DateTime()); $query = new TestQuery(); diff --git a/tests/Unit/Application/Bus/ValidatorTest.php b/tests/Unit/Application/Bus/ValidatorTest.php index f6beba20..c2002760 100644 --- a/tests/Unit/Application/Bus/ValidatorTest.php +++ b/tests/Unit/Application/Bus/ValidatorTest.php @@ -20,6 +20,7 @@ use CloudCreativity\Modules\Toolkit\Result\Error; use CloudCreativity\Modules\Toolkit\Result\ListOfErrors; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; @@ -41,7 +42,8 @@ public static function messageProvider(): array * @param class-string $class */ #[DataProvider('messageProvider')] - public function testItValidatesMessage(string $class): void + #[Test] + public function it_validates_message(string $class): void { $message = $this->createStub($class); $error1 = new Error(null, 'Message 1'); @@ -86,7 +88,8 @@ public function testItValidatesMessage(string $class): void * @param class-string $class */ #[DataProvider('messageProvider')] - public function testItValidatesMessageUsingPsrContainer(string $class): void + #[Test] + public function it_validates_message_using_psr_container(string $class): void { $message = $this->createStub($class); $error1 = new Error(null, 'Message 1'); @@ -131,7 +134,8 @@ public function testItValidatesMessageUsingPsrContainer(string $class): void * @param class-string $class */ #[DataProvider('messageProvider')] - public function testItStopsOnFirstFailure(string $class): void + #[Test] + public function it_stops_on_first_failure(string $class): void { $message = $this->createStub($class); $error = new Error(null, 'Message 1'); @@ -160,7 +164,8 @@ public function testItStopsOnFirstFailure(string $class): void $this->assertSame([$error], $actual->all()); } - public function testItHasNoRules(): void + #[Test] + public function it_has_no_rules(): void { $query = $this->createStub(Query::class); $validator = new Validator(); diff --git a/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php b/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php index 6a107c7e..02f70698 100644 --- a/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php +++ b/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php @@ -18,6 +18,7 @@ use CloudCreativity\Modules\Contracts\Application\DomainEventDispatching\ListenerContainer; use CloudCreativity\Modules\Contracts\Domain\Events\DomainEvent; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -42,7 +43,14 @@ protected function setUp(): void ) extends DeferredDispatcher {}; } - public function testItDispatchesImmediately(): void + protected function tearDown(): void + { + unset($this->dispatcher, $this->listeners, $this->middleware); + parent::tearDown(); + } + + #[Test] + public function it_dispatches_immediately(): void { $sequence = []; $event = new TestImmediateDomainEvent(); @@ -105,7 +113,8 @@ public function testItDispatchesImmediately(): void $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3']); } - public function testItFlushesDeferredEvents(): void + #[Test] + public function it_flushes_deferred_events(): void { $sequence = []; $event1 = new class () extends TestDomainEvent {}; @@ -176,7 +185,8 @@ public function testItFlushesDeferredEvents(): void $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3', 'Listener4']); } - public function testItFlushesDeferredEventsIncludingEventsDispatchedByListeners(): void + #[Test] + public function it_flushes_deferred_events_including_events_dispatched_by_listeners(): void { $sequence = []; $event1 = new class () extends TestDomainEvent {}; @@ -232,7 +242,8 @@ public function testItFlushesDeferredEventsIncludingEventsDispatchedByListeners( $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3']); } - public function testItForgetsDeferredEvents(): void + #[Test] + public function it_forgets_deferred_events(): void { $sequence = []; $deferred = new class () extends TestDomainEvent {}; @@ -293,7 +304,8 @@ public function testItForgetsDeferredEvents(): void $this->assertSame($step3, ['Listener1', 'Listener2']); } - public function testItForgetsDeferredEventsAfterException(): void + #[Test] + public function it_forgets_deferred_events_after_exception(): void { $sequence = []; $event1 = new class () extends TestDomainEvent {}; @@ -355,14 +367,16 @@ public function testItForgetsDeferredEventsAfterException(): void $this->dispatcher->flush(); // flush again, not expecting any events to be triggered. } - public function testNoListeners(): void + #[Test] + public function it_does_nothing_when_there_are_no_listeners(): void { $event = $this->createMock(DomainEvent::class); $this->listeners->expects($this->never())->method($this->anything()); $this->dispatcher->dispatch($event); } - public function testItDispatchesThroughMiddleware(): void + #[Test] + public function it_dispatches_through_middleware(): void { $event1 = new TestImmediateDomainEvent(); $event2 = new TestImmediateDomainEvent(); @@ -404,7 +418,8 @@ public function testItDispatchesThroughMiddleware(): void $this->dispatcher->dispatch($event1); } - public function testListenerDoesNotHaveHandleMethod(): void + #[Test] + public function it_fails_when_the_listener_does_not_have_a_handle_method(): void { $event = new TestImmediateDomainEvent(); diff --git a/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php b/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php index 968473fb..cf505189 100644 --- a/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php +++ b/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php @@ -18,6 +18,7 @@ use CloudCreativity\Modules\Contracts\Domain\Events\DomainEvent; use CloudCreativity\Modules\Contracts\Domain\Events\DomainEventDispatcher; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -39,7 +40,14 @@ protected function setUp(): void ) extends Dispatcher {}; } - public function testItDispatchesImmediately(): void + protected function tearDown(): void + { + unset($this->dispatcher, $this->listeners, $this->middleware); + parent::tearDown(); + } + + #[Test] + public function it_dispatches_immediately(): void { $sequence = []; $event1 = new TestImmediateDomainEvent(); @@ -102,14 +110,16 @@ public function testItDispatchesImmediately(): void $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3']); } - public function testNoListeners(): void + #[Test] + public function it_does_nothing_when_there_are_no_listeners(): void { $event = $this->createMock(DomainEvent::class); $this->listeners->expects($this->never())->method($this->anything()); $this->dispatcher->dispatch($event); } - public function testItDispatchesThroughMiddleware(): void + #[Test] + public function it_dispatches_through_middleware(): void { $event1 = new class () extends TestDomainEvent {}; ; @@ -153,7 +163,8 @@ public function testItDispatchesThroughMiddleware(): void $this->dispatcher->dispatch($event1); } - public function testListenerDoesNotHaveHandleMethod(): void + #[Test] + public function it_fails_when_the_listener_does_not_have_a_handle_method(): void { $event = new TestImmediateDomainEvent(); diff --git a/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php b/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php index fc1cfa3f..3857ac5e 100644 --- a/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php +++ b/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php @@ -13,11 +13,13 @@ namespace CloudCreativity\Modules\Tests\Unit\Application\DomainEventDispatching; use CloudCreativity\Modules\Application\DomainEventDispatching\ListenerContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class ListenerContainerTest extends TestCase { - public function testItCreatesListener(): void + #[Test] + public function it_creates_listener(): void { $container = new ListenerContainer(); $listener = new class () extends TestListener {}; @@ -28,14 +30,16 @@ public function testItCreatesListener(): void $this->assertSame($listener, $container->get('foo')); } - public function testItDoesNotRecogniseListenerName(): void + #[Test] + public function it_does_not_recognise_listener_name(): void { $container = new ListenerContainer(); $this->expectExceptionMessage('Unrecognised listener name: foo'); $container->get('foo'); } - public function testItHandlesBindingNotReturningAnObject(): void + #[Test] + public function it_handles_binding_not_returning_an_object(): void { $container = new ListenerContainer(); /** @phpstan-ignore-next-line */ diff --git a/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php b/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php index c0ffa34f..f572ce28 100644 --- a/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php +++ b/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php @@ -16,6 +16,7 @@ use CloudCreativity\Modules\Contracts\Domain\Events\DomainEvent; use DateTimeImmutable; use LogicException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -54,7 +55,14 @@ public function getOccurredAt(): DateTimeImmutable }; } - public function testWithDefaultLevels(): void + protected function tearDown(): void + { + unset($this->logger, $this->event); + parent::tearDown(); + } + + #[Test] + public function it_logs_with_the_default_levels(): void { $eventName = $this->event::class; $logs = []; @@ -78,7 +86,8 @@ public function testWithDefaultLevels(): void ], $logs); } - public function testWithCustomLevels(): void + #[Test] + public function it_logs_with_custom_levels(): void { $eventName = $this->event::class; $logs = []; @@ -102,7 +111,8 @@ public function testWithCustomLevels(): void ], $logs); } - public function testItLogsAfterTheNextClosureIsInvoked(): void + #[Test] + public function it_logs_after_the_next_closure_is_invoked(): void { $expected = new LogicException(); $eventName = $this->event::class; diff --git a/tests/Unit/Application/DomainEventDispatching/UnitOfWorkAwareDispatcherTest.php b/tests/Unit/Application/DomainEventDispatching/UnitOfWorkAwareDispatcherTest.php index 0b7a6cd9..d14f55dd 100644 --- a/tests/Unit/Application/DomainEventDispatching/UnitOfWorkAwareDispatcherTest.php +++ b/tests/Unit/Application/DomainEventDispatching/UnitOfWorkAwareDispatcherTest.php @@ -22,6 +22,7 @@ use CloudCreativity\Modules\Contracts\Domain\Events\DomainEventDispatcher; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; use PHPUnit\Framework\Attributes\Depends; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -49,7 +50,14 @@ protected function setUp(): void ) extends UnitOfWorkAwareDispatcher {}; } - public function testItDispatchesImmediately(): void + protected function tearDown(): void + { + unset($this->dispatcher, $this->unitOfWorkManager, $this->listeners, $this->middleware); + parent::tearDown(); + } + + #[Test] + public function it_dispatches_immediately(): void { $sequence = []; $event = new TestImmediateDomainEvent(); @@ -141,7 +149,8 @@ public function testItDispatchesImmediately(): void $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3']); } - public function testItDoesNotDispatchImmediately(): void + #[Test] + public function it_does_not_dispatch_immediately(): void { $event = $this->createMock(DomainEvent::class); @@ -176,8 +185,9 @@ public function testItDoesNotDispatchImmediately(): void $this->dispatcher->dispatch($event); } - #[Depends('testItDoesNotDispatchImmediately')] - public function testItDispatchesEventInBeforeCommitCallback(): void + #[Depends('it_does_not_dispatch_immediately')] + #[Test] + public function it_dispatches_event_in_before_commit_callback(): void { $event = new class () extends TestDomainEvent {}; @@ -219,7 +229,8 @@ public function testItDispatchesEventInBeforeCommitCallback(): void $this->dispatcher->dispatch($event); } - public function testBeforeCommitListener(): void + #[Test] + public function it_dispatches_to_a_before_commit_listener_before_commit(): void { $event = new TestImmediateDomainEvent(); $listener = $this->createMock(TestListenerBeforeCommit::class); @@ -250,7 +261,8 @@ public function testBeforeCommitListener(): void $this->dispatcher->dispatch($event); } - public function testAfterCommitListener(): void + #[Test] + public function it_dispatches_to_an_after_commit_listener_after_commit(): void { $event = new TestImmediateDomainEvent(); $listener = $this->createMock(TestListenerAfterCommit::class); @@ -281,14 +293,16 @@ public function testAfterCommitListener(): void $this->dispatcher->dispatch($event); } - public function testNoListeners(): void + #[Test] + public function it_does_nothing_when_there_are_no_listeners(): void { $event = $this->createMock(DomainEvent::class); $this->listeners->expects($this->never())->method($this->anything()); $this->dispatcher->dispatch($event); } - public function testItDispatchesThroughMiddleware(): void + #[Test] + public function it_dispatches_through_middleware(): void { $event1 = new TestImmediateDomainEvent(); $event2 = new TestImmediateDomainEvent(); @@ -330,7 +344,8 @@ public function testItDispatchesThroughMiddleware(): void $this->dispatcher->dispatch($event1); } - public function testListenerDoesNotHaveHandleMethod(): void + #[Test] + public function it_fails_when_the_listener_does_not_have_a_handle_method(): void { $event = new TestImmediateDomainEvent(); @@ -347,7 +362,8 @@ public function testListenerDoesNotHaveHandleMethod(): void $this->dispatcher->dispatch($event); } - public function testListenerCannotImplementBothBeforeAndAfterCommit(): void + #[Test] + public function it_fails_when_a_listener_implements_both_before_and_after_commit(): void { $listener = new class () implements DispatchBeforeCommit, DispatchAfterCommit { public function handle(): void diff --git a/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php b/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php index 9b321d52..0d2f19a1 100644 --- a/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php +++ b/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php @@ -16,12 +16,14 @@ use CloudCreativity\Modules\Bus\EventHandler; use CloudCreativity\Modules\Bus\EventHandlerContainer; use CloudCreativity\Modules\Tests\Unit\Infrastructure\OutboundEventBus\TestOutboundEvent; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; final class EventHandlerContainerTest extends TestCase { - public function testItHasHandlerBindings(): void + #[Test] + public function it_has_handler_bindings(): void { $a = new class () extends TestEventHandler {}; $b = $this->createStub(TestEventHandler::class); @@ -34,7 +36,8 @@ public function testItHasHandlerBindings(): void $this->assertEquals(new EventHandler($b), $container->get(TestOutboundEvent::class)); } - public function testItUsesPsrContainer(): void + #[Test] + public function it_uses_psr_container(): void { $a = new class () extends TestEventHandler {}; $b = $this->createStub(TestEventHandler::class); @@ -57,7 +60,8 @@ public function testItUsesPsrContainer(): void $this->assertEquals(new EventHandler($b), $container->get(TestOutboundEvent::class)); } - public function testItHasBoundDefaultHandler(): void + #[Test] + public function it_has_bound_default_handler(): void { $a = new class () extends TestEventHandler {}; $b = $this->createStub(TestEventHandler::class); @@ -69,7 +73,8 @@ public function testItHasBoundDefaultHandler(): void $this->assertEquals(new EventHandler($b), $container->get(TestOutboundEvent::class)); } - public function testItHasDefaultHandlerInPsrContainer(): void + #[Test] + public function it_has_default_handler_in_psr_container(): void { $a = new class () extends TestEventHandler {}; $b = $this->createStub(TestEventHandler::class); @@ -89,7 +94,8 @@ public function testItHasDefaultHandlerInPsrContainer(): void } - public function testItDoesNotHaveHandler(): void + #[Test] + public function it_does_not_have_handler(): void { $container = new EventHandlerContainer(); $container->bind(TestInboundEvent::class, fn () => new class () extends TestEventHandler {}); diff --git a/tests/Unit/Application/InboundEventBus/EventHandlerTest.php b/tests/Unit/Application/InboundEventBus/EventHandlerTest.php index 0aa87502..e3ba1a81 100644 --- a/tests/Unit/Application/InboundEventBus/EventHandlerTest.php +++ b/tests/Unit/Application/InboundEventBus/EventHandlerTest.php @@ -13,11 +13,13 @@ namespace CloudCreativity\Modules\Tests\Unit\Application\InboundEventBus; use CloudCreativity\Modules\Bus\EventHandler; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class EventHandlerTest extends TestCase { - public function test(): void + #[Test] + public function it_handles_the_event_and_returns_its_middleware(): void { $event = new TestInboundEvent(); @@ -38,7 +40,8 @@ public function test(): void $this->assertSame($middleware, $handler->middleware()); } - public function testItDoesNotHaveExecuteMethod(): void + #[Test] + public function it_does_not_have_execute_method(): void { $handler = new EventHandler(new \DateTime()); $event = new TestInboundEvent(); diff --git a/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php b/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php index 537eb34e..a3755e86 100644 --- a/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php +++ b/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php @@ -17,6 +17,7 @@ use CloudCreativity\Modules\Contracts\Bus\EventHandlerContainer; use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -49,7 +50,8 @@ protected function tearDown(): void parent::tearDown(); } - public function test(): void + #[Test] + public function it_dispatches_an_event(): void { $event = $this->createMock(IntegrationEvent::class); @@ -67,7 +69,8 @@ public function test(): void $this->dispatcher->dispatch($event); } - public function testWithMiddleware(): void + #[Test] + public function it_dispatches_an_event_through_middleware(): void { $event1 = new TestInboundEvent(); $event2 = new TestInboundEvent(); diff --git a/tests/Unit/Application/InboundEventBus/Middleware/SetupBeforeEventTest.php b/tests/Unit/Application/InboundEventBus/Middleware/SetupBeforeEventTest.php index 149d8bd7..c8658959 100644 --- a/tests/Unit/Application/InboundEventBus/Middleware/SetupBeforeEventTest.php +++ b/tests/Unit/Application/InboundEventBus/Middleware/SetupBeforeEventTest.php @@ -16,6 +16,7 @@ use CloudCreativity\Modules\Bus\Middleware\SetupBeforeEvent; use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -26,7 +27,8 @@ final class SetupBeforeEventTest extends TestCase */ private array $sequence = []; - public function testItSetsUpAndSucceedsWithoutTeardown(): void + #[Test] + public function it_sets_up_and_succeeds_without_teardown(): void { $event = $this->createMock(IntegrationEvent::class); @@ -43,7 +45,8 @@ public function testItSetsUpAndSucceedsWithoutTeardown(): void $this->assertSame(['setup', 'next'], $this->sequence); } - public function testItSetsUpAndSucceedsWithTeardown(): void + #[Test] + public function it_sets_up_and_succeeds_with_teardown(): void { $event = $this->createMock(IntegrationEvent::class); @@ -62,7 +65,8 @@ public function testItSetsUpAndSucceedsWithTeardown(): void $this->assertSame(['setup', 'next', 'teardown'], $this->sequence); } - public function testItSetsUpAndThrowsExceptionWithoutTeardown(): void + #[Test] + public function it_sets_up_and_throws_exception_without_teardown(): void { $event = $this->createMock(IntegrationEvent::class); $exception = new RuntimeException('Something went wrong.'); @@ -88,7 +92,8 @@ public function testItSetsUpAndThrowsExceptionWithoutTeardown(): void $this->assertSame(['setup', 'next'], $this->sequence); } - public function testItSetsUpAndThrowsExceptionWithTeardown(): void + #[Test] + public function it_sets_up_and_throws_exception_with_teardown(): void { $event = $this->createMock(IntegrationEvent::class); $exception = new RuntimeException('Something went wrong.'); diff --git a/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php b/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php index 9cbf0724..edde736f 100644 --- a/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php +++ b/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php @@ -14,12 +14,14 @@ use CloudCreativity\Modules\Bus\Middleware\TearDownAfterEvent; use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; final class TearDownAfterEventTest extends TestCase { - public function testItInvokesCallbackAfterSuccess(): void + #[Test] + public function it_invokes_callback_after_success(): void { $event = $this->createMock(IntegrationEvent::class); $sequence = []; @@ -36,7 +38,8 @@ public function testItInvokesCallbackAfterSuccess(): void $this->assertSame(['next', 'teardown'], $sequence); } - public function testItInvokesCallbackAfterException(): void + #[Test] + public function it_invokes_callback_after_exception(): void { $event = $this->createMock(IntegrationEvent::class); $exception = new RuntimeException('Something went wrong.'); diff --git a/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php b/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php index 9a49822e..48c1e12f 100644 --- a/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php +++ b/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php @@ -14,13 +14,15 @@ use CloudCreativity\Modules\Bus\SwallowInboundEvent; use CloudCreativity\Modules\Toolkit\ModuleBasename; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; final class SwallowInboundEventTest extends TestCase { - public function testItDoesNothing(): void + #[Test] + public function it_does_nothing(): void { $handler = new SwallowInboundEvent(); $handler->handle(new TestInboundEvent()); @@ -28,7 +30,8 @@ public function testItDoesNothing(): void $this->assertTrue(true); } - public function testItLogsThatItDoesNothing(): void + #[Test] + public function it_logs_that_it_does_nothing(): void { $event = new TestInboundEvent(); $name = ModuleBasename::from($event); @@ -46,7 +49,8 @@ public function testItLogsThatItDoesNothing(): void $handler->handle($event); } - public function testItLogsThatItDoesNothingWithSpecifiedLogLevel(): void + #[Test] + public function it_logs_that_it_does_nothing_with_specified_log_level(): void { $event = new TestInboundEvent(); $name = ModuleBasename::from($event); diff --git a/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php b/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php index 7def504f..3880c821 100644 --- a/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php +++ b/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php @@ -17,6 +17,7 @@ use CloudCreativity\Modules\Contracts\Application\Ports\ExceptionReporter; use CloudCreativity\Modules\Contracts\Application\Ports\UnitOfWork; use LogicException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -39,7 +40,14 @@ protected function setUp(): void ); } - public function testItExecutesCallbacks(): void + protected function tearDown(): void + { + unset($this->manager, $this->unitOfWork, $this->reporter); + parent::tearDown(); + } + + #[Test] + public function it_executes_callbacks(): void { $sequence = []; @@ -88,7 +96,8 @@ public function testItExecutesCallbacks(): void $this->assertSame($expected, $actual); } - public function testItExecutesCallbackWhenTransactionFailsToCommit(): void + #[Test] + public function it_executes_callback_when_transaction_fails_to_commit(): void { $expected = new \RuntimeException('Boom'); $sequence = []; @@ -134,7 +143,8 @@ public function testItExecutesCallbackWhenTransactionFailsToCommit(): void /** * If any callbacks get registered by other callbacks, they are executed. */ - public function testItExecutesAdditionalCommitCallbacks(): void + #[Test] + public function it_executes_additional_commit_callbacks(): void { $sequence = []; @@ -211,7 +221,8 @@ function () use (&$sequence): void { $this->assertSame($expected, $actual); } - public function testItFlushesCallbacksOnSuccessfulTransaction(): void + #[Test] + public function it_flushes_callbacks_on_successful_transaction(): void { $this->unitOfWork ->method('execute') @@ -230,7 +241,8 @@ public function testItFlushesCallbacksOnSuccessfulTransaction(): void $this->assertSame(2, $result2); } - public function testItFlushesCallbacksOnUnsuccessfulTransaction(): void + #[Test] + public function it_flushes_callbacks_on_unsuccessful_transaction(): void { $ex = new LogicException('Boom'); $count = 0; @@ -279,7 +291,8 @@ public function testItFlushesCallbacksOnUnsuccessfulTransaction(): void * is thrown should be forgotten. Otherwise, if the callback is retried, the before * callbacks will be executed twice. */ - public function testItHandlesCallbackExecutingMultipleTimes(): void + #[Test] + public function it_handles_callback_executing_multiple_times(): void { $ex = new LogicException('Boom!'); $sequence = []; @@ -368,7 +381,8 @@ function () use (&$sequence): void { * because any that are registered on one of the failed attempts should havbe been * forgotten. */ - public function testItHandlesUnitOfWorkFailingMultipleTimes(): void + #[Test] + public function it_handles_unit_of_work_failing_multiple_times(): void { $ex = new LogicException('Boom!'); $sequence = []; @@ -439,7 +453,8 @@ function () use (&$sequence): void { ], $sequence); } - public function testItFailsIfBeforeCallbacksAreQueuedBeforeTransaction(): void + #[Test] + public function it_fails_if_before_callbacks_are_queued_before_transaction(): void { $this->unitOfWork ->expects($this->never()) @@ -451,7 +466,8 @@ public function testItFailsIfBeforeCallbacksAreQueuedBeforeTransaction(): void $this->manager->beforeCommit(fn () => null); } - public function testItFailsIfAfterCallbacksAreQueuedBeforeTransaction(): void + #[Test] + public function it_fails_if_after_callbacks_are_queued_before_transaction(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Cannot queue an after commit callback when not executing a unit of work.'); @@ -459,7 +475,8 @@ public function testItFailsIfAfterCallbacksAreQueuedBeforeTransaction(): void $this->manager->afterCommit(fn () => null); } - public function testItCannotStartTransactionWithinAnExistingOne(): void + #[Test] + public function it_cannot_start_transaction_within_an_existing_one(): void { $this->unitOfWork ->expects($this->once()) @@ -476,7 +493,8 @@ public function testItCannotStartTransactionWithinAnExistingOne(): void }); } - public function testItFailsIfAfterCommitCallbackRegistersBeforeCommitCallback(): void + #[Test] + public function it_fails_if_after_commit_callback_registers_before_commit_callback(): void { $this->unitOfWork ->method('execute') @@ -492,7 +510,8 @@ public function testItFailsIfAfterCommitCallbackRegistersBeforeCommitCallback(): }); } - public function testAttemptsMustBeGreaterThanZero(): void + #[Test] + public function it_fails_if_attempts_is_not_greater_than_zero(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Attempts must be greater than zero.'); diff --git a/tests/Unit/Bus/PsrPipeContainerTest.php b/tests/Unit/Bus/PsrPipeContainerTest.php index a7508e89..eb8fdb77 100644 --- a/tests/Unit/Bus/PsrPipeContainerTest.php +++ b/tests/Unit/Bus/PsrPipeContainerTest.php @@ -13,12 +13,14 @@ namespace CloudCreativity\Modules\Tests\Unit\Bus; use CloudCreativity\Modules\Bus\PsrPipeContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; final class PsrPipeContainerTest extends TestCase { - public function testItResolvesBoundPipes(): void + #[Test] + public function it_resolves_bound_pipes(): void { $a = fn () => 1; $b = fn () => 2; @@ -36,7 +38,8 @@ public function testItResolvesBoundPipes(): void $container->get('PipeC'); } - public function testItFallsBackToPsrContainer(): void + #[Test] + public function it_falls_back_to_psr_container(): void { $psrContainer = $this->createMock(ContainerInterface::class); diff --git a/tests/Unit/Domain/EntityTest.php b/tests/Unit/Domain/EntityTest.php index 68ee901c..ecf42c1d 100644 --- a/tests/Unit/Domain/EntityTest.php +++ b/tests/Unit/Domain/EntityTest.php @@ -17,11 +17,13 @@ use CloudCreativity\Modules\Domain\IsEntity; use CloudCreativity\Modules\Toolkit\Identifiers\Guid; use CloudCreativity\Modules\Toolkit\Identifiers\IntegerId; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class EntityTest extends TestCase { - public function test(): void + #[Test] + public function it_has_an_id(): void { $entity = new TestEntity($guid = Guid::fromInteger('SomeType', 1)); @@ -31,7 +33,8 @@ public function test(): void $this->assertTrue($entity->isNot(null)); } - public function testItIsTheSame(): void + #[Test] + public function it_is_the_same(): void { $a = new TestEntity( $id1 = $this->createMock(Identifier::class), @@ -51,7 +54,8 @@ public function testItIsTheSame(): void $this->assertFalse($a->isNot($b)); } - public function testItIsNotTheSame(): void + #[Test] + public function it_is_not_the_same(): void { $a = new TestEntity( $id1 = $this->createMock(Identifier::class), @@ -71,7 +75,8 @@ public function testItIsNotTheSame(): void $this->assertTrue($a->isNot($b)); } - public function testItIsDifferentClass(): void + #[Test] + public function it_is_different_class(): void { $a = new TestEntity( $id1 = $this->createMock(Identifier::class), @@ -88,7 +93,8 @@ public function testItIsDifferentClass(): void $this->assertTrue($a->isNot($b)); } - public function testItCanUseTraitOnNonReadonlyClass(): void + #[Test] + public function it_can_use_trait_on_non_readonly_class(): void { $id = new IntegerId(123); diff --git a/tests/Unit/Domain/EntityWithNullableGuidTest.php b/tests/Unit/Domain/EntityWithNullableGuidTest.php index 63af7236..de481945 100644 --- a/tests/Unit/Domain/EntityWithNullableGuidTest.php +++ b/tests/Unit/Domain/EntityWithNullableGuidTest.php @@ -17,11 +17,13 @@ use CloudCreativity\Modules\Toolkit\ContractException; use CloudCreativity\Modules\Toolkit\Identifiers\Guid; use PHPUnit\Framework\Attributes\Depends; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class EntityWithNullableGuidTest extends TestCase { - public function test(): void + #[Test] + public function it_has_an_id(): void { $entity = new TestEntityWithNullableId( $guid = Guid::fromInteger('SomeType', 1), @@ -34,7 +36,8 @@ public function test(): void $this->assertTrue($entity->hasId()); } - public function testWithNullId(): TestEntityWithNullableId + #[Test] + public function it_has_a_null_id(): TestEntityWithNullableId { $entity = new TestEntityWithNullableId(); @@ -46,8 +49,9 @@ public function testWithNullId(): TestEntityWithNullableId return $entity; } - #[Depends('testWithNullId')] - public function testGetIdOrFailWithoutId(TestEntityWithNullableId $entity): void + #[Depends('it_has_a_null_id')] + #[Test] + public function it_fails_to_get_the_id_when_it_is_null(TestEntityWithNullableId $entity): void { $this->expectException(\AssertionError::class); $this->expectExceptionMessage('Entity does not have an identifier.'); @@ -55,7 +59,8 @@ public function testGetIdOrFailWithoutId(TestEntityWithNullableId $entity): void $entity->getIdOrFail(); } - public function testSetId(): void + #[Test] + public function it_sets_the_id(): void { $entity = new TestEntityWithNullableId(); $actual = $entity->setId($guid = Guid::fromInteger('SomeType', 99)); @@ -64,7 +69,8 @@ public function testSetId(): void $this->assertSame($guid, $entity->getId()); } - public function testSetIdWhenEntityHasGuid(): void + #[Test] + public function it_cannot_set_the_id_when_the_entity_already_has_one(): void { $entity = new TestEntityWithNullableId(Guid::fromInteger('SomeType', 1)); @@ -72,7 +78,8 @@ public function testSetIdWhenEntityHasGuid(): void $entity->setId(Guid::fromInteger('SomeType', 2)); } - public function testItIsTheSame(): void + #[Test] + public function it_is_the_same(): void { $a = new TestEntityWithNullableId( $id1 = $this->createMock(Identifier::class), @@ -92,7 +99,8 @@ public function testItIsTheSame(): void $this->assertFalse($a->isNot($b)); } - public function testItIsNotTheSameWithNullId(): void + #[Test] + public function it_is_not_the_same_with_null_id(): void { $a = new TestEntityWithNullableId(); @@ -108,7 +116,8 @@ public function testItIsNotTheSameWithNullId(): void $this->assertTrue($a->isNot($b)); } - public function testItIsTheSameWhenOtherHasNullId(): void + #[Test] + public function it_is_the_same_when_other_has_null_id(): void { $a = new TestEntityWithNullableId( $id1 = $this->createMock(Identifier::class), @@ -126,7 +135,8 @@ public function testItIsTheSameWhenOtherHasNullId(): void $this->assertTrue($a->isNot($b)); } - public function testItIsNotTheSame(): void + #[Test] + public function it_is_not_the_same(): void { $a = new TestEntityWithNullableId( $id1 = $this->createMock(Identifier::class), @@ -146,7 +156,8 @@ public function testItIsNotTheSame(): void $this->assertTrue($a->isNot($b)); } - public function testItIsDifferentClass(): void + #[Test] + public function it_is_different_class(): void { $a = new TestEntityWithNullableId( $id1 = $this->createMock(Identifier::class), diff --git a/tests/Unit/Domain/EntityWithTypedIdTest.php b/tests/Unit/Domain/EntityWithTypedIdTest.php index 799b409a..67c2965e 100644 --- a/tests/Unit/Domain/EntityWithTypedIdTest.php +++ b/tests/Unit/Domain/EntityWithTypedIdTest.php @@ -16,11 +16,13 @@ use CloudCreativity\Modules\Domain\IsEntityWithTypedId; use CloudCreativity\Modules\Toolkit\Identifiers\IntegerId; use CloudCreativity\Modules\Toolkit\Identifiers\UuidV7; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class EntityWithTypedIdTest extends TestCase { - public function test(): void + #[Test] + public function it_has_a_typed_id(): void { $entity = new TestEntityWithTypedId($id = UuidV7::make()); @@ -31,7 +33,8 @@ public function test(): void $this->assertTrue($entity->isNot(null)); } - public function testItIsTheSame(): void + #[Test] + public function it_is_the_same(): void { $a = new TestEntityWithTypedId( $id1 = UuidV7::make(), @@ -45,7 +48,8 @@ public function testItIsTheSame(): void $this->assertFalse($a->isNot($b)); } - public function testItIsNotTheSame(): void + #[Test] + public function it_is_not_the_same(): void { $a = new TestEntityWithTypedId(UuidV7::make()); $b = new TestEntityWithTypedId(UuidV7::make()); @@ -54,7 +58,8 @@ public function testItIsNotTheSame(): void $this->assertTrue($a->isNot($b)); } - public function testItIsDifferentClass(): void + #[Test] + public function it_is_different_class(): void { $a = new TestEntityWithTypedId(UuidV7::make()); $b = $this->createMock(Entity::class); @@ -64,7 +69,8 @@ public function testItIsDifferentClass(): void $this->assertTrue($a->isNot($b)); } - public function testItCanUseTraitOnNonReadonlyClass(): void + #[Test] + public function it_can_use_trait_on_non_readonly_class(): void { $id = new IntegerId(123); diff --git a/tests/Unit/Domain/IdentifierOrEntityTest.php b/tests/Unit/Domain/IdentifierOrEntityTest.php index 1ca11594..8071d73c 100644 --- a/tests/Unit/Domain/IdentifierOrEntityTest.php +++ b/tests/Unit/Domain/IdentifierOrEntityTest.php @@ -15,11 +15,13 @@ use CloudCreativity\Modules\Contracts\Domain\Entity; use CloudCreativity\Modules\Domain\IdentifierOrEntity; use CloudCreativity\Modules\Toolkit\Identifiers\Guid; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class IdentifierOrEntityTest extends TestCase { - public function testItIsAGuid(): void + #[Test] + public function it_is_a_guid(): void { $guidOrEntity = IdentifierOrEntity::make($guid = Guid::fromInteger('SomeType', 1)); @@ -28,7 +30,8 @@ public function testItIsAGuid(): void $this->assertNull($guidOrEntity->entity); } - public function testItIsAnEntityWithGuid(): void + #[Test] + public function it_is_an_entity_with_guid(): void { $entity = $this->createMock(Entity::class); $entity->method('getId')->willReturn($guid = Guid::fromInteger('SomeType', 1)); @@ -40,7 +43,8 @@ public function testItIsAnEntityWithGuid(): void $this->assertSame($entity, $guidOrEntity->entity); } - public function testItIsAnEntityWithoutGuid(): void + #[Test] + public function it_is_an_entity_without_guid(): void { $entity = $this->createMock(Entity::class); $entity->method('getId')->willReturn(null); diff --git a/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php b/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php index 9a038cb4..eb124256 100644 --- a/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php +++ b/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php @@ -15,6 +15,7 @@ use CloudCreativity\Modules\Contracts\Application\Ports\ExceptionReporter; use CloudCreativity\Modules\Infrastructure\ExceptionReporter\PsrLogExceptionReporter; use LogicException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -34,11 +35,12 @@ protected function setUp(): void protected function tearDown(): void { - parent::tearDown(); unset($this->logger, $this->reporter); + parent::tearDown(); } - public function testItReportsException(): void + #[Test] + public function it_reports_exception(): void { $exception = new LogicException('Test exception'); @@ -55,7 +57,8 @@ public function testItReportsException(): void $this->assertInstanceOf(ExceptionReporter::class, $this->reporter); } - public function testItReportsDefaultMessageIfExceptionHasEmptyMessage(): void + #[Test] + public function it_reports_default_message_if_exception_has_empty_message(): void { $exception = new LogicException(); @@ -70,7 +73,8 @@ public function testItReportsDefaultMessageIfExceptionHasEmptyMessage(): void $this->reporter->report($exception); } - public function testItLogsContextForExceptionThatImplementsContextProvider(): void + #[Test] + public function it_logs_context_for_exception_that_implements_context_provider(): void { $exception = new class ('Boom!') extends LogicException { /** @@ -98,7 +102,8 @@ public function context(): array $this->reporter->report($exception); } - public function testItLogsContextForExceptionThatHasContextMethod(): void + #[Test] + public function it_logs_context_for_exception_that_has_context_method(): void { $exception = new class ('Boom!') extends LogicException { /** diff --git a/tests/Unit/Infrastructure/InfrastructureExceptionTest.php b/tests/Unit/Infrastructure/InfrastructureExceptionTest.php index 05093007..7da23108 100644 --- a/tests/Unit/Infrastructure/InfrastructureExceptionTest.php +++ b/tests/Unit/Infrastructure/InfrastructureExceptionTest.php @@ -13,12 +13,14 @@ namespace CloudCreativity\Modules\Tests\Unit\Infrastructure; use CloudCreativity\Modules\Infrastructure\InfrastructureException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; final class InfrastructureExceptionTest extends TestCase { - public function test(): void + #[Test] + public function it_is_a_runtime_exception(): void { $ex = new InfrastructureException(); $this->assertInstanceOf(RuntimeException::class, $ex); diff --git a/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php b/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php index c61d0a27..fd7ad3d2 100644 --- a/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php +++ b/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php @@ -15,6 +15,7 @@ use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer as IPipeContainer; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\ClosurePublisher; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; @@ -27,11 +28,12 @@ final class ClosurePublisherTest extends TestCase protected function tearDown(): void { - parent::tearDown(); unset($this->actual); + parent::tearDown(); } - public function test(): void + #[Test] + public function it_publishes_an_event(): void { $event = $this->createStub(IntegrationEvent::class); @@ -41,7 +43,8 @@ public function test(): void $this->assertSame([$event], $this->actual); } - public function testWithMiddleware(): void + #[Test] + public function it_publishes_an_event_through_middleware(): void { $event1 = $this->createStub(IntegrationEvent::class); $event2 = $this->createStub(IntegrationEvent::class); @@ -82,7 +85,8 @@ public function testWithMiddleware(): void $this->assertSame([$event4], $this->actual); } - public function testWithMiddlewareViaPsrContainer(): void + #[Test] + public function it_publishes_through_middleware_resolved_from_a_psr_container(): void { $event1 = $this->createStub(IntegrationEvent::class); $event2 = $this->createStub(IntegrationEvent::class); @@ -117,7 +121,8 @@ public function testWithMiddlewareViaPsrContainer(): void } - public function testWithAlternativeHandlers(): void + #[Test] + public function it_publishes_using_the_handler_bound_to_the_event_class(): void { $expected = new class () extends TestOutboundEvent {}; $stub = $this->createStub(IntegrationEvent::class); diff --git a/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php b/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php index bd1082bf..fcc885e0 100644 --- a/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php +++ b/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php @@ -17,6 +17,7 @@ use CloudCreativity\Modules\Contracts\Infrastructure\OutboundEventBus\PublisherHandlerContainer; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\ComponentPublisher; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -52,7 +53,8 @@ protected function tearDown(): void parent::tearDown(); } - public function testPublish(): void + #[Test] + public function it_publishes_an_event(): void { $event = new class () extends TestOutboundEvent {}; @@ -70,7 +72,8 @@ public function testPublish(): void $this->publisher->publish($event); } - public function testPublishWithMiddleware(): void + #[Test] + public function it_publishes_an_event_through_middleware(): void { $event1 = new class () extends TestOutboundEvent {}; $event2 = new class () extends TestOutboundEvent {}; diff --git a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php index 67de852b..5dc09671 100644 --- a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php +++ b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php @@ -14,13 +14,15 @@ use CloudCreativity\Modules\Infrastructure\OutboundEventBus\PublisherHandler; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\PublisherHandlerContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use RuntimeException; final class PublisherHandlerContainerTest extends TestCase { - public function testItPublishesViaBindingsWithoutDefaultHandler(): void + #[Test] + public function it_publishes_via_bindings_without_default_handler(): void { $a = new class () extends TestPublisher {}; $b = $this->createStub(TestPublisher::class); @@ -42,7 +44,8 @@ public function testItPublishesViaBindingsWithoutDefaultHandler(): void $container->get($event3::class); } - public function testItPublishesViaBindingsWithDefaultHandler(): void + #[Test] + public function it_publishes_via_bindings_with_default_handler(): void { $a = new class () extends TestPublisher {}; $b = $this->createStub(TestPublisher::class); @@ -59,7 +62,8 @@ public function testItPublishesViaBindingsWithDefaultHandler(): void $this->assertEquals($default, $container->get($event3::class)); } - public function testItPublishesViaPsrContainerWithoutDefaultHandler(): void + #[Test] + public function it_publishes_via_psr_container_without_default_handler(): void { $a = new class () extends TestPublisher {}; $b = $this->createStub(TestPublisher::class); @@ -91,7 +95,8 @@ public function testItPublishesViaPsrContainerWithoutDefaultHandler(): void $container->get($event3::class); } - public function testItPublishesViaPsrContainerWithDefaultHandler(): void + #[Test] + public function it_publishes_via_psr_container_with_default_handler(): void { $a = new class () extends TestPublisher {}; $b = $this->createStub(TestPublisher::class); diff --git a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php index 2d205878..3f2e52e2 100644 --- a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php +++ b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php @@ -14,11 +14,13 @@ use CloudCreativity\Modules\Contracts\Infrastructure\OutboundEventBus\PublisherHandler as IPublisherHandler; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\PublisherHandler; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class PublisherHandlerTest extends TestCase { - public function test(): void + #[Test] + public function it_publishes_the_event_via_the_inner_publisher(): void { $event = new class () extends TestOutboundEvent {}; $innerHandler = $this->createMock(TestPublisher::class); diff --git a/tests/Unit/Infrastructure/Queue/ClosureQueueTest.php b/tests/Unit/Infrastructure/Queue/ClosureQueueTest.php index 45d2a2b1..bbc981f7 100644 --- a/tests/Unit/Infrastructure/Queue/ClosureQueueTest.php +++ b/tests/Unit/Infrastructure/Queue/ClosureQueueTest.php @@ -16,6 +16,7 @@ use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; use CloudCreativity\Modules\Infrastructure\Queue\ClosureQueue; use CloudCreativity\Modules\Tests\Unit\Application\Bus\TestCommand; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -44,11 +45,12 @@ function (Command $command): void { protected function tearDown(): void { - parent::tearDown(); unset($this->queue, $this->middleware, $this->actual); + parent::tearDown(); } - public function test(): void + #[Test] + public function it_queues_a_command(): void { $command = $this->createMock(Command::class); @@ -57,7 +59,8 @@ public function test(): void $this->assertSame([$command], $this->actual); } - public function testWithMiddleware(): void + #[Test] + public function it_queues_a_command_through_middleware(): void { $command1 = $this->createMock(Command::class); $command2 = $this->createMock(Command::class); @@ -97,7 +100,8 @@ public function testWithMiddleware(): void } - public function testWithAlternativeHandlers(): void + #[Test] + public function it_queues_using_the_handler_bound_to_the_command_class(): void { $expected = new TestCommand(); $mock = $this->createMock(Command::class); diff --git a/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php b/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php index 88be9225..82c76cfd 100644 --- a/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php +++ b/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php @@ -17,6 +17,7 @@ use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; use CloudCreativity\Modules\Infrastructure\Queue\ComponentQueue; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -49,7 +50,8 @@ protected function tearDown(): void parent::tearDown(); } - public function test(): void + #[Test] + public function it_queues_a_command(): void { $command = $this->createMock(Command::class); @@ -67,7 +69,8 @@ public function test(): void $this->queue->push($command); } - public function testItQueuesThroughMiddleware(): void + #[Test] + public function it_queues_through_middleware(): void { $command1 = $this->createMock(Command::class); $command2 = $this->createMock(Command::class); diff --git a/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php b/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php index 05333953..9a3c11a1 100644 --- a/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php +++ b/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php @@ -16,12 +16,14 @@ use CloudCreativity\Modules\Infrastructure\Queue\Enqueuer; use CloudCreativity\Modules\Infrastructure\Queue\EnqueuerContainer; use CloudCreativity\Modules\Tests\Unit\Application\Bus\TestCommand; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; final class EnqueuerContainerTest extends TestCase { - public function testItUsesBindings(): void + #[Test] + public function it_uses_bindings(): void { $command1 = new class () implements Command {}; $command2 = new class () implements Command {}; @@ -39,7 +41,8 @@ public function testItUsesBindings(): void $this->assertEquals(new Enqueuer($default), $container->get(TestCommand::class)); } - public function testItUsesPsrContainer(): void + #[Test] + public function it_uses_psr_container(): void { $command1 = new class () implements Command {}; $command2 = new class () implements Command {}; diff --git a/tests/Unit/Infrastructure/Queue/EnqueuerTest.php b/tests/Unit/Infrastructure/Queue/EnqueuerTest.php index c7f24221..4765a134 100644 --- a/tests/Unit/Infrastructure/Queue/EnqueuerTest.php +++ b/tests/Unit/Infrastructure/Queue/EnqueuerTest.php @@ -14,11 +14,13 @@ use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Infrastructure\Queue\Enqueuer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class EnqueuerTest extends TestCase { - public function test(): void + #[Test] + public function it_pushes_the_command_to_the_inner_enqueuer(): void { $command = $this->createMock(Command::class); $innerEnqueuer = $this->createMock(TestEnqueuer::class); diff --git a/tests/Unit/Testing/FakeDomainEventDispatcherTest.php b/tests/Unit/Testing/FakeDomainEventDispatcherTest.php index 46752b62..ac8370e4 100644 --- a/tests/Unit/Testing/FakeDomainEventDispatcherTest.php +++ b/tests/Unit/Testing/FakeDomainEventDispatcherTest.php @@ -16,11 +16,13 @@ use CloudCreativity\Modules\Contracts\Domain\Events\DomainEventDispatcher; use CloudCreativity\Modules\Testing\FakeDomainEventDispatcher; use LogicException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class FakeDomainEventDispatcherTest extends TestCase { - public function testItPublishesEvents(): void + #[Test] + public function it_publishes_events(): void { $dispatcher = new class () extends FakeDomainEventDispatcher {}; @@ -40,7 +42,8 @@ public function testItPublishesEvents(): void $this->assertSame($event2, $dispatcher[1]); } - public function testItReturnsSoleEvent(): void + #[Test] + public function it_returns_sole_event(): void { $dispatcher = new class () extends FakeDomainEventDispatcher {}; $event = $this->createMock(DomainEvent::class); @@ -50,7 +53,8 @@ public function testItReturnsSoleEvent(): void $this->assertSame($event, $dispatcher->sole()); } - public function testItThrowsExceptionIfNoEvents(): void + #[Test] + public function it_throws_exception_if_no_events(): void { $dispatcher = new class () extends FakeDomainEventDispatcher {}; @@ -60,7 +64,8 @@ public function testItThrowsExceptionIfNoEvents(): void $dispatcher->sole(); } - public function testItThrowsExceptionIfMultipleEvents(): void + #[Test] + public function it_throws_exception_if_multiple_events(): void { $dispatcher = new class () extends FakeDomainEventDispatcher {}; $event1 = $this->createMock(DomainEvent::class); diff --git a/tests/Unit/Testing/FakeExceptionReporterTest.php b/tests/Unit/Testing/FakeExceptionReporterTest.php index 5f872f01..adff2698 100644 --- a/tests/Unit/Testing/FakeExceptionReporterTest.php +++ b/tests/Unit/Testing/FakeExceptionReporterTest.php @@ -15,12 +15,14 @@ use CloudCreativity\Modules\Contracts\Application\Ports\ExceptionReporter; use CloudCreativity\Modules\Testing\FakeExceptionReporter; use LogicException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; final class FakeExceptionReporterTest extends TestCase { - public function testItReportsExceptions(): void + #[Test] + public function it_reports_exceptions(): void { $reporter = new FakeExceptionReporter(); $reporter->report($ex1 = new RuntimeException('Whoops!')); @@ -34,7 +36,8 @@ public function testItReportsExceptions(): void $this->assertSame($ex2, $reporter[1]); } - public function testItDoesNotExpectExceptions(): void + #[Test] + public function it_does_not_expect_exceptions(): void { $expected = new RuntimeException('Boom! That was a surprise.'); @@ -45,7 +48,8 @@ public function testItDoesNotExpectExceptions(): void $reporter->report($expected); } - public function testItExpectsExceptions(): void + #[Test] + public function it_expects_exceptions(): void { $expected = new RuntimeException('Boom! That was a surprise.'); @@ -62,7 +66,8 @@ public function testItExpectsExceptions(): void $reporter->report($expected); } - public function testItHasSoleException(): void + #[Test] + public function it_has_sole_exception(): void { $reporter = new FakeExceptionReporter(); $reporter->report($ex = new RuntimeException('Whoops!')); @@ -70,7 +75,8 @@ public function testItHasSoleException(): void $this->assertSame($ex, $reporter->sole()); } - public function testItFailsWhenThereIsNoSoleException(): void + #[Test] + public function it_fails_when_there_is_no_sole_exception(): void { $this->expectExceptionMessage('Expected one exception to be reported but there are 0 exceptions.'); $this->expectException(LogicException::class); @@ -79,7 +85,8 @@ public function testItFailsWhenThereIsNoSoleException(): void $reporter->sole(); } - public function testItFailsWhenThereIsMoreThanOneSoleException(): void + #[Test] + public function it_fails_when_there_is_more_than_one_sole_exception(): void { $this->expectExceptionMessage('Expected one exception to be reported but there are 2 exceptions.'); $this->expectException(LogicException::class); diff --git a/tests/Unit/Testing/FakeOutboundEventPublisherTest.php b/tests/Unit/Testing/FakeOutboundEventPublisherTest.php index 6c2def8a..aed8e515 100644 --- a/tests/Unit/Testing/FakeOutboundEventPublisherTest.php +++ b/tests/Unit/Testing/FakeOutboundEventPublisherTest.php @@ -16,11 +16,13 @@ use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; use CloudCreativity\Modules\Testing\FakeOutboundEventPublisher; use LogicException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class FakeOutboundEventPublisherTest extends TestCase { - public function testItPublishesEvents(): void + #[Test] + public function it_publishes_events(): void { $publisher = new class () extends FakeOutboundEventPublisher {}; @@ -38,7 +40,8 @@ public function testItPublishesEvents(): void $this->assertSame($event2, $publisher[1]); } - public function testItReturnsSoleEvent(): void + #[Test] + public function it_returns_sole_event(): void { $publisher = new class () extends FakeOutboundEventPublisher {}; $event = $this->createMock(IntegrationEvent::class); @@ -48,7 +51,8 @@ public function testItReturnsSoleEvent(): void $this->assertSame($event, $publisher->sole()); } - public function testItThrowsExceptionIfNoEvents(): void + #[Test] + public function it_throws_exception_if_no_events(): void { $publisher = new class () extends FakeOutboundEventPublisher {}; @@ -58,7 +62,8 @@ public function testItThrowsExceptionIfNoEvents(): void $publisher->sole(); } - public function testItThrowsExceptionIfMultipleEvents(): void + #[Test] + public function it_throws_exception_if_multiple_events(): void { $publisher = new class () extends FakeOutboundEventPublisher {}; $event1 = $this->createMock(IntegrationEvent::class); diff --git a/tests/Unit/Testing/FakeQueueTest.php b/tests/Unit/Testing/FakeQueueTest.php index 65ebd497..04e2d521 100644 --- a/tests/Unit/Testing/FakeQueueTest.php +++ b/tests/Unit/Testing/FakeQueueTest.php @@ -16,11 +16,13 @@ use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Testing\FakeQueue; use LogicException; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class FakeQueueTest extends TestCase { - public function testItQueuesCommands(): void + #[Test] + public function it_queues_commands(): void { $queue = new class () extends FakeQueue {}; $queue->push($command1 = $this->createMock(Command::class)); @@ -34,7 +36,8 @@ public function testItQueuesCommands(): void $this->assertSame($command2, $queue[1]); } - public function testItHasSoleCommand(): void + #[Test] + public function it_has_sole_command(): void { $queue = new class () extends FakeQueue {}; $queue->push($command = $this->createMock(Command::class)); @@ -42,7 +45,8 @@ public function testItHasSoleCommand(): void $this->assertSame($command, $queue->sole()); } - public function testItFailsWhenThereIsNoSoleCommand(): void + #[Test] + public function it_fails_when_there_is_no_sole_command(): void { $this->expectExceptionMessage('Expected one command in the queue but there are 0 commands.'); $this->expectException(LogicException::class); @@ -51,7 +55,8 @@ public function testItFailsWhenThereIsNoSoleCommand(): void $queue->sole(); } - public function testItFailsWhenThereIsMoreThanOneSoleCommand(): void + #[Test] + public function it_fails_when_there_is_more_than_one_sole_command(): void { $this->expectExceptionMessage('Expected one command in the queue but there are 2 commands.'); $this->expectException(LogicException::class); diff --git a/tests/Unit/Testing/FakeUnitOfWorkTest.php b/tests/Unit/Testing/FakeUnitOfWorkTest.php index fbd11fe8..2f5cd5f0 100644 --- a/tests/Unit/Testing/FakeUnitOfWorkTest.php +++ b/tests/Unit/Testing/FakeUnitOfWorkTest.php @@ -14,12 +14,14 @@ use CloudCreativity\Modules\Contracts\Application\Ports\UnitOfWork; use CloudCreativity\Modules\Testing\FakeUnitOfWork; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; final class FakeUnitOfWorkTest extends TestCase { - public function testItIsSuccessfulOnFirstAttempt(): void + #[Test] + public function it_is_successful_on_first_attempt(): void { $unitOfWork = new FakeUnitOfWork(); $result = $unitOfWork->execute(fn () => 'result'); @@ -33,7 +35,8 @@ public function testItIsSuccessfulOnFirstAttempt(): void $this->assertSame(0, $unitOfWork->rollbacks); } - public function testItIsSuccessfulBeforeMaxAttempts(): void + #[Test] + public function it_is_successful_before_max_attempts(): void { $ex1 = new RuntimeException('An error occurred.'); $ex2 = new RuntimeException('Another error occurred.'); @@ -64,7 +67,8 @@ public function testItIsSuccessfulBeforeMaxAttempts(): void $this->assertSame(2, $unitOfWork->rollbacks); } - public function testItIsSuccessfulOnMaxAttempts(): void + #[Test] + public function it_is_successful_on_max_attempts(): void { $ex1 = new RuntimeException('An error occurred.'); $ex2 = new RuntimeException('Another error occurred.'); @@ -95,7 +99,8 @@ public function testItIsSuccessfulOnMaxAttempts(): void $this->assertSame(2, $unitOfWork->rollbacks); } - public function testItIsNotSuccessful(): void + #[Test] + public function it_is_not_successful(): void { $ex1 = new RuntimeException('An error occurred.'); $ex2 = new RuntimeException('Another error occurred.'); diff --git a/tests/Unit/Toolkit/ContractsTest.php b/tests/Unit/Toolkit/ContractsTest.php index 2849b656..5e78ad77 100644 --- a/tests/Unit/Toolkit/ContractsTest.php +++ b/tests/Unit/Toolkit/ContractsTest.php @@ -14,11 +14,13 @@ use CloudCreativity\Modules\Toolkit\ContractException; use CloudCreativity\Modules\Toolkit\Contracts; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class ContractsTest extends TestCase { - public function testItDoesNotThrowWhenPreconditionIsTrue(): void + #[Test] + public function it_does_not_throw_when_precondition_is_true(): void { /** @phpstan-ignore-next-line */ Contracts::assert(true, 'Not expected error.'); @@ -27,7 +29,8 @@ public function testItDoesNotThrowWhenPreconditionIsTrue(): void $this->assertTrue(true); } - public function testItDoesNotThrowWhenPreconditionIsTrueWithLazyMessage(): void + #[Test] + public function it_does_not_throw_when_precondition_is_true_with_lazy_message(): void { /** @phpstan-ignore-next-line */ Contracts::assert(true, fn () => $this->fail('Not expected error.')); @@ -36,7 +39,8 @@ public function testItDoesNotThrowWhenPreconditionIsTrueWithLazyMessage(): void $this->assertTrue(true); } - public function testItThrowsWhenPreconditionIsFalse(): void + #[Test] + public function it_throws_when_precondition_is_false(): void { $this->expectException(ContractException::class); $this->expectExceptionMessage($expected = 'The expected message.'); @@ -45,7 +49,8 @@ public function testItThrowsWhenPreconditionIsFalse(): void Contracts::assert(false, $expected); } - public function testItThrowsWhenPreconditionIsFalseWithLazyMessage(): void + #[Test] + public function it_throws_when_precondition_is_false_with_lazy_message(): void { $this->expectException(ContractException::class); $this->expectExceptionMessage($expected = 'The expected message.'); diff --git a/tests/Unit/Toolkit/EnumStringTest.php b/tests/Unit/Toolkit/EnumStringTest.php index 911ddc12..6b7e6495 100644 --- a/tests/Unit/Toolkit/EnumStringTest.php +++ b/tests/Unit/Toolkit/EnumStringTest.php @@ -16,6 +16,7 @@ use CloudCreativity\Modules\Tests\TestBackedIntEnum; use CloudCreativity\Modules\Tests\TestUnitEnum; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use UnitEnum; @@ -53,7 +54,8 @@ public static function valueProvider(): array } #[DataProvider('valueProvider')] - public function testItReturnsScalarValue(string|UnitEnum $value, string $expected): void + #[Test] + public function it_returns_scalar_value(string|UnitEnum $value, string $expected): void { $this->assertSame($expected, enum_string($value)); } diff --git a/tests/Unit/Toolkit/EnumValueTest.php b/tests/Unit/Toolkit/EnumValueTest.php index d4776b2a..d9a686e6 100644 --- a/tests/Unit/Toolkit/EnumValueTest.php +++ b/tests/Unit/Toolkit/EnumValueTest.php @@ -16,6 +16,7 @@ use CloudCreativity\Modules\Tests\TestBackedIntEnum; use CloudCreativity\Modules\Tests\TestUnitEnum; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use UnitEnum; @@ -57,7 +58,8 @@ public static function valueProvider(): array } #[DataProvider('valueProvider')] - public function testItReturnsScalarValue(int|string|UnitEnum $value, int|string $expected): void + #[Test] + public function it_returns_scalar_value(int|string|UnitEnum $value, int|string $expected): void { $this->assertSame($expected, enum_value($value)); } diff --git a/tests/Unit/Toolkit/Identifiers/GuidTest.php b/tests/Unit/Toolkit/Identifiers/GuidTest.php index 3fdc9637..81529c4d 100644 --- a/tests/Unit/Toolkit/Identifiers/GuidTest.php +++ b/tests/Unit/Toolkit/Identifiers/GuidTest.php @@ -23,6 +23,7 @@ use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; use CloudCreativity\Modules\Toolkit\Identifiers\UuidV4; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Ramsey\Uuid\Uuid as BaseUuid; use Ramsey\Uuid\UuidInterface; @@ -57,7 +58,8 @@ public static function typeProvider(): array * @param string|TestUnitEnum $other */ #[DataProvider('typeProvider')] - public function testStringId(string|UnitEnum $type, string $value, string|UnitEnum $other): void + #[Test] + public function it_can_be_created_from_a_string_id(string|UnitEnum $type, string $value, string|UnitEnum $other): void { $guid = Guid::fromString($type, '123'); @@ -89,7 +91,8 @@ public function testStringId(string|UnitEnum $type, string $value, string|UnitEn } #[DataProvider('typeProvider')] - public function testIntegerId(string|UnitEnum $type, string $value, string|UnitEnum $other): void + #[Test] + public function it_can_be_created_from_an_integer_id(string|UnitEnum $type, string $value, string|UnitEnum $other): void { $guid = Guid::fromInteger($type, 123); @@ -111,7 +114,8 @@ public function testIntegerId(string|UnitEnum $type, string $value, string|UnitE } #[DataProvider('typeProvider')] - public function testUuid(string|UnitEnum $type, string $value, string|UnitEnum $other): void + #[Test] + public function it_can_be_created_from_a_uuid(string|UnitEnum $type, string $value, string|UnitEnum $other): void { $uuid = Uuid::random(); $guid = Guid::fromUuid($type, $uuid->value); @@ -150,7 +154,8 @@ public static function makeProvider(): array } #[DataProvider('makeProvider')] - public function testItMakesGuid(int|IUuid|string|UuidInterface $value, Identifier $expected): void + #[Test] + public function it_makes_guid(int|IUuid|string|UuidInterface $value, Identifier $expected): void { $guid = Guid::make('SomeType', $value); $this->assertTrue($expected->is($guid->id)); @@ -158,7 +163,8 @@ public function testItMakesGuid(int|IUuid|string|UuidInterface $value, Identifie $this->assertSame($guid, Guid::tryFrom($guid)); } - public function testFromWithNull(): void + #[Test] + public function it_does_not_accept_null(): void { $this->assertNull(Guid::tryFrom(null)); @@ -166,38 +172,44 @@ public function testFromWithNull(): void Guid::from(null); } - public function testEmptyType(): void + #[Test] + public function it_rejects_an_empty_type(): void { $this->expectException(ContractException::class); Guid::fromString('', '123'); } - public function testEmptyStringId(): void + #[Test] + public function it_rejects_an_empty_string_id(): void { $this->expectException(ContractException::class); Guid::fromString('SomeType', ''); } - public function testNegativeIntegerId(): void + #[Test] + public function it_rejects_a_negative_integer_id(): void { $this->expectException(ContractException::class); Guid::fromInteger('SomeType', -1); } - public function testFromInteger(): void + #[Test] + public function it_wraps_an_integer_in_an_integer_id(): void { $guid = Guid::fromInteger('SomeType', 1); $this->assertObjectEquals(new IntegerId(1), $guid->id); } - public function testFromString(): void + #[Test] + public function it_wraps_a_string_in_a_string_id(): void { $guid = Guid::fromString('SomeType', '1'); $this->assertObjectEquals(new StringId('1'), $guid->id); } #[DataProvider('typeProvider')] - public function testIsTypeWithMultipleTypes(string|UnitEnum $type, string $value, string|UnitEnum $other): void + #[Test] + public function it_checks_if_it_is_any_of_multiple_types(string|UnitEnum $type, string $value, string|UnitEnum $other): void { $guid = Guid::fromInteger($type, 1); @@ -207,7 +219,8 @@ public function testIsTypeWithMultipleTypes(string|UnitEnum $type, string $value } #[DataProvider('typeProvider')] - public function testAssertTypeDoesNotThrowForExpectedType(string|UnitEnum $type): void + #[Test] + public function it_does_not_throw_when_asserting_the_expected_type(string|UnitEnum $type): void { $guid = Guid::fromInteger($type, 1); @@ -216,7 +229,8 @@ public function testAssertTypeDoesNotThrowForExpectedType(string|UnitEnum $type) } #[DataProvider('typeProvider')] - public function testAssertTypeDoesThrowForUnexpectedType( + #[Test] + public function it_throws_when_asserting_an_unexpected_type( string|UnitEnum $type, string $value, string|UnitEnum $other, diff --git a/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php b/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php index f4177698..215f8b8a 100644 --- a/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php +++ b/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php @@ -20,11 +20,13 @@ use CloudCreativity\Modules\Toolkit\Identifiers\GuidTypeMap; use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; use PHPUnit\Framework\Attributes\Depends; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class GuidTypeMapTest extends TestCase { - public function testItReturnsExpectedType(): GuidTypeMap + #[Test] + public function it_returns_expected_type(): GuidTypeMap { $map = new GuidTypeMap([ 'SomeTypeA' => 'SomeOtherTypeA', @@ -41,8 +43,9 @@ public function testItReturnsExpectedType(): GuidTypeMap return $map; } - #[Depends('testItReturnsExpectedType')] - public function testItReturnsExpectedGuid(GuidTypeMap $map): void + #[Depends('it_returns_expected_type')] + #[Test] + public function it_returns_expected_guid(GuidTypeMap $map): void { $this->assertEquals( Guid::fromInteger('SomeOtherTypeA', 99), @@ -55,8 +58,9 @@ public function testItReturnsExpectedGuid(GuidTypeMap $map): void ); } - #[Depends('testItReturnsExpectedType')] - public function testItThrowsIfTypeIsNotValidString(GuidTypeMap $map): void + #[Depends('it_returns_expected_type')] + #[Test] + public function it_throws_if_type_is_not_valid_string(GuidTypeMap $map): void { $this->expectException(AssertionError::class); $this->expectExceptionMessage('Expecting type for alias "NotString" to be a non-empty string.'); @@ -64,8 +68,9 @@ public function testItThrowsIfTypeIsNotValidString(GuidTypeMap $map): void $map->typeFor('NotString'); } - #[Depends('testItReturnsExpectedType')] - public function testItThrowsIfTypeIsEmptyString(GuidTypeMap $map): void + #[Depends('it_returns_expected_type')] + #[Test] + public function it_throws_if_type_is_empty_string(GuidTypeMap $map): void { $this->expectException(AssertionError::class); $this->expectExceptionMessage('Expecting type for alias "EmptyString" to be a non-empty string.'); @@ -73,8 +78,9 @@ public function testItThrowsIfTypeIsEmptyString(GuidTypeMap $map): void $map->typeFor('EmptyString'); } - #[Depends('testItReturnsExpectedType')] - public function testItThrowsIfTypeIsNotDefined(GuidTypeMap $map): void + #[Depends('it_returns_expected_type')] + #[Test] + public function it_throws_if_type_is_not_defined(GuidTypeMap $map): void { $this->expectException(AssertionError::class); $this->expectExceptionMessage('Alias "NotDefined" is not defined in the type map.'); @@ -82,7 +88,8 @@ public function testItThrowsIfTypeIsNotDefined(GuidTypeMap $map): void $map->typeFor('NotDefined'); } - public function testItReturnsExpectedTypeWithEnums(): void + #[Test] + public function it_returns_expected_type_with_enums(): void { $map = new GuidTypeMap(); $map->define(TestBackedEnum::Foo, 'SomeFooType'); diff --git a/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php b/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php index 45f9581a..00980f01 100644 --- a/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php +++ b/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php @@ -20,11 +20,13 @@ use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; use LogicException; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class IntegerIdTest extends TestCase { - public function test(): void + #[Test] + public function it_wraps_an_integer(): void { $id = new IntegerId(99); @@ -39,14 +41,16 @@ public function test(): void ); } - public function testItMustBeGreaterThanZero(): void + #[Test] + public function it_must_be_greater_than_zero(): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Identifier value must be greater than zero.'); new IntegerId(0); } - public function testItIsEquals(): void + #[Test] + public function it_is_equals(): void { $this->assertObjectEquals($id = new IntegerId(99), $other = IntegerId::from(99)); $this->assertSame($id, IntegerId::from($id)); @@ -56,7 +60,8 @@ public function testItIsEquals(): void $this->assertSame($id, IntegerId::tryFrom($id)); } - public function testItIsNotEqual(): void + #[Test] + public function it_is_not_equal(): void { $id = new IntegerId(99); $this->assertFalse($id->equals($other = new IntegerId(100))); @@ -79,7 +84,8 @@ public static function notIntegerIdProvider(): array } #[DataProvider('notIntegerIdProvider')] - public function testIsWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void { $id = new IntegerId(1); @@ -88,12 +94,14 @@ public function testIsWithOtherIdentifiers(?Identifier $other): void } #[DataProvider('notIntegerIdProvider')] - public function testTryFromWithInvalidValue(?Identifier $other): void + #[Test] + public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { $this->assertNull(IntegerId::tryFrom($other)); } - public function testIsWithNull(): void + #[Test] + public function it_is_not_equal_to_null(): void { $id = new IntegerId(1); @@ -101,7 +109,8 @@ public function testIsWithNull(): void } #[DataProvider('notIntegerIdProvider')] - public function testFromWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); diff --git a/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php b/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php index 4e96faa6..1b438c4d 100644 --- a/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php +++ b/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php @@ -16,6 +16,7 @@ use CloudCreativity\Modules\Toolkit\Identifiers\PossiblyNumericId; use CloudCreativity\Modules\Toolkit\Identifiers\StringId; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class PossiblyNumericIdTest extends TestCase @@ -36,7 +37,8 @@ public static function valueProvider(): array } #[DataProvider('valueProvider')] - public function test(int|string $value, int|string $expected): void + #[Test] + public function it_converts_numeric_strings_to_integers(int|string $value, int|string $expected): void { $actual = new PossiblyNumericId($value); $expectedId = is_string($expected) ? new StringId($expected) : new IntegerId($expected); diff --git a/tests/Unit/Toolkit/Identifiers/StringIdTest.php b/tests/Unit/Toolkit/Identifiers/StringIdTest.php index 8e4f453f..91724a10 100644 --- a/tests/Unit/Toolkit/Identifiers/StringIdTest.php +++ b/tests/Unit/Toolkit/Identifiers/StringIdTest.php @@ -19,11 +19,13 @@ use CloudCreativity\Modules\Toolkit\Identifiers\StringId; use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class StringIdTest extends TestCase { - public function test(): void + #[Test] + public function it_wraps_a_string(): void { $id = new StringId('99'); @@ -38,20 +40,23 @@ public function test(): void ); } - public function testItCanBeZero(): void + #[Test] + public function it_can_be_zero(): void { $id = new StringId('0'); $this->assertSame('0', $id->value); } - public function testItMustNotBeEmpty(): void + #[Test] + public function it_must_not_be_empty(): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Identifier value must be a non-empty string.'); new StringId(''); } - public function testItIsEquals(): void + #[Test] + public function it_is_equals(): void { $this->assertObjectEquals($id = new StringId('99'), $other = StringId::from('99')); $this->assertSame($id, StringId::from($id)); @@ -61,7 +66,8 @@ public function testItIsEquals(): void $this->assertSame($id, StringId::tryFrom($id)); } - public function testItIsNotEqual(): void + #[Test] + public function it_is_not_equal(): void { $id = new StringId('99'); $this->assertFalse($id->equals($other = new StringId('100'))); @@ -84,7 +90,8 @@ public static function notStringIdProvider(): array } #[DataProvider('notStringIdProvider')] - public function testIsWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void { $id = new StringId('1'); @@ -93,13 +100,15 @@ public function testIsWithOtherIdentifiers(?Identifier $other): void } #[DataProvider('notStringIdProvider')] - public function testTryFromWithInvalid(?Identifier $other): void + #[Test] + public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { $this->assertNull(StringId::tryFrom($other)); } #[DataProvider('notStringIdProvider')] - public function testFromWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); diff --git a/tests/Unit/Toolkit/Identifiers/UuidFactoryTest.php b/tests/Unit/Toolkit/Identifiers/UuidFactoryTest.php index 83e6dbb8..ecc4e640 100644 --- a/tests/Unit/Toolkit/Identifiers/UuidFactoryTest.php +++ b/tests/Unit/Toolkit/Identifiers/UuidFactoryTest.php @@ -19,6 +19,7 @@ use CloudCreativity\Modules\Toolkit\Identifiers\UuidV4; use CloudCreativity\Modules\Toolkit\Identifiers\UuidV7; use DateTimeImmutable; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Ramsey\Uuid\Type\Hexadecimal; @@ -42,7 +43,14 @@ protected function setUp(): void ); } - public function testFromWithBaseUuid(): void + protected function tearDown(): void + { + unset($this->factory, $this->baseFactory); + parent::tearDown(); + } + + #[Test] + public function it_wraps_a_base_uuid(): void { $this->baseFactory ->expects($this->never()) @@ -54,7 +62,8 @@ public function testFromWithBaseUuid(): void $this->assertSame($base, $uuid->value); } - public function testFromWithUuid(): void + #[Test] + public function it_returns_the_same_uuid_instance(): void { $this->baseFactory ->expects($this->never()) @@ -65,7 +74,8 @@ public function testFromWithUuid(): void $this->assertSame($expected, $actual); } - public function testFromWithIdentifierInterface(): void + #[Test] + public function it_rejects_a_non_uuid_identifier(): void { $this->baseFactory ->expects($this->never()) @@ -78,7 +88,8 @@ public function testFromWithIdentifierInterface(): void ); } - public function testFromBytes(): void + #[Test] + public function it_creates_from_bytes(): void { $this->baseFactory ->expects($this->once()) @@ -92,7 +103,8 @@ public function testFromBytes(): void $this->assertSame($uuid->value, $base); } - public function testFromDateTime(): void + #[Test] + public function it_creates_from_a_date_time(): void { $this->baseFactory ->expects($this->once()) @@ -110,7 +122,8 @@ public function testFromDateTime(): void $this->assertSame($uuid->value, $base); } - public function testFromInteger(): void + #[Test] + public function it_creates_from_an_integer(): void { $this->baseFactory ->expects($this->once()) @@ -124,7 +137,8 @@ public function testFromInteger(): void $this->assertSame($uuid->value, $base); } - public function testFromString(): void + #[Test] + public function it_creates_from_a_string(): void { $this->baseFactory ->expects($this->once()) @@ -138,7 +152,8 @@ public function testFromString(): void $this->assertSame($uuid->value, $base); } - public function testUuid1(): void + #[Test] + public function it_creates_a_uuid_v1(): void { $this->baseFactory ->expects($this->once()) @@ -155,7 +170,8 @@ public function testUuid1(): void $this->assertSame($uuid->value, $base); } - public function testUuid2(): void + #[Test] + public function it_creates_a_uuid_v2(): void { $this->baseFactory ->expects($this->once()) @@ -174,7 +190,8 @@ public function testUuid2(): void $this->assertSame($uuid->value, $base); } - public function testUuid3(): void + #[Test] + public function it_creates_a_uuid_v3(): void { $this->baseFactory ->expects($this->once()) @@ -191,7 +208,8 @@ public function testUuid3(): void $this->assertSame($uuid->value, $base); } - public function testUuid4(): void + #[Test] + public function it_creates_a_uuid_v4(): void { $this->baseFactory ->expects($this->once()) @@ -204,7 +222,8 @@ public function testUuid4(): void $this->assertSame($uuid->value, $base); } - public function testUuid5(): void + #[Test] + public function it_creates_a_uuid_v5(): void { $this->baseFactory ->expects($this->once()) @@ -221,7 +240,8 @@ public function testUuid5(): void $this->assertSame($uuid->value, $base); } - public function testUuid6(): void + #[Test] + public function it_creates_a_uuid_v6(): void { $this->baseFactory ->expects($this->once()) @@ -238,7 +258,8 @@ public function testUuid6(): void $this->assertSame($uuid->value, $base); } - public function testUuid7(): void + #[Test] + public function it_creates_a_uuid_v7(): void { $date = new \DateTimeImmutable(); @@ -254,7 +275,8 @@ public function testUuid7(): void $this->assertSame($uuid->value, $base); } - public function testUuid7NotSupported(): void + #[Test] + public function it_throws_if_uuid_v7_is_not_supported(): void { $factory = new UuidFactory( $this->createMock(BaseUuidFactoryInterface::class), @@ -266,7 +288,8 @@ public function testUuid7NotSupported(): void $factory->uuid7(); } - public function testUuid8(): void + #[Test] + public function it_creates_a_uuid_v8(): void { $bytes = 'blah!'; @@ -282,7 +305,8 @@ public function testUuid8(): void $this->assertSame($uuid->value, $base); } - public function testUuid8NotSupported(): void + #[Test] + public function it_throws_if_uuid_v8_is_not_supported(): void { $factory = new UuidFactory( $this->createMock(BaseUuidFactoryInterface::class), diff --git a/tests/Unit/Toolkit/Identifiers/UuidTest.php b/tests/Unit/Toolkit/Identifiers/UuidTest.php index 935bc396..6025e2a4 100644 --- a/tests/Unit/Toolkit/Identifiers/UuidTest.php +++ b/tests/Unit/Toolkit/Identifiers/UuidTest.php @@ -20,6 +20,7 @@ use CloudCreativity\Modules\Toolkit\Identifiers\StringId; use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Ramsey\Uuid\Uuid as RamseyUuid; @@ -27,11 +28,12 @@ final class UuidTest extends TestCase { protected function tearDown(): void { - parent::tearDown(); Uuid::setFactory(null); + parent::tearDown(); } - public function test(): void + #[Test] + public function it_wraps_a_ramsey_uuid(): void { $base = RamseyUuid::uuid4(); $id = new Uuid($base); @@ -48,7 +50,8 @@ public function test(): void ); } - public function testItIsEquals(): void + #[Test] + public function it_is_equals(): void { $base = RamseyUuid::uuid4(); $id = new Uuid($base); @@ -61,7 +64,8 @@ public function testItIsEquals(): void $this->assertSame($id, Uuid::tryFrom($id)); } - public function testItIsNotEqual(): void + #[Test] + public function it_is_not_equal(): void { $id = new Uuid(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')); $this->assertFalse($id->is($other = new Uuid( @@ -85,7 +89,8 @@ public static function notUuidProvider(): array } #[DataProvider('notUuidProvider')] - public function testIsWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void { $id = new Uuid(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')); @@ -95,7 +100,8 @@ public function testIsWithOtherIdentifiers(?Identifier $other): void } #[DataProvider('notUuidProvider')] - public function testFromWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); @@ -103,12 +109,14 @@ public function testFromWithOtherIdentifiers(?Identifier $other): void } #[DataProvider('notUuidProvider')] - public function testTryFromWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { $this->assertNull(Uuid::tryFrom($other)); } - public function testFromWithString(): void + #[Test] + public function it_can_be_created_from_a_string(): void { Uuid::setFactory($factory = $this->createMock(UuidFactory::class)); @@ -121,7 +129,8 @@ public function testFromWithString(): void $this->assertSame($expected, Uuid::from($str)); } - public function testTryFromWithString(): void + #[Test] + public function it_can_try_to_create_from_a_string(): void { Uuid::setFactory($factory = $this->createMock(UuidFactory::class)); @@ -135,7 +144,8 @@ public function testTryFromWithString(): void $this->assertNull(Uuid::tryFrom('invalid')); } - public function testFromAndTryFromWithBaseUuid(): void + #[Test] + public function it_can_be_created_from_a_base_uuid(): void { Uuid::setFactory($factory = $this->createMock(UuidFactory::class)); @@ -149,7 +159,8 @@ public function testFromAndTryFromWithBaseUuid(): void $this->assertSame($expected, Uuid::tryFrom($base)); } - public function testTryFromWithNull(): void + #[Test] + public function it_returns_null_when_trying_from_null(): void { Uuid::setFactory($factory = $this->createMock(UuidFactory::class)); @@ -160,7 +171,8 @@ public function testTryFromWithNull(): void $this->assertNull(Uuid::tryFrom(null)); } - public function testNil(): void + #[Test] + public function it_creates_a_nil_uuid(): void { $base = RamseyUuid::fromString(RamseyUuid::NIL); $actual = Uuid::nil(); @@ -168,7 +180,8 @@ public function testNil(): void $this->assertTrue($actual->toBase()->equals($base)); } - public function testCompareTo(): void + #[Test] + public function it_can_be_compared_for_sorting(): void { $uuid1 = Uuid::random(); $uuid2 = Uuid::random(); diff --git a/tests/Unit/Toolkit/Identifiers/UuidV4Test.php b/tests/Unit/Toolkit/Identifiers/UuidV4Test.php index bf6d60c5..bfbe66a5 100644 --- a/tests/Unit/Toolkit/Identifiers/UuidV4Test.php +++ b/tests/Unit/Toolkit/Identifiers/UuidV4Test.php @@ -21,12 +21,14 @@ use CloudCreativity\Modules\Toolkit\Identifiers\UuidV4; use CloudCreativity\Modules\Toolkit\Identifiers\UuidV7; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Ramsey\Uuid\Uuid as RamseyUuid; final class UuidV4Test extends TestCase { - public function test(): void + #[Test] + public function it_wraps_a_ramsey_uuid(): void { $base = RamseyUuid::uuid4(); $id = UuidV4::from($base); @@ -43,7 +45,8 @@ public function test(): void ); } - public function testItIsEquals(): void + #[Test] + public function it_is_equals(): void { $base = RamseyUuid::uuid4(); $id = UuidV4::from($base); @@ -57,7 +60,8 @@ public function testItIsEquals(): void $this->assertTrue($id->is(new Uuid($base))); } - public function testItIsNotEqual(): void + #[Test] + public function it_is_not_equal(): void { $id = UuidV4::from(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')); $this->assertFalse($id->is($other = UuidV4::from( @@ -83,7 +87,8 @@ public static function notUuidV4Provider(): array } #[DataProvider('notUuidV4Provider')] - public function testIsWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void { $id = UuidV4::from(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')); @@ -93,7 +98,8 @@ public function testIsWithOtherIdentifiers(?Identifier $other): void } #[DataProvider('notUuidV4Provider')] - public function testFromWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); @@ -101,19 +107,22 @@ public function testFromWithOtherIdentifiers(?Identifier $other): void } #[DataProvider('notUuidV4Provider')] - public function testTryFromWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { $this->assertNull(UuidV4::tryFrom($other)); } - public function testFromWithString(): void + #[Test] + public function it_can_be_created_from_a_string(): void { $base = RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816'); $this->assertTrue(UuidV4::from($base)->is(UuidV4::from($base->toString()))); } - public function testTryFromWithString(): void + #[Test] + public function it_can_try_to_create_from_a_string(): void { $base = RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816'); @@ -121,12 +130,14 @@ public function testTryFromWithString(): void $this->assertNull(UuidV4::tryFrom('invalid')); } - public function testTryFromWithNull(): void + #[Test] + public function it_returns_null_when_trying_from_null(): void { $this->assertNull(Uuid::tryFrom(null)); } - public function testCompareTo(): void + #[Test] + public function it_can_be_compared_for_sorting(): void { $uuid1 = UuidV4::make(); $uuid2 = UuidV4::make(); diff --git a/tests/Unit/Toolkit/Identifiers/UuidV7Test.php b/tests/Unit/Toolkit/Identifiers/UuidV7Test.php index d0d6a522..9522d283 100644 --- a/tests/Unit/Toolkit/Identifiers/UuidV7Test.php +++ b/tests/Unit/Toolkit/Identifiers/UuidV7Test.php @@ -21,12 +21,14 @@ use CloudCreativity\Modules\Toolkit\Identifiers\UuidV4; use CloudCreativity\Modules\Toolkit\Identifiers\UuidV7; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Ramsey\Uuid\Uuid as RamseyUuid; final class UuidV7Test extends TestCase { - public function test(): void + #[Test] + public function it_wraps_a_ramsey_uuid(): void { $base = RamseyUuid::uuid7(); $id = UuidV7::from($base); @@ -43,7 +45,8 @@ public function test(): void ); } - public function testItIsEquals(): void + #[Test] + public function it_is_equals(): void { $base = RamseyUuid::uuid7(); $id = UuidV7::from($base); @@ -57,7 +60,8 @@ public function testItIsEquals(): void $this->assertTrue($id->is(new Uuid($base))); } - public function testItIsNotEqual(): void + #[Test] + public function it_is_not_equal(): void { $id = UuidV7::from(RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df')); $this->assertFalse($id->is($other = UuidV7::from( @@ -83,7 +87,8 @@ public static function notUuidV7Provider(): array } #[DataProvider('notUuidV7Provider')] - public function testIsWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void { $id = UuidV7::from(RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df')); @@ -93,7 +98,8 @@ public function testIsWithOtherIdentifiers(?Identifier $other): void } #[DataProvider('notUuidV7Provider')] - public function testFromWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); @@ -101,19 +107,22 @@ public function testFromWithOtherIdentifiers(?Identifier $other): void } #[DataProvider('notUuidV7Provider')] - public function testTryFromWithOtherIdentifiers(?Identifier $other): void + #[Test] + public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { $this->assertNull(UuidV7::tryFrom($other)); } - public function testFromWithString(): void + #[Test] + public function it_can_be_created_from_a_string(): void { $base = RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df'); $this->assertTrue(UuidV7::from($base)->is(UuidV7::from($base->toString()))); } - public function testTryFromWithString(): void + #[Test] + public function it_can_try_to_create_from_a_string(): void { $base = RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df'); @@ -121,12 +130,14 @@ public function testTryFromWithString(): void $this->assertNull(UuidV7::tryFrom('invalid')); } - public function testTryFromWithNull(): void + #[Test] + public function it_returns_null_when_trying_from_null(): void { $this->assertNull(Uuid::tryFrom(null)); } - public function testCompareTo(): void + #[Test] + public function it_can_be_compared_for_sorting(): void { $uuid1 = UuidV7::make(); $uuid2 = UuidV7::make(); diff --git a/tests/Unit/Toolkit/Iterables/IsLazyListTest.php b/tests/Unit/Toolkit/Iterables/IsLazyListTest.php index 0d32e931..500702dd 100644 --- a/tests/Unit/Toolkit/Iterables/IsLazyListTest.php +++ b/tests/Unit/Toolkit/Iterables/IsLazyListTest.php @@ -14,11 +14,13 @@ use CloudCreativity\Modules\Contracts\Toolkit\Iterables\LazyList; use CloudCreativity\Modules\Toolkit\Iterables\IsLazyList; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class IsLazyListTest extends TestCase { - public function testItIteratesOverList(): void + #[Test] + public function it_iterates_over_list(): void { $expected = ['one', 'two', 'three']; @@ -40,7 +42,8 @@ public function __construct(string ...$values) $this->assertSame($expected, $list->all()); } - public function testItYieldsListFromKeyedSet(): void + #[Test] + public function it_yields_list_from_keyed_set(): void { $expected = ['one' => 'foo', 'two' => 'bar', 'three' => 'baz']; diff --git a/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php b/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php index 95fb30e8..18b759c6 100644 --- a/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php +++ b/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php @@ -14,11 +14,13 @@ use CloudCreativity\Modules\Contracts\Toolkit\Iterables\NonEmptyList; use CloudCreativity\Modules\Toolkit\Iterables\IsNonEmptyList; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class IsNonEmptyListTest extends TestCase { - public function test(): void + #[Test] + public function it_iterates_counts_and_returns_all_values(): void { $expected = ['one', 'two', 'three']; diff --git a/tests/Unit/Toolkit/ModuleBasenameTest.php b/tests/Unit/Toolkit/ModuleBasenameTest.php index 6ea0a70f..2049905b 100644 --- a/tests/Unit/Toolkit/ModuleBasenameTest.php +++ b/tests/Unit/Toolkit/ModuleBasenameTest.php @@ -15,6 +15,7 @@ use CloudCreativity\Modules\Toolkit\ModuleBasename; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Depends; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class ModuleBasenameTest extends TestCase @@ -124,7 +125,8 @@ public static function withoutModuleProvider(): array } #[DataProvider('moduleProvider')] - public function testFromModule(string $value, string $context, string $message): void + #[Test] + public function it_parses_a_class_name_with_a_module(string $value, string $context, string $message): void { $name = ModuleBasename::from($value); @@ -137,7 +139,8 @@ public function testFromModule(string $value, string $context, string $message): } #[DataProvider('withoutModuleProvider')] - public function testFromWithoutModule(string $value, string $message): void + #[Test] + public function it_parses_a_class_name_without_a_module(string $value, string $message): void { $name = ModuleBasename::from($value); @@ -149,7 +152,8 @@ public function testFromWithoutModule(string $value, string $message): void $this->assertSame($message, (string) $name); } - public function testToArray(): ModuleBasename + #[Test] + public function it_converts_to_an_array(): ModuleBasename { $value = ModuleBasename::from( 'CloudCreativity\Application\Modules\WaitList\BoundedContext\Application\Commands\ScheduleDelayedProcess\ScheduleDelayedProcessCommand', @@ -163,8 +167,9 @@ public function testToArray(): ModuleBasename return $value; } - #[Depends('testToArray')] - public function testJsonSerialize(ModuleBasename $value): void + #[Depends('it_converts_to_an_array')] + #[Test] + public function it_serializes_to_json(ModuleBasename $value): void { $expected = json_encode([ 'module' => $value->module, @@ -174,14 +179,16 @@ public function testJsonSerialize(ModuleBasename $value): void $this->assertJsonStringEqualsJsonString($expected, json_encode($value, JSON_THROW_ON_ERROR)); } - public function testTryFromWithInvalid(): void + #[Test] + public function it_returns_null_when_trying_from_an_invalid_value(): void { $name = ModuleBasename::tryFrom(ModuleBasename::class); $this->assertNull($name); } - public function testFromWithInvalid(): void + #[Test] + public function it_throws_when_parsing_an_invalid_value(): void { $this->expectException(\UnexpectedValueException::class); diff --git a/tests/Unit/Toolkit/Pipeline/AccumulationProcessorTest.php b/tests/Unit/Toolkit/Pipeline/AccumulationProcessorTest.php index c010e1b8..ad3486c9 100644 --- a/tests/Unit/Toolkit/Pipeline/AccumulationProcessorTest.php +++ b/tests/Unit/Toolkit/Pipeline/AccumulationProcessorTest.php @@ -13,11 +13,13 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Pipeline; use CloudCreativity\Modules\Toolkit\Pipeline\AccumulationProcessor; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class AccumulationProcessorTest extends TestCase { - public function test(): void + #[Test] + public function it_accumulates_stage_results(): void { $input = new \DateTime(); @@ -45,7 +47,8 @@ public function test(): void $this->assertSame(6, $result); } - public function testWithInitialValue(): void + #[Test] + public function it_accumulates_stage_results_with_an_initial_value(): void { $input = new \DateTime(); @@ -74,7 +77,8 @@ public function testWithInitialValue(): void $this->assertSame(16, $result); } - public function testNoStagesWithoutInitialValue(): void + #[Test] + public function it_returns_null_when_there_are_no_stages_or_initial_value(): void { $processor = new AccumulationProcessor(function () { $this->fail('Callback should not be executed on an empty stack.'); @@ -83,7 +87,8 @@ public function testNoStagesWithoutInitialValue(): void $this->assertNull($processor->process('foobar')); } - public function testNoStagesWithInitialValue(): void + #[Test] + public function it_returns_the_initial_value_when_there_are_no_stages(): void { $processor = new AccumulationProcessor(function () { $this->fail('Callback should not be executed on an empty stack.'); diff --git a/tests/Unit/Toolkit/Pipeline/InterruptibleProcessorTest.php b/tests/Unit/Toolkit/Pipeline/InterruptibleProcessorTest.php index 7d8763d6..0a58e299 100644 --- a/tests/Unit/Toolkit/Pipeline/InterruptibleProcessorTest.php +++ b/tests/Unit/Toolkit/Pipeline/InterruptibleProcessorTest.php @@ -13,11 +13,13 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Pipeline; use CloudCreativity\Modules\Toolkit\Pipeline\InterruptibleProcessor; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class InterruptibleProcessorTest extends TestCase { - public function test(): void + #[Test] + public function it_interrupts_processing_when_the_checker_returns_true(): void { $processor = new InterruptibleProcessor( static fn (float|int $value): bool => 0 === (intval($value) % 10), @@ -35,7 +37,8 @@ public function test(): void $this->assertSame(200 / 3, $result); } - public function testNoStages(): void + #[Test] + public function it_returns_the_payload_when_there_are_no_stages(): void { $processor = new InterruptibleProcessor(function () { $this->fail('Not expecting checker function to be called'); diff --git a/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php b/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php index 09df5a70..6fd210d2 100644 --- a/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php +++ b/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php @@ -15,6 +15,7 @@ use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\Pipeline; use CloudCreativity\Modules\Toolkit\Pipeline\LazyPipe; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -31,7 +32,14 @@ protected function setUp(): void $this->container = $this->createMock(PipeContainer::class); } - public function test(): void + protected function tearDown(): void + { + unset($this->container); + parent::tearDown(); + } + + #[Test] + public function it_resolves_the_pipe_from_the_container_and_invokes_it(): void { $this->container ->expects($this->once()) @@ -51,7 +59,8 @@ public function test(): void $this->assertSame($expected, $actual); } - public function testItRethrowsException(): void + #[Test] + public function it_rethrows_exception(): void { $this->container ->expects($this->once()) diff --git a/tests/Unit/Toolkit/Pipeline/MiddlewareProcessorTest.php b/tests/Unit/Toolkit/Pipeline/MiddlewareProcessorTest.php index 44fa9df0..3a7a3c14 100644 --- a/tests/Unit/Toolkit/Pipeline/MiddlewareProcessorTest.php +++ b/tests/Unit/Toolkit/Pipeline/MiddlewareProcessorTest.php @@ -14,11 +14,13 @@ use Closure; use CloudCreativity\Modules\Toolkit\Pipeline\MiddlewareProcessor; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class MiddlewareProcessorTest extends TestCase { - public function test(): void + #[Test] + public function it_processes_middleware_in_order(): void { $processor = new MiddlewareProcessor(); @@ -32,7 +34,8 @@ public function test(): void $this->assertSame(['A1', 'B1', 'C1', 'C2', 'B2', 'A2'], $result); } - public function testWithDestination(): void + #[Test] + public function it_processes_middleware_with_a_destination(): void { $processor = new MiddlewareProcessor( static fn (array $values): array => array_map( @@ -51,7 +54,8 @@ public function testWithDestination(): void $this->assertSame(['a1', 'b1', 'c1', 'C2', 'B2', 'A2'], $result); } - public function testNoStages(): void + #[Test] + public function it_returns_the_payload_when_there_are_no_stages(): void { $processor = new MiddlewareProcessor(); @@ -60,7 +64,8 @@ public function testNoStages(): void $this->assertSame('foo', $result); } - public function testNoStagesWithDestination(): void + #[Test] + public function it_passes_the_payload_to_the_destination_when_there_are_no_stages(): void { $processor = new MiddlewareProcessor( static fn (string $value): string => strtoupper($value), diff --git a/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php b/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php index 75832ac5..f1214e81 100644 --- a/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php +++ b/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php @@ -13,11 +13,13 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Pipeline; use CloudCreativity\Modules\Toolkit\Pipeline\PipeContainer; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class PipeContainerTest extends TestCase { - public function testItResolvesBoundPipes(): void + #[Test] + public function it_resolves_bound_pipes(): void { $a = fn () => 1; $b = fn () => 2; diff --git a/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php b/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php index 62d79077..410f2e9c 100644 --- a/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php +++ b/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php @@ -17,11 +17,13 @@ use CloudCreativity\Modules\Toolkit\Pipeline\LazyPipe; use CloudCreativity\Modules\Toolkit\Pipeline\Pipeline; use CloudCreativity\Modules\Toolkit\Pipeline\PipelineBuilder; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class PipelineBuilderTest extends TestCase { - public function test(): void + #[Test] + public function it_builds_a_pipeline(): void { $expected = new Pipeline( $processor = $this->createMock(Processor::class), @@ -36,7 +38,8 @@ public function test(): void $this->assertEquals($expected, $actual); } - public function testServiceString(): void + #[Test] + public function it_builds_a_pipeline_with_lazy_pipes_for_service_strings(): void { $container = $this->createMock(PipeContainer::class); $processor = $this->createMock(Processor::class); @@ -54,7 +57,8 @@ public function testServiceString(): void $this->assertEquals($expected, $actual); } - public function testServiceStringWithoutContainer(): void + #[Test] + public function it_fails_to_build_with_a_service_string_without_a_container(): void { $processor = $this->createStub(Processor::class); diff --git a/tests/Unit/Toolkit/Pipeline/PipelineTest.php b/tests/Unit/Toolkit/Pipeline/PipelineTest.php index f725dc9d..b43c182a 100644 --- a/tests/Unit/Toolkit/Pipeline/PipelineTest.php +++ b/tests/Unit/Toolkit/Pipeline/PipelineTest.php @@ -14,11 +14,13 @@ use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\Processor; use CloudCreativity\Modules\Toolkit\Pipeline\Pipeline; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class PipelineTest extends TestCase { - public function testProcess(): void + #[Test] + public function it_processes_the_payload(): void { $payload = 'Hello World'; $stages = ['strtoupper', 'strtolower']; @@ -38,7 +40,8 @@ public function testProcess(): void $this->assertSame($expected, $actual); } - public function testInvokable(): void + #[Test] + public function it_is_invokable(): void { $payload = 'Hello World'; $stages = ['strtoupper', 'strtolower']; @@ -58,7 +61,8 @@ public function testInvokable(): void $this->assertSame($expected, $actual); } - public function testDefaultProcessor(): void + #[Test] + public function it_uses_a_default_processor(): void { $pipeline = new Pipeline(null, [ static fn (int $value): int => $value * 5, @@ -71,7 +75,8 @@ public function testDefaultProcessor(): void $this->assertSame(14, $result); } - public function testPipe(): void + #[Test] + public function it_returns_a_new_pipeline_when_piping(): void { $pipeline1 = new Pipeline(null, [ static fn (int $value): int => $value * 5, diff --git a/tests/Unit/Toolkit/Pipeline/SimpleProcessorTest.php b/tests/Unit/Toolkit/Pipeline/SimpleProcessorTest.php index 207ef86e..1862a4d8 100644 --- a/tests/Unit/Toolkit/Pipeline/SimpleProcessorTest.php +++ b/tests/Unit/Toolkit/Pipeline/SimpleProcessorTest.php @@ -13,11 +13,13 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Pipeline; use CloudCreativity\Modules\Toolkit\Pipeline\SimpleProcessor; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class SimpleProcessorTest extends TestCase { - public function test(): void + #[Test] + public function it_processes_stages_in_order(): void { $processor = new SimpleProcessor(); @@ -30,7 +32,8 @@ public function test(): void $this->assertSame(63, $result); } - public function testNoStages(): void + #[Test] + public function it_returns_the_payload_when_there_are_no_stages(): void { $processor = new SimpleProcessor(); diff --git a/tests/Unit/Toolkit/Result/ErrorTest.php b/tests/Unit/Toolkit/Result/ErrorTest.php index 0502cc56..2c3e7bf4 100644 --- a/tests/Unit/Toolkit/Result/ErrorTest.php +++ b/tests/Unit/Toolkit/Result/ErrorTest.php @@ -17,11 +17,13 @@ use CloudCreativity\Modules\Tests\TestUnitEnum; use CloudCreativity\Modules\Toolkit\ContractException; use CloudCreativity\Modules\Toolkit\Result\Error; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class ErrorTest extends TestCase { - public function test(): void + #[Test] + public function it_has_a_key_message_and_code(): void { $error = new Error(key: 'foo', message: 'Bar', code: TestUnitEnum::Baz); @@ -33,7 +35,8 @@ public function test(): void $this->assertFalse($error->is(TestUnitEnum::Bat)); } - public function testOnlyMessage(): void + #[Test] + public function it_can_have_only_a_message(): void { $error = new Error(message: 'Hello World'); @@ -42,7 +45,8 @@ public function testOnlyMessage(): void $this->assertNull($error->code()); } - public function testOnlyCode(): void + #[Test] + public function it_can_have_only_a_code(): void { $error = new Error(code: TestBackedEnum::Foo); @@ -51,7 +55,8 @@ public function testOnlyCode(): void $this->assertSame(TestBackedEnum::Foo, $error->code()); } - public function testNoMessageOrCode(): void + #[Test] + public function it_requires_a_message_or_a_code(): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Error must have a message or a code.'); diff --git a/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php b/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php index 5094e275..349874c9 100644 --- a/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php +++ b/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php @@ -15,11 +15,13 @@ use CloudCreativity\Modules\Tests\TestUnitEnum; use CloudCreativity\Modules\Toolkit\Result\FailedResultException; use CloudCreativity\Modules\Toolkit\Result\Result; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class FailedResultExceptionTest extends TestCase { - public function testItFailsWithMessage(): void + #[Test] + public function it_fails_with_message(): void { $result = Result::failed('Something went wrong.') ->withMeta(['foo' => 'bar']); @@ -30,7 +32,8 @@ public function testItFailsWithMessage(): void $this->assertSame('Something went wrong.', $exception->getMessage()); } - public function testItFailsWithErrorCode(): void + #[Test] + public function it_fails_with_error_code(): void { $result = Result::failed(TestUnitEnum::Bat); @@ -42,7 +45,8 @@ public function testItFailsWithErrorCode(): void $this->assertSame($expected, $exception->getMessage()); } - public function testItHasCodeAndPreviousException(): void + #[Test] + public function it_has_code_and_previous_exception(): void { $result = Result::failed('Something went wrong.'); $previous = new \LogicException('Boom!'); diff --git a/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php b/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php index ed514e2e..ec21f2c7 100644 --- a/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php +++ b/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php @@ -16,11 +16,13 @@ use CloudCreativity\Modules\Toolkit\Result\Error; use CloudCreativity\Modules\Toolkit\Result\KeyedSetOfErrors; use CloudCreativity\Modules\Toolkit\Result\ListOfErrors; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class KeyedSetOfErrorsTest extends TestCase { - public function test(): void + #[Test] + public function it_groups_errors_by_key(): void { $errors = new KeyedSetOfErrors( $a = new Error(message: 'Message A', key: 'foo'), @@ -52,7 +54,8 @@ public function test(): void $this->assertEquals($expected[TestUnitEnum::Baz->name], $errors->get(TestUnitEnum::Baz)); } - public function testEmpty(): void + #[Test] + public function it_can_be_empty(): void { $errors = new KeyedSetOfErrors(); @@ -61,7 +64,8 @@ public function testEmpty(): void $this->assertCount(0, $errors); } - public function testPutNewKey(): void + #[Test] + public function it_puts_an_error_with_a_new_key(): void { $original = new KeyedSetOfErrors( $a = new Error(message: 'Message A', key: 'foo'), @@ -84,7 +88,8 @@ public function testPutNewKey(): void $this->assertSame(['bar', 'baz', 'foo'], $actual->keys()); } - public function testPutExistingKey(): void + #[Test] + public function it_puts_an_error_with_an_existing_key(): void { $original = new KeyedSetOfErrors( $a = new Error(message: 'Message A', key: 'foo'), @@ -106,7 +111,8 @@ public function testPutExistingKey(): void $this->assertSame(['bar', 'foo'], $actual->keys()); } - public function testPutErrorWithoutKey1(): void + #[Test] + public function it_puts_an_unkeyed_error_when_there_are_no_base_errors(): void { $original = new KeyedSetOfErrors( $a = new Error(message: 'Message A', key: 'foo'), @@ -129,7 +135,8 @@ public function testPutErrorWithoutKey1(): void $this->assertSame(['_base', 'bar', 'foo'], $actual->keys()); } - public function testPutErrorWithoutKey2(): void + #[Test] + public function it_puts_an_unkeyed_error_when_there_are_base_errors(): void { $original = new KeyedSetOfErrors( $a = new Error(message: 'Message A'), @@ -151,7 +158,8 @@ public function testPutErrorWithoutKey2(): void $this->assertSame(['_base', 'foo'], $actual->keys()); } - public function testMerge(): void + #[Test] + public function it_merges_another_set(): void { $set1 = new KeyedSetOfErrors( $a = new Error(message: 'Message A', key: 'foo'), diff --git a/tests/Unit/Toolkit/Result/ListOfErrorsTest.php b/tests/Unit/Toolkit/Result/ListOfErrorsTest.php index cd98e280..e0dc791e 100644 --- a/tests/Unit/Toolkit/Result/ListOfErrorsTest.php +++ b/tests/Unit/Toolkit/Result/ListOfErrorsTest.php @@ -19,11 +19,13 @@ use CloudCreativity\Modules\Toolkit\Result\Error; use CloudCreativity\Modules\Toolkit\Result\KeyedSetOfErrors; use CloudCreativity\Modules\Toolkit\Result\ListOfErrors; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class ListOfErrorsTest extends TestCase { - public function test(): void + #[Test] + public function it_holds_errors(): void { $errors = new ListOfErrors( $a = new Error(null, 'Message A'), @@ -39,7 +41,8 @@ public function test(): void $this->assertFalse($errors->isEmpty()); } - public function testEmpty(): void + #[Test] + public function it_can_be_empty(): void { $errors = new ListOfErrors(); @@ -50,7 +53,8 @@ public function testEmpty(): void $this->assertEmpty($errors->codes()); } - public function testPush(): void + #[Test] + public function it_pushes_an_error(): void { $original = new ListOfErrors( $a = new Error(null, 'Message A'), @@ -64,7 +68,8 @@ public function testPush(): void $this->assertSame([$a, $b, $c], $actual->all()); } - public function testMerge(): void + #[Test] + public function it_merges_another_list(): void { $stack1 = new ListOfErrors( $a = new Error(null, 'Message A'), @@ -85,7 +90,8 @@ public function testMerge(): void $this->assertSame([$a, $b, $c, $d], $actual->all()); } - public function testFirst(): void + #[Test] + public function it_returns_the_first_error(): void { $errors = new ListOfErrors( $a = new Error(null, 'Message A'), @@ -96,7 +102,8 @@ public function testFirst(): void $this->assertSame($a, $errors->first()); } - public function testFind(): void + #[Test] + public function it_finds_an_error(): void { $errors = new ListOfErrors( new Error(null, 'Message A'), @@ -112,7 +119,8 @@ public function testFind(): void $this->assertNull($errors->find(TestUnitEnum::Baz)); } - public function testAny(): void + #[Test] + public function it_checks_if_any_error_matches(): void { $errors = new ListOfErrors( new Error(message: 'Message A'), @@ -127,7 +135,8 @@ public function testAny(): void $this->assertFalse($errors->any(TestUnitEnum::Bat)); } - public function testEvery(): void + #[Test] + public function it_checks_if_every_error_matches(): void { $errors1 = new ListOfErrors( new Error(message: 'Message A'), @@ -151,7 +160,8 @@ public function testEvery(): void $this->assertFalse($errors2->every(TestUnitEnum::Bat)); } - public function testSoleWithExactlyOne(): void + #[Test] + public function it_returns_the_sole_error(): void { $errors1 = new ListOfErrors( $expected = new Error(message: 'Message A', code: $code = TestUnitEnum::Baz), @@ -173,7 +183,8 @@ public function testSoleWithExactlyOne(): void $this->assertSame($expected, $errors2->sole($fn)); } - public function testSoleWithNone(): void + #[Test] + public function it_throws_when_there_is_no_sole_error(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected exactly one error but there are 0.'); @@ -183,7 +194,8 @@ public function testSoleWithNone(): void $errors->sole(); } - public function testSoleWithMany(): void + #[Test] + public function it_throws_when_there_are_many_errors_for_sole(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected exactly one error but there are 3.'); @@ -197,7 +209,8 @@ public function testSoleWithMany(): void $errors->sole(); } - public function testSoleWithNoneMatching(): void + #[Test] + public function it_throws_when_no_error_matches_the_sole_callback(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected exactly one error matching the criteria but there are 0.'); @@ -211,7 +224,8 @@ public function testSoleWithNoneMatching(): void $errors->sole(fn (IError $error) => 'Message D' === $error->message()); } - public function testSoleWithManyMatching(): void + #[Test] + public function it_throws_when_many_errors_match_the_sole_callback(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected exactly one error matching the criteria but there are 2.'); @@ -225,7 +239,8 @@ public function testSoleWithManyMatching(): void $errors->sole(fn (IError $error) => 'Message A' === $error->message()); } - public function testSoleWithNoneMatchingEnum(): void + #[Test] + public function it_throws_when_no_error_matches_the_sole_code(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected exactly one error with code "Baz" but there are 0.'); @@ -239,7 +254,8 @@ public function testSoleWithNoneMatchingEnum(): void $errors->sole(TestUnitEnum::Baz); } - public function testSoleWithManyMatchingEnum(): void + #[Test] + public function it_throws_when_many_errors_match_the_sole_code(): void { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Expected exactly one error with code "Bat" but there are 2.'); @@ -253,7 +269,8 @@ public function testSoleWithManyMatchingEnum(): void $errors->sole(TestUnitEnum::Bat); } - public function testFilter(): void + #[Test] + public function it_filters_the_list(): void { $errors = new ListOfErrors( new Error(message: 'Message A'), @@ -272,7 +289,8 @@ public function testFilter(): void $this->assertEmpty($errors->filter(TestBackedEnum::Bar)); } - public function testCodes(): void + #[Test] + public function it_returns_unique_codes(): void { $errors1 = new ListOfErrors( new Error(message: 'Message A'), @@ -290,7 +308,8 @@ public function testCodes(): void $this->assertEmpty($errors2->codes()); } - public function testCode(): void + #[Test] + public function it_returns_the_first_code(): void { $errors1 = new ListOfErrors( new Error(message: 'Message A'), @@ -308,7 +327,8 @@ public function testCode(): void $this->assertNull($errors2->code()); } - public function testMessages(): void + #[Test] + public function it_returns_unique_messages(): void { $errors = new ListOfErrors( new Error(message: 'Message A'), @@ -321,7 +341,8 @@ public function testMessages(): void $this->assertSame(['Message A', 'Message B', 'Message C'], $errors->messages()); } - public function testMessage(): void + #[Test] + public function it_returns_the_first_message(): void { $errors1 = new ListOfErrors( new Error(message: 'Message A'), diff --git a/tests/Unit/Toolkit/Result/MetaTest.php b/tests/Unit/Toolkit/Result/MetaTest.php index 45605069..c5d7912a 100644 --- a/tests/Unit/Toolkit/Result/MetaTest.php +++ b/tests/Unit/Toolkit/Result/MetaTest.php @@ -13,11 +13,13 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Result; use CloudCreativity\Modules\Toolkit\Result\Meta; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; final class MetaTest extends TestCase { - public function test(): void + #[Test] + public function it_holds_values(): void { $meta = new Meta($values = [ 'foo' => 'bar', @@ -37,7 +39,8 @@ public function test(): void $this->assertFalse($meta->isEmpty()); } - public function testItIsIterable(): void + #[Test] + public function it_is_iterable(): void { $meta = new Meta($values = [ 'foo' => 'bar', @@ -48,7 +51,8 @@ public function testItIsIterable(): void $this->assertSame($values, iterator_to_array($meta)); } - public function testEmpty(): void + #[Test] + public function it_can_be_empty(): void { $meta = new Meta(); @@ -57,7 +61,8 @@ public function testEmpty(): void $this->assertFalse($meta->isNotEmpty()); } - public function testArrayAccess(): void + #[Test] + public function it_supports_array_access(): void { $meta = new Meta(['foo' => 'bar', 'baz' => 'bat', 'foobar' => null]); @@ -67,7 +72,8 @@ public function testArrayAccess(): void $this->assertFalse(isset($meta['blah'])); } - public function testOffsetUnset(): void + #[Test] + public function it_cannot_unset_values(): void { $meta = new Meta(['foo' => 'bar']); @@ -75,7 +81,8 @@ public function testOffsetUnset(): void unset($meta['foo']); } - public function testOffsetSet(): void + #[Test] + public function it_cannot_set_values_via_array_access(): void { $meta = new Meta(['foo' => 'bar']); @@ -83,7 +90,8 @@ public function testOffsetSet(): void $meta['foo'] = 'foobar'; } - public function testPut(): void + #[Test] + public function it_puts_a_value_immutably(): void { $original = new Meta(['foo' => 'bar', 'baz' => 'bat']); $actual = $original->put('foo', 'foobar'); @@ -93,7 +101,8 @@ public function testPut(): void $this->assertSame(['foo' => 'foobar', 'baz' => 'bat'], $actual->all()); } - public function testMergeArray(): void + #[Test] + public function it_merges_an_array(): void { $original = new Meta(['foo' => 'bar', 'baz' => 'bat']); $actual = $original->merge(['foo' => null, 'foobar' => 'bazbat']); @@ -103,7 +112,8 @@ public function testMergeArray(): void $this->assertSame(['foo' => null, 'baz' => 'bat', 'foobar' => 'bazbat'], $actual->all()); } - public function testMergeMeta(): void + #[Test] + public function it_merges_another_meta(): void { $original = new Meta(['foo' => 'bar', 'baz' => 'bat']); $actual = $original->merge(new Meta(['foo' => null, 'foobar' => 'bazbat'])); diff --git a/tests/Unit/Toolkit/Result/ResultTest.php b/tests/Unit/Toolkit/Result/ResultTest.php index e91f6fd8..3491829a 100644 --- a/tests/Unit/Toolkit/Result/ResultTest.php +++ b/tests/Unit/Toolkit/Result/ResultTest.php @@ -22,6 +22,7 @@ use CloudCreativity\Modules\Toolkit\Result\Meta; use CloudCreativity\Modules\Toolkit\Result\Result; use PHPUnit\Framework\Attributes\Depends; +use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use UnitEnum; @@ -29,7 +30,8 @@ final class ResultTest extends TestCase { - public function testOk(): void + #[Test] + public function it_creates_a_successful_result_without_a_value(): void { $result = Result::ok(); $result->abort(); @@ -47,7 +49,8 @@ public function testOk(): void $this->assertNull($result->code()); } - public function testOkWithValue(): void + #[Test] + public function it_creates_a_successful_result_with_a_value(): void { $result = Result::ok($value = 99); @@ -64,7 +67,8 @@ public function testOkWithValue(): void /** * @return Result */ - public function testFailed(): Result + #[Test] + public function it_creates_a_failed_result(): Result { $errors = new ListOfErrors(new Error(null, 'Something went wrong.')); $result = Result::failed($errors); @@ -88,8 +92,9 @@ public function testFailed(): Result /** * @param Result $result */ - #[Depends('testFailed')] - public function testAbort(Result $result): void + #[Depends('it_creates_a_failed_result')] + #[Test] + public function it_throws_when_aborting_a_failed_result(Result $result): void { try { $result->abort(); @@ -99,7 +104,8 @@ public function testAbort(Result $result): void } } - public function testErrorWithMultipleErrors(): void + #[Test] + public function it_returns_the_first_message_and_code_from_multiple_errors(): void { $errors = new ListOfErrors( new Error(code: TestBackedEnum::Foo), @@ -115,7 +121,8 @@ public function testErrorWithMultipleErrors(): void $this->assertSame(TestBackedEnum::Foo, $result->code()); } - public function testErrorWithMultipleCodedErrors(): void + #[Test] + public function it_resolves_the_message_when_errors_only_have_codes(): void { $errors = new ListOfErrors( new Error(code: TestBackedEnum::Foo), @@ -140,8 +147,9 @@ enum_string(TestBackedEnum::Foo), /** * @param Result $result */ - #[Depends('testFailed')] - public function testItThrowsWhenGettingValueOnFailedResult(Result $result): void + #[Depends('it_creates_a_failed_result')] + #[Test] + public function it_throws_when_getting_value_on_failed_result(Result $result): void { try { $result->value(); @@ -151,7 +159,8 @@ public function testItThrowsWhenGettingValueOnFailedResult(Result $result): void } } - public function testFailedWithListOfErrorsInterface(): void + #[Test] + public function it_fails_with_a_list_of_errors_implementation(): void { $errors = $this->createMock(IListOfErrors::class); $errors->method('isNotEmpty')->willReturn(true); @@ -163,7 +172,8 @@ public function testFailedWithListOfErrorsInterface(): void $this->assertEquals($result, Result::fail($errors)); } - public function testFailedWithError(): void + #[Test] + public function it_fails_with_an_error(): void { $error = new Error(null, 'Something went wrong.'); $result = Result::failed($error); @@ -172,7 +182,8 @@ public function testFailedWithError(): void $this->assertEquals($result, Result::fail($error)); } - public function testFailedWithString(): void + #[Test] + public function it_fails_with_a_string_error(): void { $error = new Error(null, 'Something went wrong.'); $result = Result::failed($error->message()); @@ -181,7 +192,8 @@ public function testFailedWithString(): void $this->assertEquals($result, Result::fail($error->message())); } - public function testFailedWithArray(): void + #[Test] + public function it_fails_with_an_array_of_errors(): void { $error = new Error(null, 'Something went wrong.'); $result = Result::failed([$error]); @@ -190,7 +202,8 @@ public function testFailedWithArray(): void $this->assertEquals($result, Result::fail([$error])); } - public function testFailedWithBackedEnum(): void + #[Test] + public function it_fails_with_an_enum_error_code(): void { $error = new Error(code: $code = TestBackedEnum::Foo); $result = Result::failed($code); @@ -199,19 +212,22 @@ public function testFailedWithBackedEnum(): void $this->assertEquals($result, Result::fail($code)); } - public function testFailedWithoutErrors(): void + #[Test] + public function it_requires_errors_when_calling_failed(): void { $this->expectException(\AssertionError::class); Result::failed(new ListOfErrors()); } - public function testFailWithoutErrors(): void + #[Test] + public function it_requires_errors_when_calling_fail(): void { $this->expectException(\AssertionError::class); Result::fail(new ListOfErrors()); } - public function testWithMeta(): void + #[Test] + public function it_sets_meta(): void { $meta = new Meta(['foo' => 'bar']); $result = Result::ok()->withMeta($meta); @@ -219,7 +235,8 @@ public function testWithMeta(): void $this->assertEquals($meta, $result->meta()); } - public function testWithMetaArray(): void + #[Test] + public function it_sets_meta_from_an_array(): void { $meta = new Meta(['foo' => 'bar']); $result = Result::ok()->withMeta($meta->all()); @@ -227,7 +244,8 @@ public function testWithMetaArray(): void $this->assertEquals($meta, $result->meta()); } - public function testWithMetaMergesValues(): void + #[Test] + public function it_merges_meta_values(): void { $result1 = Result::ok() ->withMeta($values = ['foo' => 'bar', 'baz' => 'bat', 'foobar' => null]); From 2b97d26dd2abd8a045927735f2807136080c6bfb Mon Sep 17 00:00:00 2001 From: Christopher Gammie Date: Sat, 14 Nov 2026 11:45:41 +0000 Subject: [PATCH 2/3] build(deps): upgrade to PHPUnit 13 and bump dev dependencies Migrate tests for PHPUnit 13: use stubs for test doubles without expectations, add expects() where with() was used without one, and fix data provider argument counts. Fail on PHPUnit warnings, deprecations and notices. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/unit-testing/SKILL.md | 4 +- composer.json | 10 +-- phpunit.xml | 5 +- .../Application/Bus/CommandDispatcherTest.php | 17 +++-- .../Middleware/ExecuteInUnitOfWorkTest.php | 6 +- .../Middleware/FlushDeferredEventsTest.php | 6 +- .../Bus/Middleware/LogMessageDispatchTest.php | 2 +- .../Middleware/SetupBeforeDispatchTest.php | 12 ++-- .../Middleware/TearDownAfterDispatchTest.php | 6 +- .../Application/Bus/QueryDispatcherTest.php | 19 ++--- .../DeferredDispatcherTest.php | 27 +++---- .../DomainEventDispatching/DispatcherTest.php | 18 +++-- .../UnitOfWorkAwareDispatcherTest.php | 70 ++++++++++++------- .../InboundEventDispatcherTest.php | 17 +++-- .../Middleware/SetupBeforeEventTest.php | 8 +-- .../Middleware/TearDownAfterEventTest.php | 4 +- .../UnitOfWork/UnitOfWorkManagerTest.php | 28 ++++++-- tests/Unit/Domain/EntityTest.php | 8 +-- .../Domain/EntityWithNullableGuidTest.php | 8 +-- tests/Unit/Domain/EntityWithTypedIdTest.php | 2 +- tests/Unit/Domain/IdentifierOrEntityTest.php | 4 +- .../ComponentPublisherTest.php | 4 ++ .../Infrastructure/Queue/ClosureQueueTest.php | 42 ++++++----- .../Queue/ComponentQueueTest.php | 22 +++--- .../Infrastructure/Queue/EnqueuerTest.php | 2 +- .../Testing/FakeDomainEventDispatcherTest.php | 10 +-- .../FakeOutboundEventPublisherTest.php | 10 +-- tests/Unit/Testing/FakeQueueTest.php | 10 +-- tests/Unit/Toolkit/Identifiers/GuidTest.php | 40 ++++++++--- .../Toolkit/Identifiers/UuidFactoryTest.php | 14 +++- .../Toolkit/Pipeline/PipelineBuilderTest.php | 6 +- tests/Unit/Toolkit/Result/ResultTest.php | 2 +- 32 files changed, 269 insertions(+), 174 deletions(-) diff --git a/.claude/skills/unit-testing/SKILL.md b/.claude/skills/unit-testing/SKILL.md index 27732b12..7e031ed9 100644 --- a/.claude/skills/unit-testing/SKILL.md +++ b/.claude/skills/unit-testing/SKILL.md @@ -69,7 +69,7 @@ without it is skipped with no error or warning, so **every `it_` method must hav ### Use PHPUnit Attributes Always use PHPUnit attributes (`#[Test]`, `#[DataProvider]`, etc.) and never docblock annotations such as `@test` or -`@dataProvider`. Docblock metadata is deprecated in PHPUnit 11 and removed in PHPUnit 12. +`@dataProvider`. PHPUnit 12+ no longer reads docblock metadata. Data providers must be `public static` and need a precise return type for PHPStan (level 10 also covers `tests/`): @@ -200,7 +200,7 @@ Isolate the unit under test by replacing its collaborators with test doubles. In 3. **Stubs** (`createStub()`) for interfaces that only need to exist or return values, e.g. a `Command`, `Query` or `IntegrationEvent` message passed through the code under test. 4. **Mocks** (`createMock()`) only when the test asserts how a collaborator is called. Always configure them with - `expects(...)`. A mock with no expectations should be a stub: PHPUnit 12 raises a notice for it, and this repo fails + `expects(...)`. A mock with no expectations should be a stub: PHPUnit raises a notice for it, and this repo fails on notices. Mock and stub the interfaces in `src/Contracts/`, not the concrete classes. Type mock properties with a native diff --git a/composer.json b/composer.json index bae9625f..367bf494 100644 --- a/composer.json +++ b/composer.json @@ -29,11 +29,11 @@ "symfony/polyfill-php85": "^1.33" }, "require-dev": { - "deptrac/deptrac": "^4.6", - "laravel/pint": "^1.29", - "monolog/monolog": "^3.10", - "phpstan/phpstan": "^2.2", - "phpunit/phpunit": "^11.5" + "deptrac/deptrac": "^4.7", + "laravel/pint": "^1.32", + "monolog/monolog": "^3.12", + "phpstan/phpstan": "^2.3", + "phpunit/phpunit": "^13.4" }, "autoload": { "files": [ diff --git a/phpunit.xml b/phpunit.xml index 08d5bc7a..26425227 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -7,12 +7,15 @@ processIsolation="false" stopOnError="false" stopOnFailure="false" - xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd" + xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/13.4/phpunit.xsd" cacheDirectory=".phpunit.cache" backupStaticProperties="false" failOnWarning="true" failOnDeprecation="true" failOnNotice="true" + failOnPhpunitWarning="true" + failOnPhpunitDeprecation="true" + failOnPhpunitNotice="true" > diff --git a/tests/Unit/Application/Bus/CommandDispatcherTest.php b/tests/Unit/Application/Bus/CommandDispatcherTest.php index 0478579a..f627e487 100644 --- a/tests/Unit/Application/Bus/CommandDispatcherTest.php +++ b/tests/Unit/Application/Bus/CommandDispatcherTest.php @@ -26,8 +26,6 @@ final class CommandDispatcherTest extends TestCase { private CommandHandlerContainer&MockObject $handlers; - private MockObject&PipeContainer $middleware; - private CommandDispatcher $dispatcher; /** @@ -41,20 +39,20 @@ protected function setUp(): void $this->dispatcher = new class ( handlers: $this->handlers = $this->createMock(CommandHandlerContainer::class), - middleware: $this->middleware = $this->createMock(PipeContainer::class), + middleware: $this->createStub(PipeContainer::class), ) extends CommandDispatcher {}; } protected function tearDown(): void { - unset($this->handlers, $this->middleware, $this->dispatcher, $this->sequence); + unset($this->handlers, $this->dispatcher, $this->sequence); parent::tearDown(); } #[Test] public function it_dispatches_a_command(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $this->handlers ->expects($this->once()) @@ -107,6 +105,7 @@ public function it_dispatches_a_command_through_middleware(): void }; $this->handlers + ->expects($this->once()) ->method('get') ->with($command1::class) ->willReturnCallback(function () use ($handler) { @@ -114,7 +113,13 @@ public function it_dispatches_a_command_through_middleware(): void return $handler; }); - $this->middleware + $middleware = $this->createMock(PipeContainer::class); + $this->dispatcher = new class ( + handlers: $this->handlers, + middleware: $middleware, + ) extends CommandDispatcher {}; + + $middleware ->expects($this->exactly(2)) ->method('get') ->willReturnCallback(fn (string $name) => match ($name) { diff --git a/tests/Unit/Application/Bus/Middleware/ExecuteInUnitOfWorkTest.php b/tests/Unit/Application/Bus/Middleware/ExecuteInUnitOfWorkTest.php index dbfd66c2..9862aa27 100644 --- a/tests/Unit/Application/Bus/Middleware/ExecuteInUnitOfWorkTest.php +++ b/tests/Unit/Application/Bus/Middleware/ExecuteInUnitOfWorkTest.php @@ -30,7 +30,7 @@ final class ExecuteInUnitOfWorkTest extends TestCase #[Test] public function it_commits_unit_of_work_on_success(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $expected = Result::ok(); $middleware = new ExecuteInUnitOfWork( @@ -62,7 +62,7 @@ public function it_commits_unit_of_work_on_success(): void #[Test] public function it_does_not_commit_unit_of_work_on_failure(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $expected = Result::failed('Something went wrong.'); $middleware = new ExecuteInUnitOfWork( @@ -94,7 +94,7 @@ public function it_does_not_commit_unit_of_work_on_failure(): void #[Test] public function it_does_not_catch_exceptions(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $expected = new \RuntimeException('Boom! Something went wrong.'); $middleware = new ExecuteInUnitOfWork( diff --git a/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php b/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php index f616d1b4..e4985473 100644 --- a/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php +++ b/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php @@ -49,7 +49,7 @@ protected function tearDown(): void #[Test] public function it_flushes_deferred_events(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $expected = Result::ok(); $this->dispatcher @@ -76,7 +76,7 @@ public function it_flushes_deferred_events(): void #[Test] public function it_forgets_deferred_events_on_failed_result(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $expected = Result::failed('Something went wrong.'); $this->dispatcher @@ -103,7 +103,7 @@ public function it_forgets_deferred_events_on_failed_result(): void #[Test] public function it_forgets_deferred_events_on_exception(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $expected = new \LogicException('Boom!'); $this->dispatcher diff --git a/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php b/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php index 6a589bdc..4261fea9 100644 --- a/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php +++ b/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php @@ -99,7 +99,7 @@ public function it_logs_with_custom_levels(): void public function it_logs_after_the_next_closure_is_invoked(): void { $expected = new LogicException(); - $message = $this->createMock(Query::class); + $message = $this->createStub(Query::class); $name = $message::class; $middleware = new LogMessageDispatch($this->logger); diff --git a/tests/Unit/Application/Bus/Middleware/SetupBeforeDispatchTest.php b/tests/Unit/Application/Bus/Middleware/SetupBeforeDispatchTest.php index 32159d7f..562db740 100644 --- a/tests/Unit/Application/Bus/Middleware/SetupBeforeDispatchTest.php +++ b/tests/Unit/Application/Bus/Middleware/SetupBeforeDispatchTest.php @@ -31,7 +31,7 @@ final class SetupBeforeDispatchTest extends TestCase #[Test] public function it_sets_up_and_succeeds_without_teardown(): void { - $message = $this->createMock(Command::class); + $message = $this->createStub(Command::class); $result = Result::ok(); $middleware = new SetupBeforeDispatch(function () { @@ -52,7 +52,7 @@ public function it_sets_up_and_succeeds_without_teardown(): void #[Test] public function it_sets_up_and_succeeds_with_teardown(): void { - $message = $this->createMock(Query::class); + $message = $this->createStub(Query::class); $result = Result::ok(); $middleware = new SetupBeforeDispatch(function (): Closure { @@ -75,7 +75,7 @@ public function it_sets_up_and_succeeds_with_teardown(): void #[Test] public function it_sets_up_and_fails_without_teardown(): void { - $message = $this->createMock(Command::class); + $message = $this->createStub(Command::class); $result = Result::failed('Something went wrong.'); $middleware = new SetupBeforeDispatch(function () { @@ -96,7 +96,7 @@ public function it_sets_up_and_fails_without_teardown(): void #[Test] public function it_sets_up_and_fails_with_teardown(): void { - $message = $this->createMock(Command::class); + $message = $this->createStub(Command::class); $result = Result::failed('Something went wrong.'); $middleware = new SetupBeforeDispatch(function (): Closure { @@ -119,7 +119,7 @@ public function it_sets_up_and_fails_with_teardown(): void #[Test] public function it_sets_up_and_throws_exception_without_teardown(): void { - $message = $this->createMock(Command::class); + $message = $this->createStub(Command::class); $exception = new RuntimeException('Something went wrong.'); $actual = null; @@ -146,7 +146,7 @@ public function it_sets_up_and_throws_exception_without_teardown(): void #[Test] public function it_sets_up_and_throws_exception_with_teardown(): void { - $message = $this->createMock(Query::class); + $message = $this->createStub(Query::class); $exception = new RuntimeException('Something went wrong.'); $actual = null; diff --git a/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php b/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php index fd45f2f7..33f2f687 100644 --- a/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php +++ b/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php @@ -25,7 +25,7 @@ final class TearDownAfterDispatchTest extends TestCase #[Test] public function it_invokes_callback_after_success(): void { - $message = $this->createMock(Command::class); + $message = $this->createStub(Command::class); $result = Result::ok(); $sequence = []; @@ -46,7 +46,7 @@ public function it_invokes_callback_after_success(): void #[Test] public function it_invokes_callback_after_failure(): void { - $message = $this->createMock(Query::class); + $message = $this->createStub(Query::class); $result = Result::failed('Something went wrong.'); $sequence = []; @@ -67,7 +67,7 @@ public function it_invokes_callback_after_failure(): void #[Test] public function it_invokes_callback_after_exception(): void { - $message = $this->createMock(Command::class); + $message = $this->createStub(Command::class); $exception = new RuntimeException('Something went wrong.'); $actual = null; $sequence = []; diff --git a/tests/Unit/Application/Bus/QueryDispatcherTest.php b/tests/Unit/Application/Bus/QueryDispatcherTest.php index e7d822e4..7cd81b41 100644 --- a/tests/Unit/Application/Bus/QueryDispatcherTest.php +++ b/tests/Unit/Application/Bus/QueryDispatcherTest.php @@ -29,11 +29,6 @@ final class QueryDispatcherTest extends TestCase */ private QueryHandlerContainer $handlers; - /** - * @var MockObject&PipeContainer - */ - private PipeContainer $middleware; - private QueryDispatcher $dispatcher; /** @@ -47,20 +42,20 @@ protected function setUp(): void $this->dispatcher = new class ( handlers: $this->handlers = $this->createMock(QueryHandlerContainer::class), - middleware: $this->middleware = $this->createMock(PipeContainer::class), + middleware: $this->createStub(PipeContainer::class), ) extends QueryDispatcher {}; } protected function tearDown(): void { - unset($this->handlers, $this->middleware, $this->dispatcher, $this->sequence); + unset($this->handlers, $this->dispatcher, $this->sequence); parent::tearDown(); } #[Test] public function it_dispatches_a_query(): void { - $query = $this->createMock(Query::class); + $query = $this->createStub(Query::class); $this->handlers ->expects($this->once()) @@ -121,7 +116,13 @@ public function it_dispatches_a_query_through_middleware(): void return $handler; }); - $this->middleware + $middleware = $this->createMock(PipeContainer::class); + $this->dispatcher = new class ( + handlers: $this->handlers, + middleware: $middleware, + ) extends QueryDispatcher {}; + + $middleware ->expects($this->exactly(2)) ->method('get') ->willReturnCallback(fn (string $name) => match ($name) { diff --git a/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php b/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php index 02f70698..9d597417 100644 --- a/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php +++ b/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php @@ -26,11 +26,6 @@ final class DeferredDispatcherTest extends TestCase { private ListenerContainer&MockObject $listeners; - /** - * @var MockObject&MockObject&PipeContainer - */ - private MockObject&PipeContainer $middleware; - private DeferredDispatcher $dispatcher; protected function setUp(): void @@ -39,13 +34,13 @@ protected function setUp(): void $this->dispatcher = new class ( listeners: $this->listeners = $this->createMock(ListenerContainer::class), - middleware: $this->middleware = $this->createMock(PipeContainer::class), + middleware: $this->createStub(PipeContainer::class), ) extends DeferredDispatcher {}; } protected function tearDown(): void { - unset($this->dispatcher, $this->listeners, $this->middleware); + unset($this->dispatcher, $this->listeners); parent::tearDown(); } @@ -118,7 +113,7 @@ public function it_flushes_deferred_events(): void { $sequence = []; $event1 = new class () extends TestDomainEvent {}; - $event2 = $this->createMock(DomainEvent::class); + $event2 = $this->createStub(DomainEvent::class); $listener1 = $this->createMock(TestListener::class); $listener2 = $this->createMock(TestListener::class); @@ -190,7 +185,7 @@ public function it_flushes_deferred_events_including_events_dispatched_by_listen { $sequence = []; $event1 = new class () extends TestDomainEvent {}; - $event2 = $this->createMock(DomainEvent::class); + $event2 = $this->createStub(DomainEvent::class); $listener1 = $this->createMock(TestListener::class); $listener2 = $this->createMock(TestListener::class); @@ -255,6 +250,7 @@ public function it_forgets_deferred_events(): void $listener4 = $this->createMock(TestListener::class); $this->listeners + ->expects($this->exactly(2)) ->method('get') ->willReturnCallback(fn (string $name) => match ($name) { 'Listener1' => $listener1, @@ -309,7 +305,7 @@ public function it_forgets_deferred_events_after_exception(): void { $sequence = []; $event1 = new class () extends TestDomainEvent {}; - $event2 = $this->createMock(DomainEvent::class); + $event2 = $this->createStub(DomainEvent::class); $expected = new \LogicException('Boom!'); $listener1 = $this->createMock(TestListener::class); @@ -318,6 +314,7 @@ public function it_forgets_deferred_events_after_exception(): void $listener4 = $this->createMock(TestListener::class); $this->listeners + ->expects($this->exactly(2)) ->method('get') ->willReturnCallback(fn (string $name) => match ($name) { 'Listener1' => $listener1, @@ -370,7 +367,7 @@ public function it_forgets_deferred_events_after_exception(): void #[Test] public function it_does_nothing_when_there_are_no_listeners(): void { - $event = $this->createMock(DomainEvent::class); + $event = $this->createStub(DomainEvent::class); $this->listeners->expects($this->never())->method($this->anything()); $this->dispatcher->dispatch($event); } @@ -394,7 +391,13 @@ public function it_dispatches_through_middleware(): void return $next($event3); }; - $this->middleware + $middleware = $this->createMock(PipeContainer::class); + $this->dispatcher = new class ( + listeners: $this->listeners, + middleware: $middleware, + ) extends DeferredDispatcher {}; + + $middleware ->expects($this->once()) ->method('get') ->with('Middleware2') diff --git a/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php b/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php index cf505189..0a895134 100644 --- a/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php +++ b/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php @@ -26,8 +26,6 @@ final class DispatcherTest extends TestCase { private ListenerContainer&MockObject $listeners; - private MockObject&PipeContainer $middleware; - private Dispatcher $dispatcher; protected function setUp(): void @@ -36,13 +34,13 @@ protected function setUp(): void $this->dispatcher = new class ( listeners: $this->listeners = $this->createMock(ListenerContainer::class), - middleware: $this->middleware = $this->createMock(PipeContainer::class), + middleware: $this->createStub(PipeContainer::class), ) extends Dispatcher {}; } protected function tearDown(): void { - unset($this->dispatcher, $this->listeners, $this->middleware); + unset($this->dispatcher, $this->listeners); parent::tearDown(); } @@ -101,7 +99,7 @@ public function it_dispatches_immediately(): void $this->dispatcher->listen($event1::class, ['Listener1', $listener2Closure]); $this->dispatcher->listen($event2::class, ['Listener3']); - $this->dispatcher->listen($this->createMock(TestDomainEvent::class)::class, 'Listener4'); + $this->dispatcher->listen($this->createStub(TestDomainEvent::class)::class, 'Listener4'); $this->dispatcher->dispatch($event1); $this->dispatcher->dispatch($event2); @@ -113,7 +111,7 @@ public function it_dispatches_immediately(): void #[Test] public function it_does_nothing_when_there_are_no_listeners(): void { - $event = $this->createMock(DomainEvent::class); + $event = $this->createStub(DomainEvent::class); $this->listeners->expects($this->never())->method($this->anything()); $this->dispatcher->dispatch($event); } @@ -139,7 +137,13 @@ public function it_dispatches_through_middleware(): void return $next($event3); }; - $this->middleware + $middleware = $this->createMock(PipeContainer::class); + $this->dispatcher = new class ( + listeners: $this->listeners, + middleware: $middleware, + ) extends Dispatcher {}; + + $middleware ->expects($this->once()) ->method('get') ->with('Middleware2') diff --git a/tests/Unit/Application/DomainEventDispatching/UnitOfWorkAwareDispatcherTest.php b/tests/Unit/Application/DomainEventDispatching/UnitOfWorkAwareDispatcherTest.php index d14f55dd..f0bc3340 100644 --- a/tests/Unit/Application/DomainEventDispatching/UnitOfWorkAwareDispatcherTest.php +++ b/tests/Unit/Application/DomainEventDispatching/UnitOfWorkAwareDispatcherTest.php @@ -30,35 +30,28 @@ final class UnitOfWorkAwareDispatcherTest extends TestCase { private ListenerContainer&MockObject $listeners; - /** - * @var MockObject&UnitOfWorkManager - */ - private UnitOfWorkManager $unitOfWorkManager; - - private MockObject&PipeContainer $middleware; - private UnitOfWorkAwareDispatcher $dispatcher; protected function setUp(): void { parent::setUp(); - $this->dispatcher = new class ( - unitOfWorkManager: $this->unitOfWorkManager = $this->createMock(UnitOfWorkManager::class), - listeners: $this->listeners = $this->createMock(ListenerContainer::class), - middleware: $this->middleware = $this->createMock(PipeContainer::class), - ) extends UnitOfWorkAwareDispatcher {}; + $this->listeners = $this->createMock(ListenerContainer::class); + $this->dispatcher = $this->createDispatcher($this->createStub(UnitOfWorkManager::class)); } protected function tearDown(): void { - unset($this->dispatcher, $this->unitOfWorkManager, $this->listeners, $this->middleware); + unset($this->dispatcher, $this->listeners); parent::tearDown(); } #[Test] public function it_dispatches_immediately(): void { + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); + $this->dispatcher = $this->createDispatcher($unitOfWorkManager); + $sequence = []; $event = new TestImmediateDomainEvent(); @@ -125,11 +118,11 @@ public function it_dispatches_immediately(): void ->expects($this->never()) ->method('handle'); - $this->unitOfWorkManager + $unitOfWorkManager ->expects($this->once()) ->method('beforeCommit'); - $this->unitOfWorkManager + $unitOfWorkManager ->expects($this->exactly(2)) ->method('afterCommit'); @@ -152,7 +145,10 @@ public function it_dispatches_immediately(): void #[Test] public function it_does_not_dispatch_immediately(): void { - $event = $this->createMock(DomainEvent::class); + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); + $this->dispatcher = $this->createDispatcher($unitOfWorkManager); + + $event = $this->createStub(DomainEvent::class); $listener1 = $this->createMock(TestListener::class); $listener2 = $this->createMock(TestListener::class); @@ -169,11 +165,11 @@ public function it_does_not_dispatch_immediately(): void ->expects($this->never()) ->method('handle'); - $this->unitOfWorkManager + $unitOfWorkManager ->expects($this->once()) ->method('beforeCommit'); // we'll prove this works in the subsequent test - $this->unitOfWorkManager + $unitOfWorkManager ->expects($this->never()) ->method('afterCommit'); @@ -189,6 +185,9 @@ public function it_does_not_dispatch_immediately(): void #[Test] public function it_dispatches_event_in_before_commit_callback(): void { + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); + $this->dispatcher = $this->createDispatcher($unitOfWorkManager); + $event = new class () extends TestDomainEvent {}; $listener1 = $this->createMock(TestListener::class); @@ -213,7 +212,7 @@ public function it_dispatches_event_in_before_commit_callback(): void ->method('handle') ->with($this->identicalTo($event)); - $this->unitOfWorkManager + $unitOfWorkManager ->expects($this->once()) ->method('beforeCommit') ->with($this->callback(function (Closure $callback): bool { @@ -232,6 +231,9 @@ public function it_dispatches_event_in_before_commit_callback(): void #[Test] public function it_dispatches_to_a_before_commit_listener_before_commit(): void { + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); + $this->dispatcher = $this->createDispatcher($unitOfWorkManager); + $event = new TestImmediateDomainEvent(); $listener = $this->createMock(TestListenerBeforeCommit::class); @@ -240,14 +242,14 @@ public function it_dispatches_to_a_before_commit_listener_before_commit(): void ->method('handle') ->with($this->identicalTo($event)); - $this->unitOfWorkManager + $unitOfWorkManager ->expects($this->once()) ->method('beforeCommit') ->willReturnCallback(function (Closure $callback) { $callback(); }); - $this->unitOfWorkManager + $unitOfWorkManager ->expects($this->never()) ->method('afterCommit'); @@ -264,6 +266,9 @@ public function it_dispatches_to_a_before_commit_listener_before_commit(): void #[Test] public function it_dispatches_to_an_after_commit_listener_after_commit(): void { + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); + $this->dispatcher = $this->createDispatcher($unitOfWorkManager); + $event = new TestImmediateDomainEvent(); $listener = $this->createMock(TestListenerAfterCommit::class); @@ -272,14 +277,14 @@ public function it_dispatches_to_an_after_commit_listener_after_commit(): void ->method('handle') ->with($this->identicalTo($event)); - $this->unitOfWorkManager + $unitOfWorkManager ->expects($this->once()) ->method('afterCommit') ->willReturnCallback(function (Closure $callback) { $callback(); }); - $this->unitOfWorkManager + $unitOfWorkManager ->expects($this->never()) ->method('beforeCommit'); @@ -296,7 +301,7 @@ public function it_dispatches_to_an_after_commit_listener_after_commit(): void #[Test] public function it_does_nothing_when_there_are_no_listeners(): void { - $event = $this->createMock(DomainEvent::class); + $event = $this->createStub(DomainEvent::class); $this->listeners->expects($this->never())->method($this->anything()); $this->dispatcher->dispatch($event); } @@ -320,7 +325,10 @@ public function it_dispatches_through_middleware(): void return $next($event3); }; - $this->middleware + $middleware = $this->createMock(PipeContainer::class); + $this->dispatcher = $this->createDispatcher($this->createStub(UnitOfWorkManager::class), $middleware); + + $middleware ->expects($this->once()) ->method('get') ->with('Middleware2') @@ -373,6 +381,7 @@ public function handle(): void }; $this->listeners + ->expects($this->once()) ->method('get') ->with('InvalidListener') ->willReturn($listener); @@ -385,4 +394,15 @@ public function handle(): void $this->dispatcher->dispatch($event); } + + private function createDispatcher( + UnitOfWorkManager $unitOfWorkManager, + ?PipeContainer $middleware = null, + ): UnitOfWorkAwareDispatcher { + return new class ( + unitOfWorkManager: $unitOfWorkManager, + listeners: $this->listeners, + middleware: $middleware ?? $this->createStub(PipeContainer::class), + ) extends UnitOfWorkAwareDispatcher {}; + } } diff --git a/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php b/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php index a3755e86..60951cfc 100644 --- a/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php +++ b/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php @@ -25,8 +25,6 @@ final class InboundEventDispatcherTest extends TestCase { private EventHandlerContainer&MockObject $handlers; - private MockObject&PipeContainer $middleware; - private InboundEventDispatcher $dispatcher; /** @@ -40,20 +38,20 @@ protected function setUp(): void $this->dispatcher = new class ( handlers: $this->handlers = $this->createMock(EventHandlerContainer::class), - middleware: $this->middleware = $this->createMock(PipeContainer::class), + middleware: $this->createStub(PipeContainer::class), ) extends InboundEventDispatcher {}; } protected function tearDown(): void { - unset($this->handlers, $this->middleware, $this->dispatcher, $this->sequence); + unset($this->handlers, $this->dispatcher, $this->sequence); parent::tearDown(); } #[Test] public function it_dispatches_an_event(): void { - $event = $this->createMock(IntegrationEvent::class); + $event = $this->createStub(IntegrationEvent::class); $this->handlers ->expects($this->once()) @@ -100,6 +98,7 @@ public function it_dispatches_an_event_through_middleware(): void }; $this->handlers + ->expects($this->once()) ->method('get') ->with($event1::class) ->willReturnCallback(function () use ($handler) { @@ -107,7 +106,13 @@ public function it_dispatches_an_event_through_middleware(): void return $handler; }); - $this->middleware + $middleware = $this->createMock(PipeContainer::class); + $this->dispatcher = new class ( + handlers: $this->handlers, + middleware: $middleware, + ) extends InboundEventDispatcher {}; + + $middleware ->expects($this->exactly(2)) ->method('get') ->willReturnCallback(fn (string $name) => match ($name) { diff --git a/tests/Unit/Application/InboundEventBus/Middleware/SetupBeforeEventTest.php b/tests/Unit/Application/InboundEventBus/Middleware/SetupBeforeEventTest.php index c8658959..28ee2270 100644 --- a/tests/Unit/Application/InboundEventBus/Middleware/SetupBeforeEventTest.php +++ b/tests/Unit/Application/InboundEventBus/Middleware/SetupBeforeEventTest.php @@ -30,7 +30,7 @@ final class SetupBeforeEventTest extends TestCase #[Test] public function it_sets_up_and_succeeds_without_teardown(): void { - $event = $this->createMock(IntegrationEvent::class); + $event = $this->createStub(IntegrationEvent::class); $middleware = new SetupBeforeEvent(function () { $this->sequence[] = 'setup'; @@ -48,7 +48,7 @@ public function it_sets_up_and_succeeds_without_teardown(): void #[Test] public function it_sets_up_and_succeeds_with_teardown(): void { - $event = $this->createMock(IntegrationEvent::class); + $event = $this->createStub(IntegrationEvent::class); $middleware = new SetupBeforeEvent(function (): Closure { $this->sequence[] = 'setup'; @@ -68,7 +68,7 @@ public function it_sets_up_and_succeeds_with_teardown(): void #[Test] public function it_sets_up_and_throws_exception_without_teardown(): void { - $event = $this->createMock(IntegrationEvent::class); + $event = $this->createStub(IntegrationEvent::class); $exception = new RuntimeException('Something went wrong.'); $actual = null; @@ -95,7 +95,7 @@ public function it_sets_up_and_throws_exception_without_teardown(): void #[Test] public function it_sets_up_and_throws_exception_with_teardown(): void { - $event = $this->createMock(IntegrationEvent::class); + $event = $this->createStub(IntegrationEvent::class); $exception = new RuntimeException('Something went wrong.'); $actual = null; diff --git a/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php b/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php index edde736f..641ab707 100644 --- a/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php +++ b/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php @@ -23,7 +23,7 @@ final class TearDownAfterEventTest extends TestCase #[Test] public function it_invokes_callback_after_success(): void { - $event = $this->createMock(IntegrationEvent::class); + $event = $this->createStub(IntegrationEvent::class); $sequence = []; $middleware = new TearDownAfterEvent(function () use (&$sequence): void { @@ -41,7 +41,7 @@ public function it_invokes_callback_after_success(): void #[Test] public function it_invokes_callback_after_exception(): void { - $event = $this->createMock(IntegrationEvent::class); + $event = $this->createStub(IntegrationEvent::class); $exception = new RuntimeException('Something went wrong.'); $actual = null; $sequence = []; diff --git a/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php b/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php index 3880c821..a5bd0c95 100644 --- a/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php +++ b/tests/Unit/Application/UnitOfWork/UnitOfWorkManagerTest.php @@ -26,8 +26,6 @@ final class UnitOfWorkManagerTest extends TestCase { private MockObject&UnitOfWork $unitOfWork; - private ExceptionReporter&MockObject $reporter; - private UnitOfWorkManager $manager; protected function setUp(): void @@ -36,13 +34,13 @@ protected function setUp(): void $this->manager = new UnitOfWorkManager( $this->unitOfWork = $this->createMock(UnitOfWork::class), - $this->reporter = $this->createMock(ExceptionReporter::class), + $this->createStub(ExceptionReporter::class), ); } protected function tearDown(): void { - unset($this->manager, $this->unitOfWork, $this->reporter); + unset($this->manager, $this->unitOfWork); parent::tearDown(); } @@ -225,6 +223,7 @@ function () use (&$sequence): void { public function it_flushes_callbacks_on_successful_transaction(): void { $this->unitOfWork + ->expects($this->exactly(2)) ->method('execute') ->willReturnCallback(fn (Closure $callback) => $callback()); @@ -244,10 +243,13 @@ public function it_flushes_callbacks_on_successful_transaction(): void #[Test] public function it_flushes_callbacks_on_unsuccessful_transaction(): void { + $reporter = $this->createMock(ExceptionReporter::class); + $this->manager = new UnitOfWorkManager($this->unitOfWork, $reporter); + $ex = new LogicException('Boom'); $count = 0; - $this->reporter + $reporter ->expects($this->exactly(2)) // only "swallowed" exceptions are reported ->method('report') ->with($this->identicalTo($ex)); @@ -294,11 +296,14 @@ public function it_flushes_callbacks_on_unsuccessful_transaction(): void #[Test] public function it_handles_callback_executing_multiple_times(): void { + $reporter = $this->createMock(ExceptionReporter::class); + $this->manager = new UnitOfWorkManager($this->unitOfWork, $reporter); + $ex = new LogicException('Boom!'); $sequence = []; $count = 0; - $this->reporter + $reporter ->expects($this->exactly(2)) ->method('report') ->with($this->identicalTo($ex)); @@ -384,11 +389,14 @@ function () use (&$sequence): void { #[Test] public function it_handles_unit_of_work_failing_multiple_times(): void { + $reporter = $this->createMock(ExceptionReporter::class); + $this->manager = new UnitOfWorkManager($this->unitOfWork, $reporter); + $ex = new LogicException('Boom!'); $sequence = []; $count = 0; - $this->reporter + $reporter ->expects($this->exactly(2)) ->method('report') ->with($this->identicalTo($ex)); @@ -412,6 +420,7 @@ function () use (&$sequence): void { ]; $this->unitOfWork + ->expects($this->exactly(3)) ->method('execute') ->willReturnCallback(function (Closure $closure) use ($ex, &$sequence, &$count): mixed { $count++; @@ -469,6 +478,10 @@ public function it_fails_if_before_callbacks_are_queued_before_transaction(): vo #[Test] public function it_fails_if_after_callbacks_are_queued_before_transaction(): void { + $this->unitOfWork + ->expects($this->never()) + ->method('execute'); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Cannot queue an after commit callback when not executing a unit of work.'); @@ -497,6 +510,7 @@ public function it_cannot_start_transaction_within_an_existing_one(): void public function it_fails_if_after_commit_callback_registers_before_commit_callback(): void { $this->unitOfWork + ->expects($this->once()) ->method('execute') ->willReturnCallback(fn (Closure $callback) => $callback()); diff --git a/tests/Unit/Domain/EntityTest.php b/tests/Unit/Domain/EntityTest.php index ecf42c1d..77d8cb10 100644 --- a/tests/Unit/Domain/EntityTest.php +++ b/tests/Unit/Domain/EntityTest.php @@ -41,7 +41,7 @@ public function it_is_the_same(): void ); $b = new TestEntity( - $id2 = $this->createMock(Identifier::class), + $id2 = $this->createStub(Identifier::class), ); $id1 @@ -62,7 +62,7 @@ public function it_is_not_the_same(): void ); $b = new TestEntity( - $id2 = $this->createMock(Identifier::class), + $id2 = $this->createStub(Identifier::class), ); $id1 @@ -82,8 +82,8 @@ public function it_is_different_class(): void $id1 = $this->createMock(Identifier::class), ); - $b = $this->createMock(Entity::class); - $b->method('getId')->willReturn($this->createMock(Identifier::class)); + $b = $this->createStub(Entity::class); + $b->method('getId')->willReturn($this->createStub(Identifier::class)); $id1 ->expects($this->never()) diff --git a/tests/Unit/Domain/EntityWithNullableGuidTest.php b/tests/Unit/Domain/EntityWithNullableGuidTest.php index de481945..51342b2c 100644 --- a/tests/Unit/Domain/EntityWithNullableGuidTest.php +++ b/tests/Unit/Domain/EntityWithNullableGuidTest.php @@ -86,7 +86,7 @@ public function it_is_the_same(): void ); $b = new TestEntityWithNullableId( - $id2 = $this->createMock(Identifier::class), + $id2 = $this->createStub(Identifier::class), ); $id1 @@ -143,7 +143,7 @@ public function it_is_not_the_same(): void ); $b = new TestEntityWithNullableId( - $id2 = $this->createMock(Identifier::class), + $id2 = $this->createStub(Identifier::class), ); $id1 @@ -163,8 +163,8 @@ public function it_is_different_class(): void $id1 = $this->createMock(Identifier::class), ); - $b = $this->createMock(Entity::class); - $b->method('getId')->willReturn($this->createMock(Identifier::class)); + $b = $this->createStub(Entity::class); + $b->method('getId')->willReturn($this->createStub(Identifier::class)); $id1 ->expects($this->never()) diff --git a/tests/Unit/Domain/EntityWithTypedIdTest.php b/tests/Unit/Domain/EntityWithTypedIdTest.php index 67c2965e..d6bb763f 100644 --- a/tests/Unit/Domain/EntityWithTypedIdTest.php +++ b/tests/Unit/Domain/EntityWithTypedIdTest.php @@ -62,7 +62,7 @@ public function it_is_not_the_same(): void public function it_is_different_class(): void { $a = new TestEntityWithTypedId(UuidV7::make()); - $b = $this->createMock(Entity::class); + $b = $this->createStub(Entity::class); $b->method('getId')->willReturn(UuidV7::from($a->id->toString())); $this->assertFalse($a->is($b)); diff --git a/tests/Unit/Domain/IdentifierOrEntityTest.php b/tests/Unit/Domain/IdentifierOrEntityTest.php index 8071d73c..cd92115a 100644 --- a/tests/Unit/Domain/IdentifierOrEntityTest.php +++ b/tests/Unit/Domain/IdentifierOrEntityTest.php @@ -33,7 +33,7 @@ public function it_is_a_guid(): void #[Test] public function it_is_an_entity_with_guid(): void { - $entity = $this->createMock(Entity::class); + $entity = $this->createStub(Entity::class); $entity->method('getId')->willReturn($guid = Guid::fromInteger('SomeType', 1)); $guidOrEntity = IdentifierOrEntity::make($entity); @@ -46,7 +46,7 @@ public function it_is_an_entity_with_guid(): void #[Test] public function it_is_an_entity_without_guid(): void { - $entity = $this->createMock(Entity::class); + $entity = $this->createStub(Entity::class); $entity->method('getId')->willReturn(null); $guidOrEntity = IdentifierOrEntity::make($entity); diff --git a/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php b/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php index fcc885e0..e50b2b2e 100644 --- a/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php +++ b/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php @@ -69,6 +69,10 @@ public function it_publishes_an_event(): void ->method('__invoke') ->with($this->identicalTo($event)); + $this->middleware + ->expects($this->never()) + ->method($this->anything()); + $this->publisher->publish($event); } diff --git a/tests/Unit/Infrastructure/Queue/ClosureQueueTest.php b/tests/Unit/Infrastructure/Queue/ClosureQueueTest.php index bbc981f7..6ddbf61b 100644 --- a/tests/Unit/Infrastructure/Queue/ClosureQueueTest.php +++ b/tests/Unit/Infrastructure/Queue/ClosureQueueTest.php @@ -17,13 +17,10 @@ use CloudCreativity\Modules\Infrastructure\Queue\ClosureQueue; use CloudCreativity\Modules\Tests\Unit\Application\Bus\TestCommand; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; final class ClosureQueueTest extends TestCase { - private MockObject&PipeContainer $middleware; - /** * @var array */ @@ -35,24 +32,19 @@ protected function setUp(): void { parent::setUp(); - $this->queue = new class ( - function (Command $command): void { - $this->actual[] = $command; - }, - $this->middleware = $this->createMock(PipeContainer::class), - ) extends ClosureQueue {}; + $this->queue = $this->createQueue($this->createStub(PipeContainer::class)); } protected function tearDown(): void { - unset($this->queue, $this->middleware, $this->actual); + unset($this->queue, $this->actual); parent::tearDown(); } #[Test] public function it_queues_a_command(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $this->queue->push($command); @@ -62,10 +54,10 @@ public function it_queues_a_command(): void #[Test] public function it_queues_a_command_through_middleware(): void { - $command1 = $this->createMock(Command::class); - $command2 = $this->createMock(Command::class); - $command3 = $this->createMock(Command::class); - $command4 = $this->createMock(Command::class); + $command1 = $this->createStub(Command::class); + $command2 = $this->createStub(Command::class); + $command3 = $this->createStub(Command::class); + $command4 = $this->createStub(Command::class); $middleware1 = function ($command, \Closure $next) use ($command1, $command2) { $this->assertSame($command1, $command); @@ -82,12 +74,15 @@ public function it_queues_a_command_through_middleware(): void return $next($command4); }; - $this->middleware + $middleware = $this->createMock(PipeContainer::class); + $middleware ->expects($this->once()) ->method('get') ->with('MySecondMiddleware') ->willReturn($middleware2); + $this->queue = $this->createQueue($middleware); + $this->queue->through([ $middleware1, 'MySecondMiddleware', @@ -99,15 +94,14 @@ public function it_queues_a_command_through_middleware(): void $this->assertSame([$command4], $this->actual); } - #[Test] public function it_queues_using_the_handler_bound_to_the_command_class(): void { $expected = new TestCommand(); - $mock = $this->createMock(Command::class); + $stub = $this->createStub(Command::class); $actual = null; - $this->queue->bind($mock::class, function (Command $cmd): never { + $this->queue->bind($stub::class, function (Command $cmd): never { $this->fail('Not expecting this closure to be called.'); }); @@ -123,4 +117,14 @@ function (TestCommand $cmd) use (&$actual) { $this->assertEmpty($this->actual); $this->assertSame($expected, $actual); } + + private function createQueue(PipeContainer $middleware): ClosureQueue + { + return new class ( + function (Command $command): void { + $this->actual[] = $command; + }, + $middleware, + ) extends ClosureQueue {}; + } } diff --git a/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php b/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php index 82c76cfd..f40dc45e 100644 --- a/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php +++ b/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php @@ -25,8 +25,6 @@ final class ComponentQueueTest extends TestCase { private EnqueuerContainer&MockObject $enqueuers; - private MockObject&PipeContainer $middleware; - private ComponentQueue $queue; /** @@ -40,20 +38,20 @@ protected function setUp(): void $this->queue = new class ( enqueuers: $this->enqueuers = $this->createMock(EnqueuerContainer::class), - middleware: $this->middleware = $this->createMock(PipeContainer::class), + middleware: $this->createStub(PipeContainer::class), ) extends ComponentQueue {}; } protected function tearDown(): void { - unset($this->queue, $this->enqueuers, $this->middleware, $this->sequence); + unset($this->queue, $this->enqueuers, $this->sequence); parent::tearDown(); } #[Test] public function it_queues_a_command(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $this->enqueuers ->expects($this->once()) @@ -72,9 +70,9 @@ public function it_queues_a_command(): void #[Test] public function it_queues_through_middleware(): void { - $command1 = $this->createMock(Command::class); - $command2 = $this->createMock(Command::class); - $command3 = $this->createMock(Command::class); + $command1 = $this->createStub(Command::class); + $command2 = $this->createStub(Command::class); + $command3 = $this->createStub(Command::class); $enqueuer = $this->createMock(Enqueuer::class); $middleware1 = function ($actual, \Closure $next) use ($command1, $command2): void { @@ -105,12 +103,18 @@ public function it_queues_through_middleware(): void ->method('__invoke') ->with($this->identicalTo($command3)); - $this->middleware + $middleware = $this->createMock(PipeContainer::class); + $middleware ->expects($this->once()) ->method('get') ->with('MySecondMiddleware') ->willReturn($middleware2); + $this->queue = new class ( + enqueuers: $this->enqueuers, + middleware: $middleware, + ) extends ComponentQueue {}; + $this->queue->through([$middleware1, 'MySecondMiddleware']); $this->queue->push($command1); diff --git a/tests/Unit/Infrastructure/Queue/EnqueuerTest.php b/tests/Unit/Infrastructure/Queue/EnqueuerTest.php index 4765a134..b5e05a8d 100644 --- a/tests/Unit/Infrastructure/Queue/EnqueuerTest.php +++ b/tests/Unit/Infrastructure/Queue/EnqueuerTest.php @@ -22,7 +22,7 @@ final class EnqueuerTest extends TestCase #[Test] public function it_pushes_the_command_to_the_inner_enqueuer(): void { - $command = $this->createMock(Command::class); + $command = $this->createStub(Command::class); $innerEnqueuer = $this->createMock(TestEnqueuer::class); $innerEnqueuer diff --git a/tests/Unit/Testing/FakeDomainEventDispatcherTest.php b/tests/Unit/Testing/FakeDomainEventDispatcherTest.php index ac8370e4..3c27ffb2 100644 --- a/tests/Unit/Testing/FakeDomainEventDispatcherTest.php +++ b/tests/Unit/Testing/FakeDomainEventDispatcherTest.php @@ -26,8 +26,8 @@ public function it_publishes_events(): void { $dispatcher = new class () extends FakeDomainEventDispatcher {}; - $event1 = $this->createMock(DomainEvent::class); - $event2 = $this->createMock(DomainEvent::class); + $event1 = $this->createStub(DomainEvent::class); + $event2 = $this->createStub(DomainEvent::class); $dispatcher->dispatch($event1); $dispatcher->dispatch($event2); @@ -46,7 +46,7 @@ public function it_publishes_events(): void public function it_returns_sole_event(): void { $dispatcher = new class () extends FakeDomainEventDispatcher {}; - $event = $this->createMock(DomainEvent::class); + $event = $this->createStub(DomainEvent::class); $dispatcher->dispatch($event); @@ -68,8 +68,8 @@ public function it_throws_exception_if_no_events(): void public function it_throws_exception_if_multiple_events(): void { $dispatcher = new class () extends FakeDomainEventDispatcher {}; - $event1 = $this->createMock(DomainEvent::class); - $event2 = $this->createMock(DomainEvent::class); + $event1 = $this->createStub(DomainEvent::class); + $event2 = $this->createStub(DomainEvent::class); $dispatcher->dispatch($event1); $dispatcher->dispatch($event2); diff --git a/tests/Unit/Testing/FakeOutboundEventPublisherTest.php b/tests/Unit/Testing/FakeOutboundEventPublisherTest.php index aed8e515..f25cf3b7 100644 --- a/tests/Unit/Testing/FakeOutboundEventPublisherTest.php +++ b/tests/Unit/Testing/FakeOutboundEventPublisherTest.php @@ -26,8 +26,8 @@ public function it_publishes_events(): void { $publisher = new class () extends FakeOutboundEventPublisher {}; - $event1 = $this->createMock(IntegrationEvent::class); - $event2 = $this->createMock(IntegrationEvent::class); + $event1 = $this->createStub(IntegrationEvent::class); + $event2 = $this->createStub(IntegrationEvent::class); $publisher->publish($event1); $publisher->publish($event2); @@ -44,7 +44,7 @@ public function it_publishes_events(): void public function it_returns_sole_event(): void { $publisher = new class () extends FakeOutboundEventPublisher {}; - $event = $this->createMock(IntegrationEvent::class); + $event = $this->createStub(IntegrationEvent::class); $publisher->publish($event); @@ -66,8 +66,8 @@ public function it_throws_exception_if_no_events(): void public function it_throws_exception_if_multiple_events(): void { $publisher = new class () extends FakeOutboundEventPublisher {}; - $event1 = $this->createMock(IntegrationEvent::class); - $event2 = $this->createMock(IntegrationEvent::class); + $event1 = $this->createStub(IntegrationEvent::class); + $event2 = $this->createStub(IntegrationEvent::class); $publisher->publish($event1); $publisher->publish($event2); diff --git a/tests/Unit/Testing/FakeQueueTest.php b/tests/Unit/Testing/FakeQueueTest.php index 04e2d521..beb4a469 100644 --- a/tests/Unit/Testing/FakeQueueTest.php +++ b/tests/Unit/Testing/FakeQueueTest.php @@ -25,8 +25,8 @@ final class FakeQueueTest extends TestCase public function it_queues_commands(): void { $queue = new class () extends FakeQueue {}; - $queue->push($command1 = $this->createMock(Command::class)); - $queue->push($command2 = $this->createMock(Command::class)); + $queue->push($command1 = $this->createStub(Command::class)); + $queue->push($command2 = $this->createStub(Command::class)); $this->assertInstanceOf(Queue::class, $queue); $this->assertCount(2, $queue); @@ -40,7 +40,7 @@ public function it_queues_commands(): void public function it_has_sole_command(): void { $queue = new class () extends FakeQueue {}; - $queue->push($command = $this->createMock(Command::class)); + $queue->push($command = $this->createStub(Command::class)); $this->assertSame($command, $queue->sole()); } @@ -62,8 +62,8 @@ public function it_fails_when_there_is_more_than_one_sole_command(): void $this->expectException(LogicException::class); $queue = new class () extends FakeQueue {}; - $queue->push($this->createMock(Command::class)); - $queue->push($this->createMock(Command::class)); + $queue->push($this->createStub(Command::class)); + $queue->push($this->createStub(Command::class)); $queue->sole(); } } diff --git a/tests/Unit/Toolkit/Identifiers/GuidTest.php b/tests/Unit/Toolkit/Identifiers/GuidTest.php index 81529c4d..08aece24 100644 --- a/tests/Unit/Toolkit/Identifiers/GuidTest.php +++ b/tests/Unit/Toolkit/Identifiers/GuidTest.php @@ -59,8 +59,12 @@ public static function typeProvider(): array */ #[DataProvider('typeProvider')] #[Test] - public function it_can_be_created_from_a_string_id(string|UnitEnum $type, string $value, string|UnitEnum $other): void - { + public function it_can_be_created_from_a_string_id( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { $guid = Guid::fromString($type, '123'); $others = [ @@ -92,8 +96,12 @@ public function it_can_be_created_from_a_string_id(string|UnitEnum $type, string #[DataProvider('typeProvider')] #[Test] - public function it_can_be_created_from_an_integer_id(string|UnitEnum $type, string $value, string|UnitEnum $other): void - { + public function it_can_be_created_from_an_integer_id( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { $guid = Guid::fromInteger($type, 123); $this->assertSame($type, $guid->type); @@ -115,8 +123,12 @@ public function it_can_be_created_from_an_integer_id(string|UnitEnum $type, stri #[DataProvider('typeProvider')] #[Test] - public function it_can_be_created_from_a_uuid(string|UnitEnum $type, string $value, string|UnitEnum $other): void - { + public function it_can_be_created_from_a_uuid( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { $uuid = Uuid::random(); $guid = Guid::fromUuid($type, $uuid->value); @@ -209,8 +221,12 @@ public function it_wraps_a_string_in_a_string_id(): void #[DataProvider('typeProvider')] #[Test] - public function it_checks_if_it_is_any_of_multiple_types(string|UnitEnum $type, string $value, string|UnitEnum $other): void - { + public function it_checks_if_it_is_any_of_multiple_types( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { $guid = Guid::fromInteger($type, 1); $this->assertTrue($guid->isType($other, $type)); @@ -220,8 +236,12 @@ public function it_checks_if_it_is_any_of_multiple_types(string|UnitEnum $type, #[DataProvider('typeProvider')] #[Test] - public function it_does_not_throw_when_asserting_the_expected_type(string|UnitEnum $type): void - { + public function it_does_not_throw_when_asserting_the_expected_type( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { $guid = Guid::fromInteger($type, 1); $actual = $guid->assertType($type); diff --git a/tests/Unit/Toolkit/Identifiers/UuidFactoryTest.php b/tests/Unit/Toolkit/Identifiers/UuidFactoryTest.php index ecc4e640..56084ab1 100644 --- a/tests/Unit/Toolkit/Identifiers/UuidFactoryTest.php +++ b/tests/Unit/Toolkit/Identifiers/UuidFactoryTest.php @@ -84,7 +84,7 @@ public function it_rejects_a_non_uuid_identifier(): void $this->expectException(ContractException::class); $this->factory->from( - $this->createMock(Identifier::class), + $this->createStub(Identifier::class), ); } @@ -278,8 +278,12 @@ public function it_creates_a_uuid_v7(): void #[Test] public function it_throws_if_uuid_v7_is_not_supported(): void { + $this->baseFactory + ->expects($this->never()) + ->method($this->anything()); + $factory = new UuidFactory( - $this->createMock(BaseUuidFactoryInterface::class), + $this->createStub(BaseUuidFactoryInterface::class), ); $this->expectException(\RuntimeException::class); @@ -308,8 +312,12 @@ public function it_creates_a_uuid_v8(): void #[Test] public function it_throws_if_uuid_v8_is_not_supported(): void { + $this->baseFactory + ->expects($this->never()) + ->method($this->anything()); + $factory = new UuidFactory( - $this->createMock(BaseUuidFactoryInterface::class), + $this->createStub(BaseUuidFactoryInterface::class), ); $this->expectException(\RuntimeException::class); diff --git a/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php b/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php index 410f2e9c..9e1e4e47 100644 --- a/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php +++ b/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php @@ -26,7 +26,7 @@ final class PipelineBuilderTest extends TestCase public function it_builds_a_pipeline(): void { $expected = new Pipeline( - $processor = $this->createMock(Processor::class), + $processor = $this->createStub(Processor::class), $stages = ['strtoupper', 'strtolower'], ); @@ -41,8 +41,8 @@ public function it_builds_a_pipeline(): void #[Test] public function it_builds_a_pipeline_with_lazy_pipes_for_service_strings(): void { - $container = $this->createMock(PipeContainer::class); - $processor = $this->createMock(Processor::class); + $container = $this->createStub(PipeContainer::class); + $processor = $this->createStub(Processor::class); $expected = new Pipeline($processor, [ 'strtoupper', diff --git a/tests/Unit/Toolkit/Result/ResultTest.php b/tests/Unit/Toolkit/Result/ResultTest.php index 3491829a..7d0e7856 100644 --- a/tests/Unit/Toolkit/Result/ResultTest.php +++ b/tests/Unit/Toolkit/Result/ResultTest.php @@ -162,7 +162,7 @@ public function it_throws_when_getting_value_on_failed_result(Result $result): v #[Test] public function it_fails_with_a_list_of_errors_implementation(): void { - $errors = $this->createMock(IListOfErrors::class); + $errors = $this->createStub(IListOfErrors::class); $errors->method('isNotEmpty')->willReturn(true); $result = Result::failed($errors); From 7186f2ff5b4157e32db1d9be5759afac76580875 Mon Sep 17 00:00:00 2001 From: Christopher Gammie Date: Sat, 14 Nov 2026 13:30:44 +0000 Subject: [PATCH 3/3] test: fill coverage gaps and align tests with the unit-testing skill Add unit tests for untested behaviour across Toolkit, Bus, Application, Domain, Infrastructure and the Testing fakes, raising line coverage from 92% to 99.7%. The remaining uncovered lines are unreachable. Clean up existing tests to follow the unit-testing skill: one AAA per test, expectations at the end of arrange, exact exception messages, real instances and shipped fakes over mocks, no unused setUp mocks, and no tests of native assert() AssertionErrors. Bugs found in src while writing the tests are recorded in #40. Co-Authored-By: Claude Opus 5.5 --- tests/Integration/Bus/MathCommandBusTest.php | 47 +- tests/Integration/Bus/MathEventBusTest.php | 85 +++- tests/Integration/Bus/MathQueryBusTest.php | 44 +- .../MathEventPublisherTest.php | 82 +++- .../Infrastructure/Queue/MathQueueTest.php | 82 +++- .../Bus/AbortOnFailureExceptionTest.php | 43 ++ .../Unit/Application/Bus/BusExceptionTest.php | 32 ++ .../Application/Bus/CommandDispatcherTest.php | 134 ++++-- .../Bus/CommandHandlerContainerTest.php | 60 ++- .../Application/Bus/CommandHandlerTest.php | 46 +- .../Application/Bus/CommandQueuerTest.php | 14 +- .../Middleware/FlushDeferredEventsTest.php | 8 +- .../Bus/Middleware/LogMessageDispatchTest.php | 134 ++++-- .../TestValidateMessageWithRules.php | 21 + .../Bus/Middleware/ValidateMessageTest.php | 137 ++++-- .../Application/Bus/QueryDispatcherTest.php | 145 +++--- .../Bus/QueryHandlerContainerTest.php | 62 ++- .../Unit/Application/Bus/QueryHandlerTest.php | 46 +- .../Application/Bus/SanitizedMessageTest.php | 54 +++ .../TestCommandDispatcherWithAttributes.php | 23 + .../Bus/TestCommandHandlerWithThrough.php | 28 ++ .../Bus/TestQueryDispatcherWithAttributes.php | 23 + .../Bus/TestQueryHandlerWithThrough.php | 28 ++ .../Application/Bus/TestSensitiveCommand.php | 33 ++ .../Bus/ValidationProcessorTest.php | 108 +++++ tests/Unit/Application/Bus/ValidatorTest.php | 73 ++- .../DeferredDispatcherTest.php | 314 +++++------- .../DomainEventDispatching/DispatcherTest.php | 201 +++++--- .../EventHandlerTest.php | 88 ++++ .../ListenerContainerTest.php | 64 ++- .../Middleware/LogDomainEventDispatchTest.php | 59 +-- .../TestDispatcherWithAttributes.php | 24 + .../UnitOfWorkAwareDispatcherTest.php | 293 ++++++------ .../EventHandlerContainerTest.php | 105 ++-- .../InboundEventBus/EventHandlerTest.php | 44 +- .../InboundEventDispatcherTest.php | 151 ++++-- .../SwallowInboundEventTest.php | 39 +- .../TestEventHandlerWithThrough.php | 24 + ...stInboundEventDispatcherWithAttributes.php | 26 + .../InboundEventBus/TestOtherInboundEvent.php | 30 ++ .../UnitOfWork/UnitOfWorkManagerTest.php | 142 +++--- tests/Unit/Bus/PsrPipeContainerTest.php | 26 +- tests/Unit/Domain/EntityTest.php | 72 +-- .../Domain/EntityWithNullableGuidTest.php | 92 +--- tests/Unit/Domain/EntityWithTypedIdTest.php | 24 +- tests/Unit/Domain/IdentifierOrEntityTest.php | 13 +- tests/Unit/Domain/MutableTestEntity.php | 37 ++ .../Domain/MutableTestEntityWithTypedId.php | 31 ++ .../PsrLogExceptionReporterTest.php | 91 ++-- .../Monolog/ContextualProcessorTest.php | 210 ++++++++ .../Monolog/RecursiveParserTest.php | 223 +++++++++ .../OutboundEventBus/ClosurePublisherTest.php | 44 +- .../ComponentPublisherTest.php | 206 +++++--- .../Middleware/LogOutboundEventTest.php | 123 +++++ .../PublisherHandlerContainerTest.php | 237 ++++++--- .../OutboundEventBus/PublisherHandlerTest.php | 29 +- .../TestComponentPublisherWithAttributes.php | 25 + .../TestNamedOutboundEvent.php | 25 + .../Infrastructure/Queue/ClosureQueueTest.php | 66 ++- .../Queue/ComponentQueueTest.php | 216 ++++++--- .../Queue/EnqueuerContainerTest.php | 230 +++++++-- .../Infrastructure/Queue/EnqueuerTest.php | 19 +- .../Queue/Middleware/LogPushedToQueueTest.php | 119 +++++ .../TestComponentQueueWithAttributes.php | 27 ++ .../Queue/TestQueueableCommand.php | 25 + tests/Unit/Testing/FakeContainerTest.php | 204 ++++++++ .../Testing/FakeDomainEventDispatcherTest.php | 152 +++++- .../Testing/FakeExceptionReporterTest.php | 191 ++++++-- tests/Unit/Testing/FakeLoggerTest.php | 127 +++++ .../FakeOutboundEventPublisherTest.php | 146 +++++- tests/Unit/Testing/FakeQueueTest.php | 155 +++++- tests/Unit/Testing/FakeUnitOfWorkTest.php | 188 ++++++-- tests/Unit/Toolkit/ContractsTest.php | 29 +- tests/Unit/Toolkit/Identifiers/GuidTest.php | 448 +++++++++++++++--- .../Toolkit/Identifiers/GuidTypeMapTest.php | 145 +++--- .../Identifiers/IdentifierFactoryTest.php | 154 ++++++ .../Toolkit/Identifiers/IntegerIdTest.php | 156 ++++-- .../Toolkit/Identifiers/IsIdentifierTest.php | 60 +++ tests/Unit/Toolkit/Identifiers/IsUuidTest.php | 170 +++++++ .../Identifiers/PossiblyNumericIdTest.php | 54 ++- .../Unit/Toolkit/Identifiers/StringIdTest.php | 160 ++++++- .../Toolkit/Identifiers/TestIdentifier.php | 50 ++ tests/Unit/Toolkit/Identifiers/TestUuid.php | 26 + .../Toolkit/Identifiers/UuidFactoryTest.php | 59 +-- tests/Unit/Toolkit/Identifiers/UuidTest.php | 363 +++++++++++--- tests/Unit/Toolkit/Identifiers/UuidV4Test.php | 243 +++++++--- tests/Unit/Toolkit/Identifiers/UuidV7Test.php | 257 +++++++--- .../Unit/Toolkit/Iterables/IsKeyedSetTest.php | 102 ++++ .../Unit/Toolkit/Iterables/IsLazyListTest.php | 67 ++- tests/Unit/Toolkit/Iterables/IsListTest.php | 98 ++++ .../Toolkit/Iterables/IsNonEmptyListTest.php | 40 +- tests/Unit/Toolkit/ModuleBasenameTest.php | 146 +++++- .../Pipeline/AccumulationProcessorTest.php | 12 +- tests/Unit/Toolkit/Pipeline/LazyPipeTest.php | 41 +- .../Pipeline/MiddlewareProcessorTest.php | 31 ++ .../Toolkit/Pipeline/PipeContainerTest.php | 57 ++- .../Toolkit/Pipeline/PipelineBuilderTest.php | 47 +- tests/Unit/Toolkit/Pipeline/PipelineTest.php | 36 +- tests/Unit/Toolkit/Pipeline/ThroughTest.php | 70 +++ .../Toolkit/Result/ContextualResultTest.php | 264 +++++++++++ tests/Unit/Toolkit/Result/ErrorTest.php | 48 +- .../Result/FailedResultExceptionTest.php | 59 ++- .../Toolkit/Result/KeyedSetOfErrorsTest.php | 140 +++++- .../Unit/Toolkit/Result/ListOfErrorsTest.php | 388 +++++++++++---- tests/Unit/Toolkit/Result/MetaTest.php | 170 ++++++- tests/Unit/Toolkit/Result/ResultTest.php | 404 ++++++++++++---- tests/Unit/Toolkit/SensitiveTest.php | 48 ++ 107 files changed, 8866 insertions(+), 2345 deletions(-) create mode 100644 tests/Unit/Application/Bus/AbortOnFailureExceptionTest.php create mode 100644 tests/Unit/Application/Bus/BusExceptionTest.php create mode 100644 tests/Unit/Application/Bus/Middleware/TestValidateMessageWithRules.php create mode 100644 tests/Unit/Application/Bus/SanitizedMessageTest.php create mode 100644 tests/Unit/Application/Bus/TestCommandDispatcherWithAttributes.php create mode 100644 tests/Unit/Application/Bus/TestCommandHandlerWithThrough.php create mode 100644 tests/Unit/Application/Bus/TestQueryDispatcherWithAttributes.php create mode 100644 tests/Unit/Application/Bus/TestQueryHandlerWithThrough.php create mode 100644 tests/Unit/Application/Bus/TestSensitiveCommand.php create mode 100644 tests/Unit/Application/Bus/ValidationProcessorTest.php create mode 100644 tests/Unit/Application/DomainEventDispatching/EventHandlerTest.php create mode 100644 tests/Unit/Application/DomainEventDispatching/TestDispatcherWithAttributes.php create mode 100644 tests/Unit/Application/InboundEventBus/TestEventHandlerWithThrough.php create mode 100644 tests/Unit/Application/InboundEventBus/TestInboundEventDispatcherWithAttributes.php create mode 100644 tests/Unit/Application/InboundEventBus/TestOtherInboundEvent.php create mode 100644 tests/Unit/Domain/MutableTestEntity.php create mode 100644 tests/Unit/Domain/MutableTestEntityWithTypedId.php create mode 100644 tests/Unit/Infrastructure/Monolog/ContextualProcessorTest.php create mode 100644 tests/Unit/Infrastructure/Monolog/RecursiveParserTest.php create mode 100644 tests/Unit/Infrastructure/OutboundEventBus/Middleware/LogOutboundEventTest.php create mode 100644 tests/Unit/Infrastructure/OutboundEventBus/TestComponentPublisherWithAttributes.php create mode 100644 tests/Unit/Infrastructure/OutboundEventBus/TestNamedOutboundEvent.php create mode 100644 tests/Unit/Infrastructure/Queue/Middleware/LogPushedToQueueTest.php create mode 100644 tests/Unit/Infrastructure/Queue/TestComponentQueueWithAttributes.php create mode 100644 tests/Unit/Infrastructure/Queue/TestQueueableCommand.php create mode 100644 tests/Unit/Testing/FakeContainerTest.php create mode 100644 tests/Unit/Testing/FakeLoggerTest.php create mode 100644 tests/Unit/Toolkit/Identifiers/IdentifierFactoryTest.php create mode 100644 tests/Unit/Toolkit/Identifiers/IsIdentifierTest.php create mode 100644 tests/Unit/Toolkit/Identifiers/IsUuidTest.php create mode 100644 tests/Unit/Toolkit/Identifiers/TestIdentifier.php create mode 100644 tests/Unit/Toolkit/Identifiers/TestUuid.php create mode 100644 tests/Unit/Toolkit/Iterables/IsKeyedSetTest.php create mode 100644 tests/Unit/Toolkit/Iterables/IsListTest.php create mode 100644 tests/Unit/Toolkit/Pipeline/ThroughTest.php create mode 100644 tests/Unit/Toolkit/Result/ContextualResultTest.php create mode 100644 tests/Unit/Toolkit/SensitiveTest.php diff --git a/tests/Integration/Bus/MathCommandBusTest.php b/tests/Integration/Bus/MathCommandBusTest.php index 423b2113..845707a7 100644 --- a/tests/Integration/Bus/MathCommandBusTest.php +++ b/tests/Integration/Bus/MathCommandBusTest.php @@ -21,10 +21,15 @@ final class MathCommandBusTest extends TestCase { - #[Test] - public function it_dispatches_commands(): void + private FakeContainer $container; + + private MathCommandBus $bus; + + protected function setUp(): void { - $container = new FakeContainer(); + parent::setUp(); + + $this->container = $container = new FakeContainer(); $container->bind(AddCommandHandler::class, fn () => new AddCommandHandler(3)); $container->bind(MultiplyCommandHandler::class, fn () => new MultiplyCommandHandler()); $container->bind(LogMessageDispatch::class, fn () => new LogMessageDispatch($container->logger)); @@ -32,14 +37,36 @@ public function it_dispatches_commands(): void new UnitOfWorkManager($container->unitOfWork), )); - $bus = new MathCommandBus($container); + $this->bus = new MathCommandBus($container); + } + + protected function tearDown(): void + { + unset($this->container, $this->bus); + parent::tearDown(); + } + + #[Test] + public function it_dispatches_a_command_through_the_bus_middleware(): void + { + $command = new AddCommand(1, 2); + + $result = $this->bus->dispatch($command); + + $this->assertSame(6, $result->value()); + $this->assertCount(2, $this->container->logger); + $this->assertSame(0, $this->container->unitOfWork->commits); + } + + #[Test] + public function it_dispatches_a_command_through_the_handler_middleware(): void + { + $command = new MultiplyCommand(10, 11); - $add = $bus->dispatch(new AddCommand(1, 2)); - $multiply = $bus->dispatch(new MultiplyCommand(10, 11)); + $result = $this->bus->dispatch($command); - $this->assertSame(6, $add->value()); - $this->assertSame(110, $multiply->value()); - $this->assertCount(4, $container->logger); - $this->assertSame(1, $container->unitOfWork->commits); + $this->assertSame(110, $result->value()); + $this->assertCount(2, $this->container->logger); + $this->assertSame(1, $this->container->unitOfWork->commits); } } diff --git a/tests/Integration/Bus/MathEventBusTest.php b/tests/Integration/Bus/MathEventBusTest.php index b822efa2..db1914c1 100644 --- a/tests/Integration/Bus/MathEventBusTest.php +++ b/tests/Integration/Bus/MathEventBusTest.php @@ -21,14 +21,25 @@ final class MathEventBusTest extends TestCase { - #[Test] - public function it_dispatches_events(): void + private FakeContainer $container; + + private NumbersAddedHandler $addedHandler; + + private NumbersSubtractedHandler $subtractedHandler; + + private DefaultEventHandler $defaultHandler; + + private MathEventBus $bus; + + protected function setUp(): void { - $a = new NumbersAddedHandler(); - $b = new NumbersSubtractedHandler(); - $c = new DefaultEventHandler(); + parent::setUp(); + + $this->addedHandler = $a = new NumbersAddedHandler(); + $this->subtractedHandler = $b = new NumbersSubtractedHandler(); + $this->defaultHandler = $c = new DefaultEventHandler(); - $container = new FakeContainer(); + $this->container = $container = new FakeContainer(); $container->bind(NumbersAddedHandler::class, fn () => $a); $container->bind(NumbersSubtractedHandler::class, fn () => $b); $container->bind(DefaultEventHandler::class, fn () => $c); @@ -37,16 +48,60 @@ public function it_dispatches_events(): void new UnitOfWorkManager($container->unitOfWork), )); - $bus = new MathEventBus($container); + $this->bus = new MathEventBus($container); + } + + protected function tearDown(): void + { + unset( + $this->container, + $this->addedHandler, + $this->subtractedHandler, + $this->defaultHandler, + $this->bus, + ); + parent::tearDown(); + } + + #[Test] + public function it_dispatches_an_event_to_its_handler(): void + { + $event = new NumbersAdded(1, 2, 3); + + $this->bus->dispatch($event); + + $this->assertSame([$event], $this->addedHandler->handled); + $this->assertSame([], $this->subtractedHandler->handled); + $this->assertSame([], $this->defaultHandler->handled); + $this->assertCount(2, $this->container->logger); + $this->assertSame(0, $this->container->unitOfWork->commits); + } + + #[Test] + public function it_dispatches_an_event_through_the_handler_middleware(): void + { + $event = new NumbersSubtracted(10, 6, 4); + + $this->bus->dispatch($event); + + $this->assertSame([], $this->addedHandler->handled); + $this->assertSame([$event], $this->subtractedHandler->handled); + $this->assertSame([], $this->defaultHandler->handled); + $this->assertCount(2, $this->container->logger); + $this->assertSame(1, $this->container->unitOfWork->commits); + } + + #[Test] + public function it_dispatches_an_event_to_the_default_handler(): void + { + $event = new NumbersDivided(12, 3, 4); - $bus->dispatch($ev1 = new NumbersAdded(1, 2, 3)); - $bus->dispatch($ev2 = new NumbersSubtracted(10, 6, 4)); - $bus->dispatch($ev3 = new NumbersDivided(12, 3, 4)); + $this->bus->dispatch($event); - $this->assertSame([$ev1], $a->handled); - $this->assertSame([$ev2], $b->handled); - $this->assertSame([$ev3], $c->handled); - $this->assertCount(6, $container->logger); - $this->assertSame(1, $container->unitOfWork->commits); + $this->assertSame([], $this->addedHandler->handled); + $this->assertSame([], $this->subtractedHandler->handled); + $this->assertSame([$event], $this->defaultHandler->handled); + $this->assertCount(2, $this->container->logger); + $this->assertSame(0, $this->container->unitOfWork->commits); } } diff --git a/tests/Integration/Bus/MathQueryBusTest.php b/tests/Integration/Bus/MathQueryBusTest.php index 84b06051..a20e72a6 100644 --- a/tests/Integration/Bus/MathQueryBusTest.php +++ b/tests/Integration/Bus/MathQueryBusTest.php @@ -20,10 +20,15 @@ final class MathQueryBusTest extends TestCase { - #[Test] - public function it_dispatches_queries(): void + private FakeContainer $container; + + private MathQueryBus $bus; + + protected function setUp(): void { - $container = new FakeContainer(); + parent::setUp(); + + $this->container = $container = new FakeContainer(); $container->bind(SubtractQueryHandler::class, fn () => new SubtractQueryHandler(3)); $container->bind(DivideQueryHandler::class, fn () => new DivideQueryHandler()); $container->bind(LogMessageDispatch::class, fn () => new LogMessageDispatch($container->logger)); @@ -32,13 +37,34 @@ public function it_dispatches_queries(): void return $next($query); }); - $bus = new MathQueryBus($container); + $this->bus = new MathQueryBus($container); + } + + protected function tearDown(): void + { + unset($this->container, $this->bus); + parent::tearDown(); + } + + #[Test] + public function it_dispatches_a_query_through_the_bus_middleware(): void + { + $query = new SubtractQuery(1, 2); + + $result = $this->bus->dispatch($query); + + $this->assertSame(1 - 2 - 3, $result->value()); + $this->assertCount(2, $this->container->logger); + } + + #[Test] + public function it_dispatches_a_query_through_the_handler_middleware(): void + { + $query = new DivideQuery(12, 3); - $add = $bus->dispatch(new SubtractQuery(1, 2)); - $multiply = $bus->dispatch(new DivideQuery(12, 3)); + $result = $this->bus->dispatch($query); - $this->assertSame(1 - 2 - 3, $add->value()); - $this->assertEquals(120 / 3, $multiply->value()); - $this->assertCount(4, $container->logger); + $this->assertEquals(120 / 3, $result->value()); + $this->assertCount(2, $this->container->logger); } } diff --git a/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php b/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php index 439f1b3a..8f906535 100644 --- a/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php +++ b/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php @@ -22,27 +22,81 @@ final class MathEventPublisherTest extends TestCase { - #[Test] - public function it_publishes_events(): void + private FakeContainer $container; + + private NumbersAddedPublisher $addedPublisher; + + private NumbersSubtractedPublisher $subtractedPublisher; + + private TestDefaultPublisher $defaultPublisher; + + private MathEventPublisher $publisher; + + protected function setUp(): void { - $a = new NumbersAddedPublisher(); - $b = new NumbersSubtractedPublisher(); - $c = new TestDefaultPublisher(); + parent::setUp(); + + $this->addedPublisher = $a = new NumbersAddedPublisher(); + $this->subtractedPublisher = $b = new NumbersSubtractedPublisher(); + $this->defaultPublisher = $c = new TestDefaultPublisher(); - $container = new FakeContainer(); + $this->container = $container = new FakeContainer(); $container->bind(NumbersAddedPublisher::class, fn () => $a); $container->bind(NumbersSubtractedPublisher::class, fn () => $b); $container->bind(TestDefaultPublisher::class, fn () => $c); $container->bind(LogOutboundEvent::class, fn () => new LogOutboundEvent($container->logger)); - $publisher = new MathEventPublisher($container); - $publisher->publish($ev1 = new NumbersAdded(1, 2, 3)); - $publisher->publish($ev2 = new NumbersSubtracted(10, 6, 4)); - $publisher->publish($ev3 = new NumbersDivided(12, 3, 4)); + $this->publisher = new MathEventPublisher($container); + } + + protected function tearDown(): void + { + unset( + $this->container, + $this->addedPublisher, + $this->subtractedPublisher, + $this->defaultPublisher, + $this->publisher, + ); + parent::tearDown(); + } + + #[Test] + public function it_publishes_an_event_via_its_publisher(): void + { + $event = new NumbersAdded(1, 2, 3); + + $this->publisher->publish($event); + + $this->assertSame([$event], $this->addedPublisher->published); + $this->assertSame([], $this->subtractedPublisher->published); + $this->assertSame([], $this->defaultPublisher->published); + $this->assertCount(2, $this->container->logger); + } + + #[Test] + public function it_publishes_another_event_via_its_publisher(): void + { + $event = new NumbersSubtracted(10, 6, 4); + + $this->publisher->publish($event); + + $this->assertSame([], $this->addedPublisher->published); + $this->assertSame([$event], $this->subtractedPublisher->published); + $this->assertSame([], $this->defaultPublisher->published); + $this->assertCount(2, $this->container->logger); + } + + #[Test] + public function it_publishes_an_event_via_the_default_publisher(): void + { + $event = new NumbersDivided(12, 3, 4); + + $this->publisher->publish($event); - $this->assertSame([$ev1], $a->published); - $this->assertSame([$ev2], $b->published); - $this->assertSame([$ev3], $c->published); - $this->assertCount(6, $container->logger); + $this->assertSame([], $this->addedPublisher->published); + $this->assertSame([], $this->subtractedPublisher->published); + $this->assertSame([$event], $this->defaultPublisher->published); + $this->assertCount(2, $this->container->logger); } } diff --git a/tests/Integration/Infrastructure/Queue/MathQueueTest.php b/tests/Integration/Infrastructure/Queue/MathQueueTest.php index e0c9a277..514f4003 100644 --- a/tests/Integration/Infrastructure/Queue/MathQueueTest.php +++ b/tests/Integration/Infrastructure/Queue/MathQueueTest.php @@ -22,27 +22,81 @@ final class MathQueueTest extends TestCase { - #[Test] - public function it_queues_commands(): void + private FakeContainer $container; + + private AddCommandEnqueuer $addEnqueuer; + + private MultiplyCommandEnqueuer $multiplyEnqueuer; + + private TestDefaultEnqueuer $defaultEnqueuer; + + private MathQueue $queue; + + protected function setUp(): void { - $a = new AddCommandEnqueuer(); - $b = new MultiplyCommandEnqueuer(); - $c = new TestDefaultEnqueuer(); + parent::setUp(); + + $this->addEnqueuer = $a = new AddCommandEnqueuer(); + $this->multiplyEnqueuer = $b = new MultiplyCommandEnqueuer(); + $this->defaultEnqueuer = $c = new TestDefaultEnqueuer(); - $container = new FakeContainer(); + $this->container = $container = new FakeContainer(); $container->bind(AddCommandEnqueuer::class, fn () => $a); $container->bind(MultiplyCommandEnqueuer::class, fn () => $b); $container->bind(TestDefaultEnqueuer::class, fn () => $c); $container->bind(LogPushedToQueue::class, fn () => new LogPushedToQueue($container->logger)); - $publisher = new MathQueue($container); - $publisher->push($command1 = new AddCommand(1, 2)); - $publisher->push($command2 = new MultiplyCommand(10, 6)); - $publisher->push($command3 = new FloorCommand(99.9)); + $this->queue = new MathQueue($container); + } + + protected function tearDown(): void + { + unset( + $this->container, + $this->addEnqueuer, + $this->multiplyEnqueuer, + $this->defaultEnqueuer, + $this->queue, + ); + parent::tearDown(); + } + + #[Test] + public function it_queues_a_command_via_its_enqueuer(): void + { + $command = new AddCommand(1, 2); + + $this->queue->push($command); + + $this->assertSame([$command], $this->addEnqueuer->queued); + $this->assertSame([], $this->multiplyEnqueuer->queued); + $this->assertSame([], $this->defaultEnqueuer->queued); + $this->assertCount(2, $this->container->logger); + } + + #[Test] + public function it_queues_a_command_via_an_enqueuer_registered_with_a_list_of_commands(): void + { + $command = new MultiplyCommand(10, 6); + + $this->queue->push($command); + + $this->assertSame([], $this->addEnqueuer->queued); + $this->assertSame([$command], $this->multiplyEnqueuer->queued); + $this->assertSame([], $this->defaultEnqueuer->queued); + $this->assertCount(2, $this->container->logger); + } + + #[Test] + public function it_queues_a_command_via_the_default_enqueuer(): void + { + $command = new FloorCommand(99.9); + + $this->queue->push($command); - $this->assertSame([$command1], $a->queued); - $this->assertSame([$command2], $b->queued); - $this->assertSame([$command3], $c->queued); - $this->assertCount(6, $container->logger); + $this->assertSame([], $this->addEnqueuer->queued); + $this->assertSame([], $this->multiplyEnqueuer->queued); + $this->assertSame([$command], $this->defaultEnqueuer->queued); + $this->assertCount(2, $this->container->logger); } } diff --git a/tests/Unit/Application/Bus/AbortOnFailureExceptionTest.php b/tests/Unit/Application/Bus/AbortOnFailureExceptionTest.php new file mode 100644 index 00000000..88d6c814 --- /dev/null +++ b/tests/Unit/Application/Bus/AbortOnFailureExceptionTest.php @@ -0,0 +1,43 @@ +assertInstanceOf(RuntimeException::class, $ex); + $this->assertInstanceOf(FailedResultException::class, $ex); + } + + #[Test] + public function it_returns_the_result(): void + { + $result = Result::failed('Something went wrong.'); + $ex = new AbortOnFailureException($result); + + $actual = $ex->getResult(); + + $this->assertSame($result, $actual); + } +} diff --git a/tests/Unit/Application/Bus/BusExceptionTest.php b/tests/Unit/Application/Bus/BusExceptionTest.php new file mode 100644 index 00000000..92692549 --- /dev/null +++ b/tests/Unit/Application/Bus/BusExceptionTest.php @@ -0,0 +1,32 @@ +assertInstanceOf(RuntimeException::class, $ex); + $this->assertInstanceOf(IBusException::class, $ex); + $this->assertSame('Something went wrong.', $ex->getMessage()); + } +} diff --git a/tests/Unit/Application/Bus/CommandDispatcherTest.php b/tests/Unit/Application/Bus/CommandDispatcherTest.php index f627e487..5a292cb8 100644 --- a/tests/Unit/Application/Bus/CommandDispatcherTest.php +++ b/tests/Unit/Application/Bus/CommandDispatcherTest.php @@ -12,53 +12,37 @@ namespace CloudCreativity\Modules\Tests\Unit\Application\Bus; +use Closure; use CloudCreativity\Modules\Bus\CommandDispatcher; +use CloudCreativity\Modules\Bus\PsrPipeContainer; use CloudCreativity\Modules\Contracts\Bus\CommandHandler; use CloudCreativity\Modules\Contracts\Bus\CommandHandlerContainer; use CloudCreativity\Modules\Contracts\Messaging\Command; -use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use CloudCreativity\Modules\Testing\FakeContainer; use CloudCreativity\Modules\Toolkit\Result\Result; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; final class CommandDispatcherTest extends TestCase { - private CommandHandlerContainer&MockObject $handlers; - - private CommandDispatcher $dispatcher; - /** - * @var array + * @var list */ private array $sequence = []; - protected function setUp(): void - { - parent::setUp(); - - $this->dispatcher = new class ( - handlers: $this->handlers = $this->createMock(CommandHandlerContainer::class), - middleware: $this->createStub(PipeContainer::class), - ) extends CommandDispatcher {}; - } - - protected function tearDown(): void - { - unset($this->handlers, $this->dispatcher, $this->sequence); - parent::tearDown(); - } - #[Test] public function it_dispatches_a_command(): void { $command = $this->createStub(Command::class); + $handler = $this->createMock(CommandHandler::class); + $handlers = $this->createMock(CommandHandlerContainer::class); + $dispatcher = new class ($handlers) extends CommandDispatcher {}; - $this->handlers + $handlers ->expects($this->once()) ->method('get') ->with($command::class) - ->willReturn($handler = $this->createMock(CommandHandler::class)); + ->willReturn($handler); $handler ->expects($this->once()) @@ -66,7 +50,7 @@ public function it_dispatches_a_command(): void ->with($this->identicalTo($command)) ->willReturn($expected = Result::ok()); - $actual = $this->dispatcher->dispatch($command); + $actual = $dispatcher->dispatch($command); $this->assertSame($expected, $actual); } @@ -79,8 +63,9 @@ public function it_dispatches_a_command_through_middleware(): void $command3 = new TestCommand(); $command4 = new TestCommand(); $handler = $this->createMock(CommandHandler::class); + $handlers = $this->createMock(CommandHandlerContainer::class); - $middleware1 = function (TestCommand $command, \Closure $next) use ($command1, $command2) { + $middleware1 = function (TestCommand $command, Closure $next) use ($command1, $command2) { $this->assertSame($command1, $command); $this->sequence[] = 'before1'; $result = $next($command2); @@ -88,7 +73,7 @@ public function it_dispatches_a_command_through_middleware(): void return $result; }; - $middleware2 = function (TestCommand $command, \Closure $next) use ($command2, $command3) { + $middleware2 = function (TestCommand $command, Closure $next) use ($command2, $command3) { $this->assertSame($command2, $command); $this->sequence[] = 'before2'; $result = $next($command3); @@ -96,7 +81,7 @@ public function it_dispatches_a_command_through_middleware(): void return $result; }; - $middleware3 = function (TestCommand $command, \Closure $next) use ($command3, $command4) { + $middleware3 = function (TestCommand $command, Closure $next) use ($command3, $command4) { $this->assertSame($command3, $command); $this->sequence[] = 'before3'; $result = $next($command4); @@ -104,7 +89,14 @@ public function it_dispatches_a_command_through_middleware(): void return $result; }; - $this->handlers + $middleware = new PsrPipeContainer(); + $middleware->bind('MyFirstMiddleware', fn () => $middleware1); + $middleware->bind('MySecondMiddleware', fn () => $middleware2); + + $dispatcher = new class ($handlers, $middleware) extends CommandDispatcher {}; + $dispatcher->through(['MyFirstMiddleware']); + + $handlers ->expects($this->once()) ->method('get') ->with($command1::class) @@ -113,21 +105,6 @@ public function it_dispatches_a_command_through_middleware(): void return $handler; }); - $middleware = $this->createMock(PipeContainer::class); - $this->dispatcher = new class ( - handlers: $this->handlers, - middleware: $middleware, - ) extends CommandDispatcher {}; - - $middleware - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'MyFirstMiddleware' => $middleware1, - 'MySecondMiddleware' => $middleware2, - default => $this->fail('Unexpected middleware: ' . $name), - }); - $handler ->expects($this->once()) ->method('middleware') @@ -139,8 +116,7 @@ public function it_dispatches_a_command_through_middleware(): void ->with($this->identicalTo($command4)) ->willReturn($expected = Result::ok()); - $this->dispatcher->through(['MyFirstMiddleware']); - $actual = $this->dispatcher->dispatch($command1); + $actual = $dispatcher->dispatch($command1); $this->assertSame($expected, $actual); $this->assertSame([ @@ -152,4 +128,68 @@ public function it_dispatches_a_command_through_middleware(): void 'after1', ], $this->sequence); } + + #[Test] + public function it_autowires_handlers_and_middleware_from_a_psr_container(): void + { + $command = new TestCommand(); + $expected = Result::ok(); + $handler = $this->createMock(TestCommandHandler::class); + $container = new FakeContainer(); + $container->instance(TestCommandHandler::class, $handler); + $container->instance('Middleware1', function (TestCommand $actual, Closure $next) { + $this->sequence[] = 'Middleware1'; + return $next($actual); + }); + $dispatcher = new TestCommandDispatcherWithAttributes($container); + + $handler + ->expects($this->once()) + ->method('execute') + ->with($this->identicalTo($command)) + ->willReturnCallback(function () use ($expected) { + $this->sequence[] = 'handler'; + return $expected; + }); + + $actual = $dispatcher->dispatch($command); + + $this->assertSame($expected, $actual); + $this->assertSame(['Middleware1', 'handler'], $this->sequence); + } + + #[Test] + public function it_autowires_middleware_but_not_handlers_with_a_custom_handler_container(): void + { + $command = new TestCommand(); + $expected = Result::ok(); + $middleware = new PsrPipeContainer(); + $middleware->bind('Middleware1', fn () => function (TestCommand $actual, Closure $next) { + $this->sequence[] = 'Middleware1'; + return $next($actual); + }); + $handler = $this->createMock(CommandHandler::class); + $handlers = $this->createMock(CommandHandlerContainer::class); + $dispatcher = new TestCommandDispatcherWithAttributes($handlers, $middleware); + + $handlers + ->expects($this->once()) + ->method('get') + ->with(TestCommand::class) + ->willReturn($handler); + + $handler + ->expects($this->once()) + ->method('__invoke') + ->with($this->identicalTo($command)) + ->willReturnCallback(function () use ($expected) { + $this->sequence[] = 'handler'; + return $expected; + }); + + $actual = $dispatcher->dispatch($command); + + $this->assertSame($expected, $actual); + $this->assertSame(['Middleware1', 'handler'], $this->sequence); + } } diff --git a/tests/Unit/Application/Bus/CommandHandlerContainerTest.php b/tests/Unit/Application/Bus/CommandHandlerContainerTest.php index c024c998..a17cd65b 100644 --- a/tests/Unit/Application/Bus/CommandHandlerContainerTest.php +++ b/tests/Unit/Application/Bus/CommandHandlerContainerTest.php @@ -16,9 +16,9 @@ use CloudCreativity\Modules\Bus\CommandHandler; use CloudCreativity\Modules\Bus\CommandHandlerContainer; use CloudCreativity\Modules\Contracts\Messaging\Command; +use CloudCreativity\Modules\Testing\FakeContainer; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; final class CommandHandlerContainerTest extends TestCase { @@ -30,7 +30,6 @@ public function it_resolves_using_closure_bindings(): void $command1 = new class () implements Command {}; $command2 = new class () implements Command {}; - $command3 = new class () implements Command {}; $container = new CommandHandlerContainer(); $container->bind($command1::class, fn () => $a); @@ -38,11 +37,21 @@ public function it_resolves_using_closure_bindings(): void $this->assertEquals(new CommandHandler($a), $container->get($command1::class)); $this->assertEquals(new CommandHandler($b), $container->get($command2::class)); + } + + #[Test] + public function it_throws_when_no_closure_binding_exists_for_the_command(): void + { + $command1 = new class () implements Command {}; + $command2 = new class () implements Command {}; + + $container = new CommandHandlerContainer(); + $container->bind($command1::class, fn () => new class () extends TestCommandHandler {}); $this->expectException(BusException::class); - $this->expectExceptionMessage('No command handler bound for command class: ' . $command3::class); + $this->expectExceptionMessage('No command handler bound for command class: ' . $command2::class); - $container->get($command3::class); + $container->get($command2::class); } #[Test] @@ -53,17 +62,10 @@ public function it_resolves_via_psr_container(): void $command1 = new class () implements Command {}; $command2 = new class () implements Command {}; - $command3 = new class () implements Command {}; - - $psrContainer = $this->createMock(ContainerInterface::class); - $psrContainer - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $id) => match ($id) { - $a::class => $a, - $b::class => $b, - default => $this->fail('Unexpected container id: ' . $id), - }); + + $psrContainer = new FakeContainer(); + $psrContainer->instance($a::class, $a); + $psrContainer->instance($b::class, $b); $container = new CommandHandlerContainer($psrContainer); $container->bind($command1::class, $a::class); @@ -71,10 +73,34 @@ public function it_resolves_via_psr_container(): void $this->assertEquals(new CommandHandler($a), $container->get($command1::class)); $this->assertEquals(new CommandHandler($b), $container->get($command2::class)); + } + + #[Test] + public function it_throws_when_no_psr_container_binding_exists_for_the_command(): void + { + $command1 = new class () implements Command {}; + $command2 = new class () implements Command {}; + + $psrContainer = new FakeContainer(); + $psrContainer->instance(TestCommandHandler::class, new class () extends TestCommandHandler {}); + + $container = new CommandHandlerContainer($psrContainer); + $container->bind($command1::class, TestCommandHandler::class); + + $this->expectException(BusException::class); + $this->expectExceptionMessage('No command handler bound for command class: ' . $command2::class); + + $container->get($command2::class); + } + + #[Test] + public function it_throws_when_binding_a_string_without_a_psr_container(): void + { + $container = new CommandHandlerContainer(); $this->expectException(BusException::class); - $this->expectExceptionMessage('No command handler bound for command class: ' . $command3::class); + $this->expectExceptionMessage('Cannot use a string command handler binding without a PSR container.'); - $container->get($command3::class); + $container->bind(TestCommand::class, TestCommandHandler::class); } } diff --git a/tests/Unit/Application/Bus/CommandHandlerTest.php b/tests/Unit/Application/Bus/CommandHandlerTest.php index 96443c4c..f63cbf56 100644 --- a/tests/Unit/Application/Bus/CommandHandlerTest.php +++ b/tests/Unit/Application/Bus/CommandHandlerTest.php @@ -20,40 +20,52 @@ final class CommandHandlerTest extends TestCase { #[Test] - public function it_executes_the_command_and_returns_its_middleware(): void + public function it_executes_the_command(): void { $command = new TestCommand(); - $innerHandler = $this->createMock(TestCommandHandler::class); + $handler = new CommandHandler($innerHandler); + $innerHandler ->expects($this->once()) ->method('execute') ->with($this->identicalTo($command)) ->willReturn($expected = Result::ok()); - $innerHandler - ->expects($this->once()) - ->method('middleware') - ->willReturn($middleware = ['Middleware1', 'Middleware2']); + $actual = $handler($command); + $this->assertSame($expected, $actual); + } + + #[Test] + public function it_returns_the_middleware_of_the_inner_handler(): void + { + $innerHandler = $this->createStub(TestCommandHandler::class); + $innerHandler->method('middleware')->willReturn(['Middleware1', 'Middleware2']); $handler = new CommandHandler($innerHandler); - $this->assertSame($expected, $handler($command)); - $this->assertSame($middleware, $handler->middleware()); + $actual = $handler->middleware(); + + $this->assertSame(['Middleware1', 'Middleware2'], $actual); } #[Test] - public function it_does_not_have_execute_method(): void + public function it_returns_middleware_from_the_through_attribute(): void { - $handler = new CommandHandler(new \DateTime()); - $command = new TestCommand(); - $commandClass = $command::class; + $handler = new CommandHandler(new TestCommandHandlerWithThrough()); + + $actual = $handler->middleware(); + + $this->assertSame(['Middleware1', 'Middleware2'], $actual); + } + + #[Test] + public function it_returns_no_middleware_when_none_is_declared(): void + { + $handler = new CommandHandler(new \stdClass()); - $this->expectException(\AssertionError::class); - $this->expectExceptionMessage( - "Cannot dispatch \"{$commandClass}\" - handler \"DateTime\" does not have an execute method.", - ); + $actual = $handler->middleware(); - $handler($command); + $this->assertSame([], $actual); } } diff --git a/tests/Unit/Application/Bus/CommandQueuerTest.php b/tests/Unit/Application/Bus/CommandQueuerTest.php index 95897241..18eb7bc2 100644 --- a/tests/Unit/Application/Bus/CommandQueuerTest.php +++ b/tests/Unit/Application/Bus/CommandQueuerTest.php @@ -13,14 +13,13 @@ namespace CloudCreativity\Modules\Tests\Unit\Application\Bus; use CloudCreativity\Modules\Application\Bus\CommandQueuer; -use CloudCreativity\Modules\Contracts\Application\Ports\Queue; +use CloudCreativity\Modules\Testing\FakeQueue; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; final class CommandQueuerTest extends TestCase { - private MockObject&Queue $queue; + private FakeQueue $queue; private CommandQueuer $queuer; @@ -29,7 +28,7 @@ protected function setUp(): void parent::setUp(); $this->queuer = new class ( - $this->queue = $this->createMock(Queue::class), + $this->queue = new class () extends FakeQueue {}, ) extends CommandQueuer {}; } @@ -42,11 +41,10 @@ protected function tearDown(): void #[Test] public function it_queues_the_command(): void { - $this->queue - ->expects($this->once()) - ->method('push') - ->with($this->identicalTo($command = new TestCommand())); + $command = new TestCommand(); $this->queuer->queue($command); + + $this->assertSame([$command], $this->queue->commands); } } diff --git a/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php b/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php index e4985473..b9bd8b64 100644 --- a/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php +++ b/tests/Unit/Application/Bus/Middleware/FlushDeferredEventsTest.php @@ -96,10 +96,10 @@ public function it_forgets_deferred_events_on_failed_result(): void return $expected; }); + $this->assertSame($expected, $actual); $this->assertSame(['next', 'forget'], $this->sequence); } - #[Test] public function it_forgets_deferred_events_on_exception(): void { @@ -117,17 +117,19 @@ public function it_forgets_deferred_events_on_exception(): void ->expects($this->never()) ->method('flush'); + $actual = null; + try { ($this->middleware)($command, function ($in) use ($command, $expected) { $this->assertSame($command, $in); $this->sequence[] = 'next'; throw $expected; }); - $this->fail('No exception thrown.'); } catch (\LogicException $ex) { - $this->assertSame($expected, $ex); + $actual = $ex; } + $this->assertSame($expected, $actual); $this->assertSame(['next', 'forget'], $this->sequence); } } diff --git a/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php b/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php index 4261fea9..047a1f71 100644 --- a/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php +++ b/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php @@ -15,45 +15,34 @@ use CloudCreativity\Modules\Bus\Middleware\LogMessageDispatch; use CloudCreativity\Modules\Bus\SanitizedMessage; use CloudCreativity\Modules\Contracts\Messaging\Command; +use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; use CloudCreativity\Modules\Contracts\Messaging\Message; use CloudCreativity\Modules\Contracts\Messaging\Query; +use CloudCreativity\Modules\Testing\FakeLogger; +use CloudCreativity\Modules\Tests\Unit\Application\Bus\TestCommand; use CloudCreativity\Modules\Toolkit\Result\Result; use LogicException; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; final class LogMessageDispatchTest extends TestCase { - private LoggerInterface&Stub $logger; + private FakeLogger $logger; private Command $message; - /** - * @var array - */ - private array $logs = []; - protected function setUp(): void { parent::setUp(); - $this->logger = $this->createStub(LoggerInterface::class); - $this->logger - ->method('log') - ->willReturnCallback(function ($level, $message, $context): bool { - $this->logs[] = [$level, $message, $context]; - return true; - }); - + $this->logger = new FakeLogger(); $this->message = new class () implements Command {}; } protected function tearDown(): void { - unset($this->logger, $this->message, $this->logs); + unset($this->logger, $this->message); parent::tearDown(); } @@ -62,8 +51,8 @@ public function it_logs_with_the_default_levels(): void { $expected = Result::ok(); $name = $this->message::class; - $middleware = new LogMessageDispatch($this->logger); + $actual = $middleware($this->message, function (Message $received) use ($expected) { $this->assertSame($this->message, $received); return $expected; @@ -71,9 +60,17 @@ public function it_logs_with_the_default_levels(): void $this->assertSame($expected, $actual); $this->assertEquals([ - [LogLevel::DEBUG, "Bus dispatching {$name}.", ['command' => new SanitizedMessage($this->message)->context()]], - [LogLevel::INFO, "Bus dispatched {$name}.", ['result' => $expected->context()]], - ], $this->logs); + [ + 'level' => LogLevel::DEBUG, + 'message' => "Bus dispatching {$name}.", + 'context' => ['command' => new SanitizedMessage($this->message)->context()], + ], + [ + 'level' => LogLevel::INFO, + 'message' => "Bus dispatched {$name}.", + 'context' => ['result' => $expected->context()], + ], + ], $this->logger->log); } #[Test] @@ -81,8 +78,8 @@ public function it_logs_with_custom_levels(): void { $expected = Result::failed('Something went wrong.'); $name = $this->message::class; - $middleware = new LogMessageDispatch($this->logger, LogLevel::NOTICE, LogLevel::WARNING); + $actual = $middleware($this->message, function (Message $received) use ($expected) { $this->assertSame($this->message, $received); return $expected; @@ -90,9 +87,17 @@ public function it_logs_with_custom_levels(): void $this->assertSame($expected, $actual); $this->assertEquals([ - [LogLevel::NOTICE, "Bus dispatching {$name}.", ['command' => new SanitizedMessage($this->message)->context()]], - [LogLevel::WARNING, "Bus dispatched {$name}.", ['result' => $expected->context()]], - ], $this->logs); + [ + 'level' => LogLevel::NOTICE, + 'message' => "Bus dispatching {$name}.", + 'context' => ['command' => new SanitizedMessage($this->message)->context()], + ], + [ + 'level' => LogLevel::WARNING, + 'message' => "Bus dispatched {$name}.", + 'context' => ['result' => $expected->context()], + ], + ], $this->logger->log); } #[Test] @@ -102,17 +107,86 @@ public function it_logs_after_the_next_closure_is_invoked(): void $message = $this->createStub(Query::class); $name = $message::class; $middleware = new LogMessageDispatch($this->logger); + $actual = null; try { $middleware($message, static function () use ($expected) { throw $expected; }); - $this->fail('No exception thrown.'); } catch (LogicException $ex) { - $this->assertSame($expected, $ex); - $this->assertEquals([ - [LogLevel::DEBUG, "Bus dispatching {$name}.", ['query' => new SanitizedMessage($message)->context()]], - ], $this->logs); + $actual = $ex; } + + $this->assertSame($expected, $actual); + $this->assertEquals([ + [ + 'level' => LogLevel::DEBUG, + 'message' => "Bus dispatching {$name}.", + 'context' => ['query' => new SanitizedMessage($message)->context()], + ], + ], $this->logger->log); + } + + #[Test] + public function it_logs_an_integration_event(): void + { + $event = $this->createStub(IntegrationEvent::class); + $name = $event::class; + $middleware = new LogMessageDispatch($this->logger); + + $actual = $middleware($event, fn () => null); + + $this->assertNull($actual); + $this->assertEquals([ + [ + 'level' => LogLevel::DEBUG, + 'message' => "Bus dispatching {$name}.", + 'context' => ['event' => new SanitizedMessage($event)->context()], + ], + ['level' => LogLevel::INFO, 'message' => "Bus dispatched {$name}.", 'context' => []], + ], $this->logger->log); + } + + #[Test] + public function it_logs_a_message_that_is_not_a_command_query_or_event(): void + { + $message = $this->createStub(Message::class); + $expected = Result::ok(); + $name = $message::class; + $middleware = new LogMessageDispatch($this->logger); + + $actual = $middleware($message, fn () => $expected); + + $this->assertSame($expected, $actual); + $this->assertEquals([ + [ + 'level' => LogLevel::DEBUG, + 'message' => "Bus dispatching {$name}.", + 'context' => ['message' => new SanitizedMessage($message)->context()], + ], + [ + 'level' => LogLevel::INFO, + 'message' => "Bus dispatched {$name}.", + 'context' => ['result' => $expected->context()], + ], + ], $this->logger->log); + } + + #[Test] + public function it_logs_the_module_basename_and_sanitized_message(): void + { + $command = new TestCommand(fail: true); + $middleware = new LogMessageDispatch($this->logger); + + $middleware($command, fn () => null); + + $this->assertSame([ + [ + 'level' => LogLevel::DEBUG, + 'message' => 'Bus dispatching Tests:TestCommand.', + 'context' => ['command' => ['fail' => true]], + ], + ['level' => LogLevel::INFO, 'message' => 'Bus dispatched Tests:TestCommand.', 'context' => []], + ], $this->logger->log); } } diff --git a/tests/Unit/Application/Bus/Middleware/TestValidateMessageWithRules.php b/tests/Unit/Application/Bus/Middleware/TestValidateMessageWithRules.php new file mode 100644 index 00000000..aaf9e86b --- /dev/null +++ b/tests/Unit/Application/Bus/Middleware/TestValidateMessageWithRules.php @@ -0,0 +1,21 @@ +createStub(Command::class); $expected = Result::ok(); + $next = function ($actual) use ($command, $expected) { + $this->assertSame($command, $actual); + return $expected; + }; + $this->validator ->expects($this->once()) ->method('using') @@ -88,11 +90,6 @@ public function it_succeeds(): void })) ->willReturn(new ListOfErrors()); - $next = function ($actual) use ($command, $expected) { - $this->assertSame($command, $actual); - return $expected; - }; - $actual = ($this->middleware)($command, $next); $this->assertSame($expected, $actual); @@ -101,6 +98,13 @@ public function it_succeeds(): void #[Test] public function it_fails(): void { + $command = $this->createStub(Query::class); + $errors = new ListOfErrors(new Error(null, 'Something went wrong.')); + + $next = function () { + throw new \LogicException('Not expecting next closure to be called.'); + }; + $this->validator ->expects($this->once()) ->method('using') @@ -115,23 +119,20 @@ public function it_fails(): void $this->validator ->expects($this->once()) ->method('validate') - ->with($command = $this->createStub(Query::class)) - ->willReturn($errors = new ListOfErrors(new Error(null, 'Something went wrong.'))); + ->with($this->identicalTo($command)) + ->willReturn($errors); - $next = function () { - throw new \LogicException('Not expecting next closure to be called.'); - }; - - $result = ($this->middleware)($command, $next); + $actual = ($this->middleware)($command, $next); - $this->assertTrue($result?->didFail()); - $this->assertSame($errors, $result->errors()); + $this->assertEquals(Result::failed($errors), $actual); } #[Test] public function it_stops_on_first_failure_via_bail(): void { - $this->middleware = new class ($this->validator) extends ValidateMessage implements Bail { + $command = $this->createStub(Message::class); + $errors = new ListOfErrors(new Error(null, 'Something went wrong.')); + $middleware = new class ($this->validator) extends ValidateMessage implements Bail { /** * @return iterable */ @@ -141,6 +142,10 @@ protected function rules(): iterable } }; + $next = function () { + throw new \LogicException('Not expecting next closure to be called.'); + }; + $this->validator ->expects($this->once()) ->method('using') @@ -155,25 +160,20 @@ protected function rules(): iterable $this->validator ->expects($this->once()) ->method('validate') - ->with($command = $this->createStub(Message::class)) - ->willReturn($errors = new ListOfErrors(new Error(null, 'Something went wrong.'))); - - $next = function () { - throw new \LogicException('Not expecting next closure to be called.'); - }; + ->with($this->identicalTo($command)) + ->willReturn($errors); - $result = ($this->middleware)($command, $next); + $actual = $middleware($command, $next); - $this->assertTrue($result?->didFail()); - $this->assertSame($errors, $result->errors()); + $this->assertEquals(Result::failed($errors), $actual); } #[Test] public function it_stops_on_first_failure(): void { $command = $this->createStub(Command::class); - - $this->middleware = new class ($command, $this->validator) extends ValidateMessage { + $errors = new ListOfErrors(new Error(null, 'Something went wrong.')); + $middleware = new class ($command, $this->validator) extends ValidateMessage { public function __construct(private Message $message, Validator $validator) { parent::__construct($validator); @@ -193,6 +193,10 @@ protected function stopOnFirstFailure(Message $message): bool } }; + $next = function () { + throw new \LogicException('Not expecting next closure to be called.'); + }; + $this->validator ->expects($this->once()) ->method('using') @@ -207,16 +211,73 @@ protected function stopOnFirstFailure(Message $message): bool $this->validator ->expects($this->once()) ->method('validate') - ->with($command) - ->willReturn($errors = new ListOfErrors(new Error(null, 'Something went wrong.'))); + ->with($this->identicalTo($command)) + ->willReturn($errors); - $next = function () { - throw new \LogicException('Not expecting next closure to be called.'); - }; + $actual = $middleware($command, $next); + + $this->assertEquals(Result::failed($errors), $actual); + } - $result = ($this->middleware)($command, $next); + #[Test] + public function it_uses_rules_from_the_with_rules_attribute(): void + { + $command = $this->createStub(Command::class); + $expected = Result::ok(); + $middleware = new TestValidateMessageWithRules($this->validator); - $this->assertTrue($result?->didFail()); - $this->assertSame($errors, $result->errors()); + $this->validator + ->expects($this->once()) + ->method('using') + ->with($this->callback( + fn (iterable $rules): bool => ['Rule1', 'Rule2'] === iterator_to_array($rules, false), + )) + ->willReturnSelf(); + + $this->validator + ->expects($this->once()) + ->method('stopOnFirstFailure') + ->with(false) + ->willReturnSelf(); + + $this->validator + ->expects($this->once()) + ->method('validate') + ->with($this->identicalTo($command)) + ->willReturn(new ListOfErrors()); + + $actual = $middleware($command, fn () => $expected); + + $this->assertSame($expected, $actual); + } + + #[Test] + public function it_has_no_rules_by_default(): void + { + $command = $this->createStub(Command::class); + $expected = Result::ok(); + $middleware = new class ($this->validator) extends ValidateMessage {}; + + $this->validator + ->expects($this->once()) + ->method('using') + ->with($this->callback(fn (iterable $rules): bool => [] === iterator_to_array($rules, false))) + ->willReturnSelf(); + + $this->validator + ->expects($this->once()) + ->method('stopOnFirstFailure') + ->with(false) + ->willReturnSelf(); + + $this->validator + ->expects($this->once()) + ->method('validate') + ->with($this->identicalTo($command)) + ->willReturn(new ListOfErrors()); + + $actual = $middleware($command, fn () => $expected); + + $this->assertSame($expected, $actual); } } diff --git a/tests/Unit/Application/Bus/QueryDispatcherTest.php b/tests/Unit/Application/Bus/QueryDispatcherTest.php index 7cd81b41..7a3571ad 100644 --- a/tests/Unit/Application/Bus/QueryDispatcherTest.php +++ b/tests/Unit/Application/Bus/QueryDispatcherTest.php @@ -12,56 +12,37 @@ namespace CloudCreativity\Modules\Tests\Unit\Application\Bus; +use Closure; use CloudCreativity\Modules\Bus\QueryDispatcher; +use CloudCreativity\Modules\Bus\PsrPipeContainer; use CloudCreativity\Modules\Contracts\Bus\QueryHandler; use CloudCreativity\Modules\Contracts\Bus\QueryHandlerContainer; use CloudCreativity\Modules\Contracts\Messaging\Query; -use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use CloudCreativity\Modules\Testing\FakeContainer; use CloudCreativity\Modules\Toolkit\Result\Result; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; final class QueryDispatcherTest extends TestCase { /** - * @var MockObject&QueryHandlerContainer - */ - private QueryHandlerContainer $handlers; - - private QueryDispatcher $dispatcher; - - /** - * @var array + * @var list */ private array $sequence = []; - protected function setUp(): void - { - parent::setUp(); - - $this->dispatcher = new class ( - handlers: $this->handlers = $this->createMock(QueryHandlerContainer::class), - middleware: $this->createStub(PipeContainer::class), - ) extends QueryDispatcher {}; - } - - protected function tearDown(): void - { - unset($this->handlers, $this->dispatcher, $this->sequence); - parent::tearDown(); - } - #[Test] public function it_dispatches_a_query(): void { $query = $this->createStub(Query::class); + $handler = $this->createMock(QueryHandler::class); + $handlers = $this->createMock(QueryHandlerContainer::class); + $dispatcher = new class ($handlers) extends QueryDispatcher {}; - $this->handlers + $handlers ->expects($this->once()) ->method('get') ->with($query::class) - ->willReturn($handler = $this->createMock(QueryHandler::class)); + ->willReturn($handler); $handler ->expects($this->once()) @@ -69,7 +50,7 @@ public function it_dispatches_a_query(): void ->with($this->identicalTo($query)) ->willReturn($expected = Result::ok()); - $actual = $this->dispatcher->dispatch($query); + $actual = $dispatcher->dispatch($query); $this->assertSame($expected, $actual); } @@ -82,55 +63,48 @@ public function it_dispatches_a_query_through_middleware(): void $query3 = new TestQuery(); $query4 = new TestQuery(); $handler = $this->createMock(QueryHandler::class); + $handlers = $this->createMock(QueryHandlerContainer::class); - $middleware1 = function (TestQuery $q, \Closure $next) use ($query1, $query2) { - $this->assertSame($query1, $q); + $middleware1 = function (TestQuery $query, Closure $next) use ($query1, $query2) { + $this->assertSame($query1, $query); $this->sequence[] = 'before1'; $result = $next($query2); $this->sequence[] = 'after1'; return $result; }; - $middleware2 = function (TestQuery $q, \Closure $next) use ($query2, $query3) { - $this->assertSame($query2, $q); + $middleware2 = function (TestQuery $query, Closure $next) use ($query2, $query3) { + $this->assertSame($query2, $query); $this->sequence[] = 'before2'; $result = $next($query3); $this->sequence[] = 'after2'; return $result; }; - $middleware3 = function (TestQuery $q, \Closure $next) use ($query3, $query4) { - $this->assertSame($query3, $q); + $middleware3 = function (TestQuery $query, Closure $next) use ($query3, $query4) { + $this->assertSame($query3, $query); $this->sequence[] = 'before3'; $result = $next($query4); $this->sequence[] = 'after3'; return $result; }; - $this->handlers + $middleware = new PsrPipeContainer(); + $middleware->bind('MyFirstMiddleware', fn () => $middleware1); + $middleware->bind('MySecondMiddleware', fn () => $middleware2); + + $dispatcher = new class ($handlers, $middleware) extends QueryDispatcher {}; + $dispatcher->through(['MyFirstMiddleware']); + + $handlers ->expects($this->once()) ->method('get') - ->with(TestQuery::class) + ->with($query1::class) ->willReturnCallback(function () use ($handler) { $this->assertSame(['before1'], $this->sequence); return $handler; }); - $middleware = $this->createMock(PipeContainer::class); - $this->dispatcher = new class ( - handlers: $this->handlers, - middleware: $middleware, - ) extends QueryDispatcher {}; - - $middleware - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'MyFirstMiddleware' => $middleware1, - 'MySecondMiddleware' => $middleware2, - default => $this->fail('Unexpected middleware: ' . $name), - }); - $handler ->expects($this->once()) ->method('middleware') @@ -142,8 +116,7 @@ public function it_dispatches_a_query_through_middleware(): void ->with($this->identicalTo($query4)) ->willReturn($expected = Result::ok()); - $this->dispatcher->through(['MyFirstMiddleware']); - $actual = $this->dispatcher->dispatch($query1); + $actual = $dispatcher->dispatch($query1); $this->assertSame($expected, $actual); $this->assertSame([ @@ -155,4 +128,68 @@ public function it_dispatches_a_query_through_middleware(): void 'after1', ], $this->sequence); } + + #[Test] + public function it_autowires_handlers_and_middleware_from_a_psr_container(): void + { + $query = new TestQuery(); + $expected = Result::ok(); + $handler = $this->createMock(TestQueryHandler::class); + $container = new FakeContainer(); + $container->instance(TestQueryHandler::class, $handler); + $container->instance('Middleware1', function (TestQuery $actual, Closure $next) { + $this->sequence[] = 'Middleware1'; + return $next($actual); + }); + $dispatcher = new TestQueryDispatcherWithAttributes($container); + + $handler + ->expects($this->once()) + ->method('execute') + ->with($this->identicalTo($query)) + ->willReturnCallback(function () use ($expected) { + $this->sequence[] = 'handler'; + return $expected; + }); + + $actual = $dispatcher->dispatch($query); + + $this->assertSame($expected, $actual); + $this->assertSame(['Middleware1', 'handler'], $this->sequence); + } + + #[Test] + public function it_autowires_middleware_but_not_handlers_with_a_custom_handler_container(): void + { + $query = new TestQuery(); + $expected = Result::ok(); + $middleware = new PsrPipeContainer(); + $middleware->bind('Middleware1', fn () => function (TestQuery $actual, Closure $next) { + $this->sequence[] = 'Middleware1'; + return $next($actual); + }); + $handler = $this->createMock(QueryHandler::class); + $handlers = $this->createMock(QueryHandlerContainer::class); + $dispatcher = new TestQueryDispatcherWithAttributes($handlers, $middleware); + + $handlers + ->expects($this->once()) + ->method('get') + ->with(TestQuery::class) + ->willReturn($handler); + + $handler + ->expects($this->once()) + ->method('__invoke') + ->with($this->identicalTo($query)) + ->willReturnCallback(function () use ($expected) { + $this->sequence[] = 'handler'; + return $expected; + }); + + $actual = $dispatcher->dispatch($query); + + $this->assertSame($expected, $actual); + $this->assertSame(['Middleware1', 'handler'], $this->sequence); + } } diff --git a/tests/Unit/Application/Bus/QueryHandlerContainerTest.php b/tests/Unit/Application/Bus/QueryHandlerContainerTest.php index 3a040dae..0e2b5506 100644 --- a/tests/Unit/Application/Bus/QueryHandlerContainerTest.php +++ b/tests/Unit/Application/Bus/QueryHandlerContainerTest.php @@ -16,21 +16,20 @@ use CloudCreativity\Modules\Bus\QueryHandler; use CloudCreativity\Modules\Bus\QueryHandlerContainer; use CloudCreativity\Modules\Contracts\Messaging\Query; +use CloudCreativity\Modules\Testing\FakeContainer; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; final class QueryHandlerContainerTest extends TestCase { #[Test] - public function it_resolves_closure_bindings(): void + public function it_resolves_using_closure_bindings(): void { $a = new class () extends TestQueryHandler {}; $b = $this->createStub(TestQueryHandler::class); $query1 = new class () implements Query {}; $query2 = new class () implements Query {}; - $query3 = new class () implements Query {}; $container = new QueryHandlerContainer(); $container->bind($query1::class, fn () => $a); @@ -38,11 +37,21 @@ public function it_resolves_closure_bindings(): void $this->assertEquals(new QueryHandler($a), $container->get($query1::class)); $this->assertEquals(new QueryHandler($b), $container->get($query2::class)); + } + + #[Test] + public function it_throws_when_no_closure_binding_exists_for_the_query(): void + { + $query1 = new class () implements Query {}; + $query2 = new class () implements Query {}; + + $container = new QueryHandlerContainer(); + $container->bind($query1::class, fn () => new class () extends TestQueryHandler {}); $this->expectException(BusException::class); - $this->expectExceptionMessage('No query handler bound for query class: ' . $query3::class); + $this->expectExceptionMessage('No query handler bound for query class: ' . $query2::class); - $container->get($query3::class); + $container->get($query2::class); } #[Test] @@ -53,17 +62,10 @@ public function it_resolves_via_psr_container(): void $query1 = new class () implements Query {}; $query2 = new class () implements Query {}; - $query3 = new class () implements Query {}; - - $psrContainer = $this->createMock(ContainerInterface::class); - $psrContainer - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $id) => match ($id) { - $a::class => $a, - $b::class => $b, - default => $this->fail('Unexpected container id: ' . $id), - }); + + $psrContainer = new FakeContainer(); + $psrContainer->instance($a::class, $a); + $psrContainer->instance($b::class, $b); $container = new QueryHandlerContainer($psrContainer); $container->bind($query1::class, $a::class); @@ -71,10 +73,34 @@ public function it_resolves_via_psr_container(): void $this->assertEquals(new QueryHandler($a), $container->get($query1::class)); $this->assertEquals(new QueryHandler($b), $container->get($query2::class)); + } + + #[Test] + public function it_throws_when_no_psr_container_binding_exists_for_the_query(): void + { + $query1 = new class () implements Query {}; + $query2 = new class () implements Query {}; + + $psrContainer = new FakeContainer(); + $psrContainer->instance(TestQueryHandler::class, new class () extends TestQueryHandler {}); + + $container = new QueryHandlerContainer($psrContainer); + $container->bind($query1::class, TestQueryHandler::class); + + $this->expectException(BusException::class); + $this->expectExceptionMessage('No query handler bound for query class: ' . $query2::class); + + $container->get($query2::class); + } + + #[Test] + public function it_throws_when_binding_a_string_without_a_psr_container(): void + { + $container = new QueryHandlerContainer(); $this->expectException(BusException::class); - $this->expectExceptionMessage('No query handler bound for query class: ' . $query3::class); + $this->expectExceptionMessage('Cannot use a string query handler binding without a PSR container.'); - $container->get($query3::class); + $container->bind(TestQuery::class, TestQueryHandler::class); } } diff --git a/tests/Unit/Application/Bus/QueryHandlerTest.php b/tests/Unit/Application/Bus/QueryHandlerTest.php index 0f1120ad..b196a435 100644 --- a/tests/Unit/Application/Bus/QueryHandlerTest.php +++ b/tests/Unit/Application/Bus/QueryHandlerTest.php @@ -20,40 +20,52 @@ final class QueryHandlerTest extends TestCase { #[Test] - public function it_executes_the_query_and_returns_its_middleware(): void + public function it_executes_the_query(): void { $query = new TestQuery(); - $innerHandler = $this->createMock(TestQueryHandler::class); + $handler = new QueryHandler($innerHandler); + $innerHandler ->expects($this->once()) ->method('execute') ->with($this->identicalTo($query)) ->willReturn($expected = Result::ok()); - $innerHandler - ->expects($this->once()) - ->method('middleware') - ->willReturn($middleware = ['Middleware1', 'Middleware2']); + $actual = $handler($query); + $this->assertSame($expected, $actual); + } + + #[Test] + public function it_returns_the_middleware_of_the_inner_handler(): void + { + $innerHandler = $this->createStub(TestQueryHandler::class); + $innerHandler->method('middleware')->willReturn(['Middleware1', 'Middleware2']); $handler = new QueryHandler($innerHandler); - $this->assertSame($expected, $handler($query)); - $this->assertSame($middleware, $handler->middleware()); + $actual = $handler->middleware(); + + $this->assertSame(['Middleware1', 'Middleware2'], $actual); } #[Test] - public function it_does_not_have_execute_method(): void + public function it_returns_middleware_from_the_through_attribute(): void { - $handler = new QueryHandler(new \DateTime()); - $query = new TestQuery(); - $queryClass = $query::class; + $handler = new QueryHandler(new TestQueryHandlerWithThrough()); + + $actual = $handler->middleware(); + + $this->assertSame(['Middleware1', 'Middleware2'], $actual); + } + + #[Test] + public function it_returns_no_middleware_when_none_is_declared(): void + { + $handler = new QueryHandler(new \stdClass()); - $this->expectException(\AssertionError::class); - $this->expectExceptionMessage( - "Cannot dispatch \"{$queryClass}\" - handler \"DateTime\" does not have an execute method.", - ); + $actual = $handler->middleware(); - $handler($query); + $this->assertSame([], $actual); } } diff --git a/tests/Unit/Application/Bus/SanitizedMessageTest.php b/tests/Unit/Application/Bus/SanitizedMessageTest.php new file mode 100644 index 00000000..72761cb4 --- /dev/null +++ b/tests/Unit/Application/Bus/SanitizedMessageTest.php @@ -0,0 +1,54 @@ + $value) { + $actual[$key] = $value; + } + + $this->assertSame(['name' => 'Bob', 'age' => 42], $actual); + } + + #[Test] + public function it_returns_public_properties_that_are_not_sensitive_as_context(): void + { + $sanitized = new SanitizedMessage(new TestSensitiveCommand('Bob', 'p4ssw0rd')); + + $actual = $sanitized->context(); + + $this->assertSame(['name' => 'Bob', 'age' => null], $actual); + } + + #[Test] + public function it_returns_empty_context_for_a_message_without_public_properties(): void + { + $sanitized = new SanitizedMessage($this->createStub(Query::class)); + + $actual = $sanitized->context(); + + $this->assertSame([], $actual); + } +} diff --git a/tests/Unit/Application/Bus/TestCommandDispatcherWithAttributes.php b/tests/Unit/Application/Bus/TestCommandDispatcherWithAttributes.php new file mode 100644 index 00000000..376930b9 --- /dev/null +++ b/tests/Unit/Application/Bus/TestCommandDispatcherWithAttributes.php @@ -0,0 +1,23 @@ + + */ + public function execute(TestCommand $command): Result + { + return Result::ok(); + } +} diff --git a/tests/Unit/Application/Bus/TestQueryDispatcherWithAttributes.php b/tests/Unit/Application/Bus/TestQueryDispatcherWithAttributes.php new file mode 100644 index 00000000..a933f7a7 --- /dev/null +++ b/tests/Unit/Application/Bus/TestQueryDispatcherWithAttributes.php @@ -0,0 +1,23 @@ + + */ + public function execute(TestQuery $query): Result + { + return Result::ok(1); + } +} diff --git a/tests/Unit/Application/Bus/TestSensitiveCommand.php b/tests/Unit/Application/Bus/TestSensitiveCommand.php new file mode 100644 index 00000000..63554f2e --- /dev/null +++ b/tests/Unit/Application/Bus/TestSensitiveCommand.php @@ -0,0 +1,33 @@ +secret; + } +} diff --git a/tests/Unit/Application/Bus/ValidationProcessorTest.php b/tests/Unit/Application/Bus/ValidationProcessorTest.php new file mode 100644 index 00000000..aa804f0e --- /dev/null +++ b/tests/Unit/Application/Bus/ValidationProcessorTest.php @@ -0,0 +1,108 @@ +expectException(BusException::class); + $this->expectExceptionMessage('Expecting a message to validate.'); + + $processor->process(new \stdClass()); + } + + #[Test] + public function it_returns_no_errors_when_there_are_no_stages(): void + { + $processor = new ValidationProcessor(); + + $actual = $processor->process($this->createStub(Command::class)); + + $this->assertEquals(new ListOfErrors(), $actual); + } + + #[Test] + public function it_collects_errors_from_every_stage(): void + { + $message = $this->createStub(Command::class); + $error1 = new Error(null, 'Error 1'); + $error2 = new Error(null, 'Error 2'); + $error3 = new Error(null, 'Error 3'); + $received = []; + $processor = new ValidationProcessor(); + + $actual = $processor->process( + $message, + function (Message $actual) use (&$received, $error1): Error { + $received[] = $actual; + return $error1; + }, + function (Message $actual) use (&$received): null { + $received[] = $actual; + return null; + }, + function (Message $actual) use (&$received, $error2, $error3): ListOfErrors { + $received[] = $actual; + return new ListOfErrors($error2, $error3); + }, + ); + + $this->assertEquals(new ListOfErrors($error1, $error2, $error3), $actual); + $this->assertSame([$message, $message, $message], $received); + } + + #[Test] + public function it_stops_on_first_failure(): void + { + $error = new Error(null, 'Error 1'); + $processor = new ValidationProcessor(stopOnFirstFailure: true); + + $actual = $processor->process( + $this->createStub(Command::class), + fn (): null => null, + fn (): Error => $error, + fn (): never => $this->fail('Not expecting stage to be called.'), + ); + + $this->assertEquals(new ListOfErrors($error), $actual); + } + + #[Test] + public function it_does_not_stop_when_stages_pass(): void + { + $error = new Error(null, 'Error 1'); + $processor = new ValidationProcessor(stopOnFirstFailure: true); + + $actual = $processor->process( + $this->createStub(Command::class), + fn (): null => null, + fn (): ListOfErrors => new ListOfErrors(), + fn (): Error => $error, + ); + + $this->assertEquals(new ListOfErrors($error), $actual); + } +} diff --git a/tests/Unit/Application/Bus/ValidatorTest.php b/tests/Unit/Application/Bus/ValidatorTest.php index c2002760..7f2a71a4 100644 --- a/tests/Unit/Application/Bus/ValidatorTest.php +++ b/tests/Unit/Application/Bus/ValidatorTest.php @@ -12,22 +12,22 @@ namespace CloudCreativity\Modules\Tests\Unit\Application\Bus; +use CloudCreativity\Modules\Bus\PsrPipeContainer; use CloudCreativity\Modules\Bus\Validation\Validator; use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Contracts\Messaging\Message; use CloudCreativity\Modules\Contracts\Messaging\Query; -use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use CloudCreativity\Modules\Testing\FakeContainer; use CloudCreativity\Modules\Toolkit\Result\Error; use CloudCreativity\Modules\Toolkit\Result\ListOfErrors; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; final class ValidatorTest extends TestCase { /** - * @return array> + * @return list}> */ public static function messageProvider(): array { @@ -65,23 +65,15 @@ public function it_validates_message(string $class): void return new ListOfErrors($error2, $error3); }; - $rules = $this->createMock(PipeContainer::class); - $rules - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'Rule2' => $b, - 'Rule3' => $c, - default => $this->fail('Unexpected rule name: ' . $name), - }); - - $validator = new Validator(rules: $rules); - $actual = $validator - ->using([$a, 'Rule2', 'Rule3']) - ->validate($message); - - $this->assertInstanceOf(ListOfErrors::class, $actual); - $this->assertSame([$error1, $error2, $error3], $actual->all()); + $rules = new PsrPipeContainer(); + $rules->bind('Rule2', fn () => $b); + $rules->bind('Rule3', fn () => $c); + + $validator = new Validator(rules: $rules)->using([$a, 'Rule2', 'Rule3']); + + $actual = $validator->validate($message); + + $this->assertEquals(new ListOfErrors($error1, $error2, $error3), $actual); } /** @@ -111,23 +103,15 @@ public function it_validates_message_using_psr_container(string $class): void return new ListOfErrors($error2, $error3); }; - $rules = $this->createMock(ContainerInterface::class); - $rules - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'Rule2' => $b, - 'Rule3' => $c, - default => $this->fail('Unexpected rule name: ' . $name), - }); - - $validator = new Validator(rules: $rules); - $actual = $validator - ->using([$a, 'Rule2', 'Rule3']) - ->validate($message); - - $this->assertInstanceOf(ListOfErrors::class, $actual); - $this->assertSame([$error1, $error2, $error3], $actual->all()); + $rules = new FakeContainer(); + $rules->instance('Rule2', $b); + $rules->instance('Rule3', $c); + + $validator = new Validator(rules: $rules)->using([$a, 'Rule2', 'Rule3']); + + $actual = $validator->validate($message); + + $this->assertEquals(new ListOfErrors($error1, $error2, $error3), $actual); } /** @@ -154,14 +138,13 @@ public function it_stops_on_first_failure(string $class): void $this->fail('Not expecting to be called.'); }; - $validator = new Validator(); - $actual = $validator + $validator = new Validator() ->using([$a, $b, $c]) - ->stopOnFirstFailure() - ->validate($message); + ->stopOnFirstFailure(); - $this->assertInstanceOf(ListOfErrors::class, $actual); - $this->assertSame([$error], $actual->all()); + $actual = $validator->validate($message); + + $this->assertEquals(new ListOfErrors($error), $actual); } #[Test] @@ -170,6 +153,8 @@ public function it_has_no_rules(): void $query = $this->createStub(Query::class); $validator = new Validator(); - $this->assertEquals(new ListOfErrors(), $validator->validate($query)); + $actual = $validator->validate($query); + + $this->assertEquals(new ListOfErrors(), $actual); } } diff --git a/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php b/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php index 9d597417..b7796263 100644 --- a/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php +++ b/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php @@ -14,34 +14,24 @@ use Closure; use CloudCreativity\Modules\Application\DomainEventDispatching\DeferredDispatcher; +use CloudCreativity\Modules\Application\DomainEventDispatching\ListenerContainer; +use CloudCreativity\Modules\Bus\PsrPipeContainer; use CloudCreativity\Modules\Contracts\Application\DomainEventDispatching\DeferredDispatcher as IDeferredDispatcher; -use CloudCreativity\Modules\Contracts\Application\DomainEventDispatching\ListenerContainer; +use CloudCreativity\Modules\Contracts\Application\DomainEventDispatching\ListenerContainer as IListenerContainer; use CloudCreativity\Modules\Contracts\Domain\Events\DomainEvent; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use LogicException; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; final class DeferredDispatcherTest extends TestCase { - private ListenerContainer&MockObject $listeners; - - private DeferredDispatcher $dispatcher; - - protected function setUp(): void + #[Test] + public function it_is_a_deferred_dispatcher(): void { - parent::setUp(); + $dispatcher = $this->makeDispatcher(); - $this->dispatcher = new class ( - listeners: $this->listeners = $this->createMock(ListenerContainer::class), - middleware: $this->createStub(PipeContainer::class), - ) extends DeferredDispatcher {}; - } - - protected function tearDown(): void - { - unset($this->dispatcher, $this->listeners); - parent::tearDown(); + $this->assertInstanceOf(IDeferredDispatcher::class, $dispatcher); } #[Test] @@ -54,18 +44,15 @@ public function it_dispatches_immediately(): void $listener2 = $this->createMock(TestListener::class); $listener3 = $this->createMock(TestListener::class); $listener4 = $this->createMock(TestListener::class); - $listener2Closure = static fn (DomainEvent $event) => $listener2->handle($event); - $this->listeners - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'Listener1' => $listener1, - 'Listener3' => $listener3, - 'Listener4' => $listener4, - default => throw new \RuntimeException('Unexpected name: ' . $name), - }); + $dispatcher = $this->makeDispatcher([ + 'Listener1' => $listener1, + 'Listener3' => $listener3, + 'Listener4' => $listener4, + ]); + $dispatcher->listen($event::class, ['Listener1', $listener2Closure, 'Listener3']); + $dispatcher->listen(TestDomainEvent::class, 'Listener4'); $listener1 ->expects($this->once()) @@ -95,17 +82,24 @@ public function it_dispatches_immediately(): void ->expects($this->never()) ->method('handle'); - $this->dispatcher->listen($event::class, [ - 'Listener1', - $listener2Closure, - 'Listener3', - ]); - $this->dispatcher->listen(TestDomainEvent::class, 'Listener4'); + $dispatcher->dispatch($event); - $this->dispatcher->dispatch($event); + $this->assertSame(['Listener1', 'Listener2', 'Listener3'], $sequence); + } - $this->assertInstanceOf(IDeferredDispatcher::class, $this->dispatcher); - $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3']); + #[Test] + public function it_defers_events(): void + { + $event = new class () extends TestDomainEvent {}; + $listener = $this->createMock(TestListener::class); + $dispatcher = $this->makeDispatcher(['Listener1' => $listener]); + $dispatcher->listen($event::class, 'Listener1'); + + $listener + ->expects($this->never()) + ->method('handle'); + + $dispatcher->dispatch($event); } #[Test] @@ -119,18 +113,17 @@ public function it_flushes_deferred_events(): void $listener2 = $this->createMock(TestListener::class); $listener3 = $this->createMock(TestListener::class); $listener4 = $this->createMock(TestListener::class); + $listener2Closure = static fn (DomainEvent $event) => $listener2->handle($event); - $listener2Closure = static fn (DomainEvent $event) => $listener2->handle($event1); - - $this->listeners - ->expects($this->exactly(3)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'Listener1' => $listener1, - 'Listener3' => $listener3, - 'Listener4' => $listener4, - default => throw new \RuntimeException('Unexpected name: ' . $name), - }); + $dispatcher = $this->makeDispatcher([ + 'Listener1' => $listener1, + 'Listener3' => $listener3, + 'Listener4' => $listener4, + ]); + $dispatcher->listen($event1::class, ['Listener1', $listener2Closure, 'Listener3']); + $dispatcher->listen($event2::class, 'Listener4'); + $dispatcher->dispatch($event1); + $dispatcher->dispatch($event2); $listener1 ->expects($this->once()) @@ -164,20 +157,9 @@ public function it_flushes_deferred_events(): void $sequence[] = 'Listener4'; }); - $this->dispatcher->listen($event1::class, [ - 'Listener1', - $listener2Closure, - 'Listener3', - ]); - $this->dispatcher->listen($event2::class, 'Listener4'); - - $this->dispatcher->dispatch($event1); - $this->dispatcher->dispatch($event2); - $before = $sequence; - $this->dispatcher->flush(); + $dispatcher->flush(); - $this->assertEmpty($before); - $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3', 'Listener4']); + $this->assertSame(['Listener1', 'Listener2', 'Listener3', 'Listener4'], $sequence); } #[Test] @@ -191,15 +173,14 @@ public function it_flushes_deferred_events_including_events_dispatched_by_listen $listener2 = $this->createMock(TestListener::class); $listener3 = $this->createMock(TestListener::class); - $this->listeners - ->expects($this->exactly(3)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'Listener1' => $listener1, - 'Listener2' => $listener2, - 'Listener3' => $listener3, - default => throw new \RuntimeException('Unexpected name: ' . $name), - }); + $dispatcher = $this->makeDispatcher([ + 'Listener1' => $listener1, + 'Listener2' => $listener2, + 'Listener3' => $listener3, + ]); + $dispatcher->listen($event1::class, ['Listener1', 'Listener2']); + $dispatcher->listen($event2::class, 'Listener3'); + $dispatcher->dispatch($event1); $listener1 ->expects($this->once()) @@ -213,9 +194,9 @@ public function it_flushes_deferred_events_including_events_dispatched_by_listen ->expects($this->once()) ->method('handle') ->with($this->identicalTo($event1)) - ->willReturnCallback(function () use ($event2, &$sequence) { + ->willReturnCallback(function () use ($dispatcher, $event2, &$sequence) { $sequence[] = 'Listener2'; - $this->dispatcher->dispatch($event2); + $dispatcher->dispatch($event2); }); $listener3 @@ -226,120 +207,76 @@ public function it_flushes_deferred_events_including_events_dispatched_by_listen $sequence[] = 'Listener3'; }); - $this->dispatcher->listen($event1::class, ['Listener1', 'Listener2']); - $this->dispatcher->listen($event2::class, 'Listener3'); + $dispatcher->flush(); - $this->dispatcher->dispatch($event1); - $before = $sequence; - $this->dispatcher->flush(); - - $this->assertEmpty($before); - $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3']); + $this->assertSame(['Listener1', 'Listener2', 'Listener3'], $sequence); } #[Test] public function it_forgets_deferred_events(): void { - $sequence = []; - $deferred = new class () extends TestDomainEvent {}; - $immediate = new TestImmediateDomainEvent(); - - $listener1 = $this->createMock(TestListener::class); - $listener2 = $this->createMock(TestListener::class); - $listener3 = $this->createMock(TestListener::class); - $listener4 = $this->createMock(TestListener::class); - - $this->listeners - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'Listener1' => $listener1, - 'Listener2' => $listener2, - 'Listener3' => $listener3, - 'Listener4' => $listener4, - default => throw new \RuntimeException('Unexpected name: ' . $name), - }); - - $listener1 - ->expects($this->once()) - ->method('handle') - ->with($this->identicalTo($immediate)) - ->willReturnCallback(function () use (&$sequence) { - $sequence[] = 'Listener1'; - }); - - $listener2 - ->expects($this->once()) - ->method('handle') - ->with($this->identicalTo($immediate)) - ->willReturnCallback(function () use (&$sequence) { - $sequence[] = 'Listener2'; - }); + $event = new class () extends TestDomainEvent {}; + $listener = $this->createMock(TestListener::class); + $dispatcher = $this->makeDispatcher(['Listener1' => $listener]); + $dispatcher->listen($event::class, 'Listener1'); + $dispatcher->dispatch($event); + $dispatcher->forget(); - $listener3 + $listener ->expects($this->never()) ->method('handle'); - $listener4 - ->expects($this->never()) - ->method('handle'); + $dispatcher->flush(); + } - $this->dispatcher->listen($immediate::class, ['Listener1', 'Listener2']); - $this->dispatcher->listen($deferred::class, ['Listener3', 'Listener4']); + #[Test] + public function it_throws_listener_exceptions_when_flushing(): void + { + $event = new class () extends TestDomainEvent {}; + $listener = $this->createStub(TestListener::class); + $listener->method('handle')->willThrowException(new LogicException('Boom!')); + $dispatcher = $this->makeDispatcher(['Listener1' => $listener]); + $dispatcher->listen($event::class, 'Listener1'); + $dispatcher->dispatch($event); - $this->dispatcher->dispatch($deferred); - $step1 = $sequence; - $this->dispatcher->dispatch($immediate); - $step2 = $sequence; - $this->dispatcher->forget(); - $this->dispatcher->flush(); - $step3 = $sequence; + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Boom!'); - $this->assertEmpty($step1); - $this->assertSame($step2, ['Listener1', 'Listener2']); - $this->assertSame($step3, ['Listener1', 'Listener2']); + $dispatcher->flush(); } #[Test] public function it_forgets_deferred_events_after_exception(): void { - $sequence = []; $event1 = new class () extends TestDomainEvent {}; $event2 = $this->createStub(DomainEvent::class); - $expected = new \LogicException('Boom!'); $listener1 = $this->createMock(TestListener::class); $listener2 = $this->createMock(TestListener::class); $listener3 = $this->createMock(TestListener::class); $listener4 = $this->createMock(TestListener::class); - $this->listeners - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'Listener1' => $listener1, - 'Listener2' => $listener2, - 'Listener3' => $listener3, - 'Listener4' => $listener4, - default => throw new \RuntimeException('Unexpected name: ' . $name), - }); + $dispatcher = $this->makeDispatcher([ + 'Listener1' => $listener1, + 'Listener2' => $listener2, + 'Listener3' => $listener3, + 'Listener4' => $listener4, + ]); + $dispatcher->listen($event1::class, ['Listener1', 'Listener2']); + $dispatcher->listen($event2::class, ['Listener3', 'Listener4']); + $dispatcher->dispatch($event1); + $dispatcher->dispatch($event2); $listener1 ->expects($this->once()) ->method('handle') - ->with($this->identicalTo($event1)) - ->willReturnCallback(function () use (&$sequence) { - $sequence[] = 'Listener1'; - }); + ->with($this->identicalTo($event1)); $listener2 ->expects($this->once()) ->method('handle') ->with($this->identicalTo($event1)) - ->willReturnCallback(function () use ($expected, &$sequence) { - $sequence[] = 'Listener2'; - throw $expected; - }); + ->willThrowException(new LogicException('Boom!')); $listener3 ->expects($this->never()) @@ -349,27 +286,28 @@ public function it_forgets_deferred_events_after_exception(): void ->expects($this->never()) ->method('handle'); - $this->dispatcher->listen($event1::class, ['Listener1', 'Listener2']); - $this->dispatcher->listen($event2::class, ['Listener3', 'Listener4']); - $this->dispatcher->dispatch($event1); - $this->dispatcher->dispatch($event2); - try { - $this->dispatcher->flush(); - $this->fail('Expected exception not thrown.'); - } catch (\LogicException $actual) { - $this->assertSame($expected, $actual); + $dispatcher->flush(); + } catch (LogicException) { + // expected } - $this->dispatcher->flush(); // flush again, not expecting any events to be triggered. + $dispatcher->flush(); } #[Test] public function it_does_nothing_when_there_are_no_listeners(): void { $event = $this->createStub(DomainEvent::class); - $this->listeners->expects($this->never())->method($this->anything()); - $this->dispatcher->dispatch($event); + $listeners = $this->createMock(IListenerContainer::class); + $dispatcher = new class ($listeners) extends DeferredDispatcher {}; + $dispatcher->dispatch($event); + + $listeners + ->expects($this->never()) + ->method($this->anything()); + + $dispatcher->flush(); } #[Test] @@ -391,51 +329,33 @@ public function it_dispatches_through_middleware(): void return $next($event3); }; - $middleware = $this->createMock(PipeContainer::class); - $this->dispatcher = new class ( - listeners: $this->listeners, - middleware: $middleware, - ) extends DeferredDispatcher {}; - - $middleware - ->expects($this->once()) - ->method('get') - ->with('Middleware2') - ->willReturn($b); - $listener = $this->createMock(TestListener::class); + $middleware = new PsrPipeContainer(); + $middleware->bind('Middleware2', fn () => $b); + + $dispatcher = $this->makeDispatcher(['MyListener' => $listener], $middleware); + $dispatcher->through([$a, 'Middleware2']); + $dispatcher->listen($event3::class, 'MyListener'); $listener ->expects($this->once()) ->method('handle') ->with($this->identicalTo($event3)); - $this->listeners - ->expects($this->once()) - ->method('get') - ->with('MyListener') - ->willReturn($listener); - - $this->dispatcher->through([$a, 'Middleware2']); - $this->dispatcher->listen($event3::class, 'MyListener'); - $this->dispatcher->dispatch($event1); + $dispatcher->dispatch($event1); } - #[Test] - public function it_fails_when_the_listener_does_not_have_a_handle_method(): void + /** + * @param array $listeners + */ + private function makeDispatcher(array $listeners = [], ?PipeContainer $middleware = null): DeferredDispatcher { - $event = new TestImmediateDomainEvent(); + $container = new ListenerContainer(); - $this->listeners - ->expects($this->once()) - ->method('get') - ->with('Listener1') - ->willReturn(new \DateTime()); - - $this->expectException(\AssertionError::class); - $this->expectExceptionMessage('Listener "DateTime" is not an object with a handle method or a closure.'); + foreach ($listeners as $name => $listener) { + $container->bind($name, fn () => $listener); + } - $this->dispatcher->listen($event::class, 'Listener1'); - $this->dispatcher->dispatch($event); + return new class ($container, $middleware) extends DeferredDispatcher {}; } } diff --git a/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php b/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php index 0a895134..e4a3789d 100644 --- a/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php +++ b/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php @@ -14,60 +14,45 @@ use Closure; use CloudCreativity\Modules\Application\DomainEventDispatching\Dispatcher; -use CloudCreativity\Modules\Contracts\Application\DomainEventDispatching\ListenerContainer; +use CloudCreativity\Modules\Application\DomainEventDispatching\ListenerContainer; +use CloudCreativity\Modules\Bus\PsrPipeContainer; +use CloudCreativity\Modules\Contracts\Application\DomainEventDispatching\ListenerContainer as IListenerContainer; use CloudCreativity\Modules\Contracts\Domain\Events\DomainEvent; use CloudCreativity\Modules\Contracts\Domain\Events\DomainEventDispatcher; -use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use CloudCreativity\Modules\Testing\FakeContainer; +use InvalidArgumentException; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; final class DispatcherTest extends TestCase { - private ListenerContainer&MockObject $listeners; - - private Dispatcher $dispatcher; - - protected function setUp(): void + #[Test] + public function it_is_a_domain_event_dispatcher(): void { - parent::setUp(); + $dispatcher = new class () extends Dispatcher {}; - $this->dispatcher = new class ( - listeners: $this->listeners = $this->createMock(ListenerContainer::class), - middleware: $this->createStub(PipeContainer::class), - ) extends Dispatcher {}; - } - - protected function tearDown(): void - { - unset($this->dispatcher, $this->listeners); - parent::tearDown(); + $this->assertInstanceOf(DomainEventDispatcher::class, $dispatcher); } #[Test] - public function it_dispatches_immediately(): void + public function it_dispatches_to_a_list_of_listeners(): void { $sequence = []; $event1 = new TestImmediateDomainEvent(); $event2 = new class () extends TestDomainEvent {}; - ; $listener1 = $this->createMock(TestListener::class); $listener2 = $this->createMock(TestListener::class); $listener3 = $this->createMock(TestListener::class); - $listener4 = $this->createMock(TestListener::class); - $listener2Closure = static fn (DomainEvent $event) => $listener2->handle($event); - $this->listeners - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'Listener1' => $listener1, - 'Listener3' => $listener3, - 'Listener4' => $listener4, - default => throw new \RuntimeException('Unexpected name: ' . $name), - }); + $listeners = new ListenerContainer(); + $listeners->bind('Listener1', fn () => $listener1); + $listeners->bind('Listener3', fn () => $listener3); + + $dispatcher = new class ($listeners) extends Dispatcher {}; + $dispatcher->listen($event1::class, ['Listener1', $listener2Closure]); + $dispatcher->listen($event2::class, ['Listener3']); $listener1 ->expects($this->once()) @@ -86,43 +71,62 @@ public function it_dispatches_immediately(): void }); $listener3 + ->expects($this->never()) + ->method('handle'); + + $dispatcher->dispatch($event1); + + $this->assertSame(['Listener1', 'Listener2'], $sequence); + } + + #[Test] + public function it_dispatches_to_a_single_listener(): void + { + $event1 = new class () extends TestDomainEvent {}; + $event2 = new TestImmediateDomainEvent(); + + $listener1 = $this->createMock(TestListener::class); + $listener2 = $this->createMock(TestListener::class); + + $listeners = new ListenerContainer(); + $listeners->bind('Listener1', fn () => $listener1); + $listeners->bind('Listener2', fn () => $listener2); + + $dispatcher = new class ($listeners) extends Dispatcher {}; + $dispatcher->listen($event1::class, 'Listener1'); + $dispatcher->listen($event2::class, 'Listener2'); + + $listener1 ->expects($this->once()) ->method('handle') - ->with($this->identicalTo($event2)) - ->willReturnCallback(function () use (&$sequence) { - $sequence[] = 'Listener3'; - }); + ->with($this->identicalTo($event1)); - $listener4 + $listener2 ->expects($this->never()) ->method('handle'); - $this->dispatcher->listen($event1::class, ['Listener1', $listener2Closure]); - $this->dispatcher->listen($event2::class, ['Listener3']); - $this->dispatcher->listen($this->createStub(TestDomainEvent::class)::class, 'Listener4'); - - $this->dispatcher->dispatch($event1); - $this->dispatcher->dispatch($event2); - - $this->assertInstanceOf(DomainEventDispatcher::class, $this->dispatcher); - $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3']); + $dispatcher->dispatch($event1); } #[Test] public function it_does_nothing_when_there_are_no_listeners(): void { $event = $this->createStub(DomainEvent::class); - $this->listeners->expects($this->never())->method($this->anything()); - $this->dispatcher->dispatch($event); + $listeners = $this->createMock(IListenerContainer::class); + $dispatcher = new class ($listeners) extends Dispatcher {}; + + $listeners + ->expects($this->never()) + ->method($this->anything()); + + $dispatcher->dispatch($event); } #[Test] public function it_dispatches_through_middleware(): void { $event1 = new class () extends TestDomainEvent {}; - ; $event2 = new class () extends TestDomainEvent {}; - ; $event3 = new TestImmediateDomainEvent(); $a = function ($actual, Closure $next) use ($event1, $event2): DomainEvent { @@ -137,51 +141,90 @@ public function it_dispatches_through_middleware(): void return $next($event3); }; - $middleware = $this->createMock(PipeContainer::class); - $this->dispatcher = new class ( - listeners: $this->listeners, - middleware: $middleware, - ) extends Dispatcher {}; + $listener = $this->createMock(TestListener::class); - $middleware - ->expects($this->once()) - ->method('get') - ->with('Middleware2') - ->willReturn($b); + $listeners = new ListenerContainer(); + $listeners->bind('MyListener', fn () => $listener); - $listener = $this->createMock(TestListener::class); + $middleware = new PsrPipeContainer(); + $middleware->bind('Middleware2', fn () => $b); + + $dispatcher = new class ($listeners, $middleware) extends Dispatcher {}; + $dispatcher->through([$a, 'Middleware2']); + $dispatcher->listen($event3::class, 'MyListener'); $listener ->expects($this->once()) ->method('handle') ->with($this->identicalTo($event3)); - $this->listeners - ->expects($this->once()) - ->method('get') - ->with('MyListener') - ->willReturn($listener); + $dispatcher->dispatch($event1); + } + + #[Test] + public function it_throws_when_the_listener_is_an_empty_string(): void + { + $dispatcher = new class () extends Dispatcher {}; - $this->dispatcher->through([$a, 'Middleware2']); - $this->dispatcher->listen($event3::class, 'MyListener'); - $this->dispatcher->dispatch($event1); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Expecting listener to be a Closure or non-empty string.'); + + $dispatcher->listen(TestImmediateDomainEvent::class, ['Listener1', '']); } #[Test] - public function it_fails_when_the_listener_does_not_have_a_handle_method(): void + public function it_autowires_listeners_and_middleware_from_attributes(): void { + $sequence = []; $event = new TestImmediateDomainEvent(); + $middleware = new PsrPipeContainer(); + $middleware->bind('Middleware1', function () use (&$sequence): Closure { + return function (DomainEvent $actual, Closure $next) use (&$sequence) { + $sequence[] = 'Middleware1'; + return $next($actual); + }; + }); + + $listeners = new ListenerContainer(); + + foreach (['Listener1', 'Listener2', 'Listener3'] as $name) { + $listeners->bind($name, function () use (&$sequence, $event, $name): Closure { + return function (DomainEvent $actual) use (&$sequence, $event, $name): void { + $this->assertSame($event, $actual); + $sequence[] = $name; + }; + }); + } - $this->listeners - ->expects($this->once()) - ->method('get') - ->with('Listener1') - ->willReturn(new \DateTime()); + $dispatcher = new TestDispatcherWithAttributes($listeners, $middleware); + + $dispatcher->dispatch($event); + + $this->assertSame(['Middleware1', 'Listener1', 'Listener2', 'Listener3'], $sequence); + } + + #[Test] + public function it_resolves_listeners_and_middleware_from_a_psr_container(): void + { + $sequence = []; + $event = new TestImmediateDomainEvent(); + $container = new FakeContainer(); + $container->instance('Middleware1', function (DomainEvent $actual, Closure $next) use (&$sequence) { + $sequence[] = 'Middleware1'; + return $next($actual); + }); + + foreach (['Listener1', 'Listener2', 'Listener3'] as $name) { + $container->instance($name, function (DomainEvent $actual) use (&$sequence, $event, $name): void { + $this->assertSame($event, $actual); + $sequence[] = $name; + }); + } + + $dispatcher = new TestDispatcherWithAttributes($container); - $this->expectException(\AssertionError::class); - $this->expectExceptionMessage('Listener "DateTime" is not an object with a handle method or a closure.'); + $dispatcher->dispatch($event); - $this->dispatcher->listen($event::class, 'Listener1'); - $this->dispatcher->dispatch($event); + $this->assertSame(['Middleware1', 'Listener1', 'Listener2', 'Listener3'], $sequence); } } diff --git a/tests/Unit/Application/DomainEventDispatching/EventHandlerTest.php b/tests/Unit/Application/DomainEventDispatching/EventHandlerTest.php new file mode 100644 index 00000000..dbf34cd5 --- /dev/null +++ b/tests/Unit/Application/DomainEventDispatching/EventHandlerTest.php @@ -0,0 +1,88 @@ +assertSame($listener::class, $actual); + } + + #[Test] + public function it_is_not_dispatched_before_or_after_commit_by_default(): void + { + $handler = new EventHandler(new class () extends TestListener {}); + + $this->assertFalse($handler->beforeCommit()); + $this->assertFalse($handler->afterCommit()); + } + + #[Test] + public function it_is_dispatched_before_commit(): void + { + $handler = new EventHandler(new class () extends TestListenerBeforeCommit {}); + + $this->assertTrue($handler->beforeCommit()); + $this->assertFalse($handler->afterCommit()); + } + + #[Test] + public function it_is_dispatched_after_commit(): void + { + $handler = new EventHandler(new class () extends TestListenerAfterCommit {}); + + $this->assertFalse($handler->beforeCommit()); + $this->assertTrue($handler->afterCommit()); + } + + #[Test] + public function it_invokes_the_listener_handle_method(): void + { + $event = new TestImmediateDomainEvent(); + $listener = $this->createMock(TestListener::class); + $handler = new EventHandler($listener); + + $listener + ->expects($this->once()) + ->method('handle') + ->with($this->identicalTo($event)); + + $handler($event); + } + + #[Test] + public function it_invokes_a_closure_listener(): void + { + $event = new TestImmediateDomainEvent(); + $received = null; + $handler = new EventHandler(function (DomainEvent $actual) use (&$received): void { + $received = $actual; + }); + + $handler($event); + + $this->assertSame($event, $received); + } +} diff --git a/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php b/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php index 3857ac5e..2ce6b1ae 100644 --- a/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php +++ b/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php @@ -13,6 +13,8 @@ namespace CloudCreativity\Modules\Tests\Unit\Application\DomainEventDispatching; use CloudCreativity\Modules\Application\DomainEventDispatching\ListenerContainer; +use CloudCreativity\Modules\Application\ApplicationException; +use CloudCreativity\Modules\Testing\FakeContainer; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -21,30 +23,76 @@ final class ListenerContainerTest extends TestCase #[Test] public function it_creates_listener(): void { - $container = new ListenerContainer(); $listener = new class () extends TestListener {}; - + $container = new ListenerContainer(); $container->bind('bar', fn () => new class () extends TestListener {}); $container->bind('foo', fn () => $listener); - $this->assertSame($listener, $container->get('foo')); + $actual = $container->get('foo'); + + $this->assertSame($listener, $actual); } #[Test] public function it_does_not_recognise_listener_name(): void { $container = new ListenerContainer(); + + $this->expectException(ApplicationException::class); $this->expectExceptionMessage('Unrecognised listener name: foo'); + $container->get('foo'); } #[Test] - public function it_handles_binding_not_returning_an_object(): void + public function it_throws_when_binding_a_string_without_a_psr_container(): void { $container = new ListenerContainer(); - /** @phpstan-ignore-next-line */ - $container->bind('foo', fn () => 'bar'); - $this->expectExceptionMessage('Listener binding for foo must return an object.'); - $container->get('foo'); + + $this->expectException(ApplicationException::class); + $this->expectExceptionMessage('Cannot use a string listener binding without a PSR container.'); + + $container->bind('foo', 'bar'); + } + + #[Test] + public function it_resolves_a_string_binding_via_the_psr_container(): void + { + $listener = new class () extends TestListener {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance('bar', $listener); + $container = new ListenerContainer($psrContainer); + $container->bind('foo', 'bar'); + + $actual = $container->get('foo'); + + $this->assertSame($listener, $actual); + } + + #[Test] + public function it_resolves_an_unbound_listener_name_via_the_psr_container(): void + { + $listener = new class () extends TestListener {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance('foo', $listener); + $container = new ListenerContainer($psrContainer); + + $actual = $container->get('foo'); + + $this->assertSame($listener, $actual); + } + + #[Test] + public function it_prefers_a_closure_binding_over_the_psr_container(): void + { + $listener = new class () extends TestListener {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance('foo', new class () extends TestListener {}); + $container = new ListenerContainer($psrContainer); + $container->bind('foo', fn () => $listener); + + $actual = $container->get('foo'); + + $this->assertSame($listener, $actual); } } diff --git a/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php b/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php index f572ce28..fc66cda3 100644 --- a/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php +++ b/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php @@ -14,20 +14,16 @@ use CloudCreativity\Modules\Application\DomainEventDispatching\Middleware\LogDomainEventDispatch; use CloudCreativity\Modules\Contracts\Domain\Events\DomainEvent; +use CloudCreativity\Modules\Testing\FakeLogger; use DateTimeImmutable; use LogicException; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; final class LogDomainEventDispatchTest extends TestCase { - /** - * @var LoggerInterface&MockObject - */ - private LoggerInterface $logger; + private FakeLogger $logger; private DomainEvent $event; @@ -35,7 +31,7 @@ protected function setUp(): void { parent::setUp(); - $this->logger = $this->createMock(LoggerInterface::class); + $this->logger = new FakeLogger(); /** * Do not expect any public properties to be logged as context. @@ -65,50 +61,32 @@ protected function tearDown(): void public function it_logs_with_the_default_levels(): void { $eventName = $this->event::class; - $logs = []; - - $this->logger - ->expects($this->exactly(2)) - ->method('log') - ->willReturnCallback(function ($level, $message, $context) use (&$logs): bool { - $logs[] = [$level, $message, $context]; - return true; - }); - $middleware = new LogDomainEventDispatch($this->logger); + $middleware($this->event, function (DomainEvent $received) { $this->assertSame($this->event, $received); }); $this->assertSame([ - [LogLevel::DEBUG, "Dispatching domain event {$eventName}.", []], - [LogLevel::INFO, "Dispatched domain event {$eventName}.", []], - ], $logs); + ['level' => LogLevel::DEBUG, 'message' => "Dispatching domain event {$eventName}.", 'context' => []], + ['level' => LogLevel::INFO, 'message' => "Dispatched domain event {$eventName}.", 'context' => []], + ], $this->logger->log); } #[Test] public function it_logs_with_custom_levels(): void { $eventName = $this->event::class; - $logs = []; - - $this->logger - ->expects($this->exactly(2)) - ->method('log') - ->willReturnCallback(function ($level, $message) use (&$logs): bool { - $logs[] = [$level, $message]; - return true; - }); - $middleware = new LogDomainEventDispatch($this->logger, LogLevel::NOTICE, LogLevel::WARNING); + $middleware($this->event, function (DomainEvent $received) { $this->assertSame($this->event, $received); }); $this->assertSame([ - [LogLevel::NOTICE, "Dispatching domain event {$eventName}."], - [LogLevel::WARNING, "Dispatched domain event {$eventName}."], - ], $logs); + ['level' => LogLevel::NOTICE, 'message' => "Dispatching domain event {$eventName}.", 'context' => []], + ['level' => LogLevel::WARNING, 'message' => "Dispatched domain event {$eventName}.", 'context' => []], + ], $this->logger->log); } #[Test] @@ -116,21 +94,20 @@ public function it_logs_after_the_next_closure_is_invoked(): void { $expected = new LogicException(); $eventName = $this->event::class; - - $this->logger - ->expects($this->once()) - ->method('log') - ->with(LogLevel::DEBUG, "Dispatching domain event {$eventName}."); - $middleware = new LogDomainEventDispatch($this->logger); + $actual = null; try { $middleware($this->event, static function () use ($expected) { throw $expected; }); - $this->fail('No exception thrown.'); } catch (LogicException $ex) { - $this->assertSame($expected, $ex); + $actual = $ex; } + + $this->assertSame($expected, $actual); + $this->assertSame([ + ['level' => LogLevel::DEBUG, 'message' => "Dispatching domain event {$eventName}.", 'context' => []], + ], $this->logger->log); } } diff --git a/tests/Unit/Application/DomainEventDispatching/TestDispatcherWithAttributes.php b/tests/Unit/Application/DomainEventDispatching/TestDispatcherWithAttributes.php new file mode 100644 index 00000000..0c630733 --- /dev/null +++ b/tests/Unit/Application/DomainEventDispatching/TestDispatcherWithAttributes.php @@ -0,0 +1,24 @@ +makeDispatcher($this->createStub(UnitOfWorkManager::class)); - $this->listeners = $this->createMock(ListenerContainer::class); - $this->dispatcher = $this->createDispatcher($this->createStub(UnitOfWorkManager::class)); - } - - protected function tearDown(): void - { - unset($this->dispatcher, $this->listeners); - parent::tearDown(); + $this->assertInstanceOf(DomainEventDispatcher::class, $dispatcher); } #[Test] public function it_dispatches_immediately(): void { - $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); - $this->dispatcher = $this->createDispatcher($unitOfWorkManager); - $sequence = []; $event = new TestImmediateDomainEvent(); + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); $listener1 = $this->createMock(TestListener::class); $listener2 = $this->createMock(TestListener::class); @@ -62,21 +52,25 @@ public function it_dispatches_immediately(): void $listener5 = $this->createMock(TestListenerAfterCommit::class); $listener6 = $this->createMock(TestListenerAfterCommit::class); $listener7 = $this->createMock(TestListener::class); - $listener2Closure = static fn (DomainEvent $event) => $listener2->handle($event); - $this->listeners - ->expects($this->exactly(5)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'Listener1' => $listener1, - 'Listener3' => $listener3, - 'Listener4' => $listener4, - 'Listener5' => $listener5, - 'Listener6' => $listener6, - 'Listener7' => $listener7, - default => throw new \RuntimeException('Unexpected name: ' . $name), - }); + $dispatcher = $this->makeDispatcher($unitOfWorkManager, [ + 'Listener1' => $listener1, + 'Listener3' => $listener3, + 'Listener4' => $listener4, + 'Listener5' => $listener5, + 'Listener6' => $listener6, + 'Listener7' => $listener7, + ]); + $dispatcher->listen($event::class, [ + 'Listener1', + $listener2Closure, + 'Listener3', + 'Listener4', + 'Listener5', + 'Listener6', + ]); + $dispatcher->listen(TestDomainEvent::class, 'Listener7'); $listener1 ->expects($this->once()) @@ -126,36 +120,24 @@ public function it_dispatches_immediately(): void ->expects($this->exactly(2)) ->method('afterCommit'); - $this->dispatcher->listen($event::class, [ - 'Listener1', - $listener2Closure, - 'Listener3', - 'Listener4', - 'Listener5', - 'Listener6', - ]); - $this->dispatcher->listen(TestDomainEvent::class, 'Listener7'); - - $this->dispatcher->dispatch($event); + $dispatcher->dispatch($event); - $this->assertInstanceOf(DomainEventDispatcher::class, $this->dispatcher); - $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3']); + $this->assertSame(['Listener1', 'Listener2', 'Listener3'], $sequence); } #[Test] public function it_does_not_dispatch_immediately(): void { - $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); - $this->dispatcher = $this->createDispatcher($unitOfWorkManager); - $event = $this->createStub(DomainEvent::class); - + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); $listener1 = $this->createMock(TestListener::class); $listener2 = $this->createMock(TestListener::class); - $this->listeners - ->expects($this->never()) - ->method('get'); + $dispatcher = $this->makeDispatcher($unitOfWorkManager, [ + 'Listener1' => $listener1, + 'Listener2' => $listener2, + ]); + $dispatcher->listen($event::class, ['Listener1', 'Listener2']); $listener1 ->expects($this->never()) @@ -167,40 +149,28 @@ public function it_does_not_dispatch_immediately(): void $unitOfWorkManager ->expects($this->once()) - ->method('beforeCommit'); // we'll prove this works in the subsequent test + ->method('beforeCommit'); $unitOfWorkManager ->expects($this->never()) ->method('afterCommit'); - $this->dispatcher->listen($event::class, [ - 'Listener1', - 'Listener2', - ]); - - $this->dispatcher->dispatch($event); + $dispatcher->dispatch($event); } - #[Depends('it_does_not_dispatch_immediately')] #[Test] public function it_dispatches_event_in_before_commit_callback(): void { - $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); - $this->dispatcher = $this->createDispatcher($unitOfWorkManager); - $event = new class () extends TestDomainEvent {}; - + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); $listener1 = $this->createMock(TestListener::class); $listener2 = $this->createMock(TestListener::class); - $this->listeners - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(static fn (string $name) => match ($name) { - 'Listener1' => $listener1, - 'Listener2' => $listener2, - default => throw new \RuntimeException('Unexpected name: ' . $name), - }); + $dispatcher = $this->makeDispatcher($unitOfWorkManager, [ + 'Listener1' => $listener1, + 'Listener2' => $listener2, + ]); + $dispatcher->listen($event::class, ['Listener1', 'Listener2']); $listener1 ->expects($this->once()) @@ -215,28 +185,23 @@ public function it_dispatches_event_in_before_commit_callback(): void $unitOfWorkManager ->expects($this->once()) ->method('beforeCommit') - ->with($this->callback(function (Closure $callback): bool { + ->willReturnCallback(function (Closure $callback): void { $callback(); - return true; - })); - - $this->dispatcher->listen($event::class, [ - 'Listener1', - 'Listener2', - ]); + }); - $this->dispatcher->dispatch($event); + $dispatcher->dispatch($event); } #[Test] public function it_dispatches_to_a_before_commit_listener_before_commit(): void { - $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); - $this->dispatcher = $this->createDispatcher($unitOfWorkManager); - $event = new TestImmediateDomainEvent(); + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); $listener = $this->createMock(TestListenerBeforeCommit::class); + $dispatcher = $this->makeDispatcher($unitOfWorkManager, ['BeforeCommitListener' => $listener]); + $dispatcher->listen($event::class, 'BeforeCommitListener'); + $listener ->expects($this->once()) ->method('handle') @@ -245,7 +210,7 @@ public function it_dispatches_to_a_before_commit_listener_before_commit(): void $unitOfWorkManager ->expects($this->once()) ->method('beforeCommit') - ->willReturnCallback(function (Closure $callback) { + ->willReturnCallback(function (Closure $callback): void { $callback(); }); @@ -253,25 +218,19 @@ public function it_dispatches_to_a_before_commit_listener_before_commit(): void ->expects($this->never()) ->method('afterCommit'); - $this->listeners - ->expects($this->once()) - ->method('get') - ->with('BeforeCommitListener') - ->willReturn($listener); - - $this->dispatcher->listen($event::class, 'BeforeCommitListener'); - $this->dispatcher->dispatch($event); + $dispatcher->dispatch($event); } #[Test] public function it_dispatches_to_an_after_commit_listener_after_commit(): void { - $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); - $this->dispatcher = $this->createDispatcher($unitOfWorkManager); - $event = new TestImmediateDomainEvent(); + $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class); $listener = $this->createMock(TestListenerAfterCommit::class); + $dispatcher = $this->makeDispatcher($unitOfWorkManager, ['AfterCommitListener' => $listener]); + $dispatcher->listen($event::class, 'AfterCommitListener'); + $listener ->expects($this->once()) ->method('handle') @@ -280,7 +239,7 @@ public function it_dispatches_to_an_after_commit_listener_after_commit(): void $unitOfWorkManager ->expects($this->once()) ->method('afterCommit') - ->willReturnCallback(function (Closure $callback) { + ->willReturnCallback(function (Closure $callback): void { $callback(); }); @@ -288,22 +247,24 @@ public function it_dispatches_to_an_after_commit_listener_after_commit(): void ->expects($this->never()) ->method('beforeCommit'); - $this->listeners - ->expects($this->once()) - ->method('get') - ->with('AfterCommitListener') - ->willReturn($listener); - - $this->dispatcher->listen($event::class, 'AfterCommitListener'); - $this->dispatcher->dispatch($event); + $dispatcher->dispatch($event); } #[Test] public function it_does_nothing_when_there_are_no_listeners(): void { $event = $this->createStub(DomainEvent::class); - $this->listeners->expects($this->never())->method($this->anything()); - $this->dispatcher->dispatch($event); + $listeners = $this->createMock(IListenerContainer::class); + $dispatcher = new class ( + unitOfWorkManager: $this->createStub(UnitOfWorkManager::class), + listeners: $listeners, + ) extends UnitOfWorkAwareDispatcher {}; + + $listeners + ->expects($this->never()) + ->method($this->anything()); + + $dispatcher->dispatch($event); } #[Test] @@ -325,84 +286,102 @@ public function it_dispatches_through_middleware(): void return $next($event3); }; - $middleware = $this->createMock(PipeContainer::class); - $this->dispatcher = $this->createDispatcher($this->createStub(UnitOfWorkManager::class), $middleware); - - $middleware - ->expects($this->once()) - ->method('get') - ->with('Middleware2') - ->willReturn($b); - $listener = $this->createMock(TestListener::class); + $middleware = new PsrPipeContainer(); + $middleware->bind('Middleware2', fn () => $b); + + $dispatcher = $this->makeDispatcher( + $this->createStub(UnitOfWorkManager::class), + ['MyListener' => $listener], + $middleware, + ); + $dispatcher->through([$a, 'Middleware2']); + $dispatcher->listen($event3::class, 'MyListener'); $listener ->expects($this->once()) ->method('handle') ->with($this->identicalTo($event3)); - $this->listeners - ->expects($this->once()) - ->method('get') - ->with('MyListener') - ->willReturn($listener); - - $this->dispatcher->through([$a, 'Middleware2']); - $this->dispatcher->listen($event3::class, 'MyListener'); - $this->dispatcher->dispatch($event1); + $dispatcher->dispatch($event1); } #[Test] - public function it_fails_when_the_listener_does_not_have_a_handle_method(): void + public function it_logs_before_commit_listeners(): void { $event = new TestImmediateDomainEvent(); + $listener = $this->createMock(TestListenerBeforeCommit::class); + $logger = new FakeLogger(); + $unitOfWork = new FakeUnitOfWork(); + $unitOfWorkManager = new UnitOfWorkManagerImpl($unitOfWork); + $dispatcher = $this->makeDispatcher($unitOfWorkManager, ['MyListener' => $listener], logger: $logger); + $dispatcher->listen($event::class, 'MyListener'); + $context = ['event' => $event::class, 'listener' => $listener::class]; - $this->listeners + $listener ->expects($this->once()) - ->method('get') - ->with('Listener1') - ->willReturn(new \DateTime()); + ->method('handle') + ->with($this->identicalTo($event)); - $this->expectException(\AssertionError::class); - $this->expectExceptionMessage('Listener "DateTime" is not an object with a handle method or a closure.'); + $unitOfWorkManager->execute(static function () use ($dispatcher, $event): void { + $dispatcher->dispatch($event); + }); - $this->dispatcher->listen($event::class, 'Listener1'); - $this->dispatcher->dispatch($event); + $this->assertSame([ + ['level' => LogLevel::DEBUG, 'message' => 'Deferring listener to be handled before commit.', 'context' => $context], + ['level' => LogLevel::DEBUG, 'message' => 'Executing listener before commit.', 'context' => $context], + ], $logger->log); + $this->assertSame(1, $unitOfWork->commits); } #[Test] - public function it_fails_when_a_listener_implements_both_before_and_after_commit(): void + public function it_logs_after_commit_listeners(): void { - $listener = new class () implements DispatchBeforeCommit, DispatchAfterCommit { - public function handle(): void - { - // no-op - } - }; + $event = new TestImmediateDomainEvent(); + $listener = $this->createMock(TestListenerAfterCommit::class); + $logger = new FakeLogger(); + $unitOfWork = new FakeUnitOfWork(); + $unitOfWorkManager = new UnitOfWorkManagerImpl($unitOfWork); + $dispatcher = $this->makeDispatcher($unitOfWorkManager, ['MyListener' => $listener], logger: $logger); + $dispatcher->listen($event::class, 'MyListener'); + $context = ['event' => $event::class, 'listener' => $listener::class]; - $this->listeners + $listener ->expects($this->once()) - ->method('get') - ->with('InvalidListener') - ->willReturn($listener); - - $event = new TestImmediateDomainEvent(); - $this->dispatcher->listen($event::class, 'InvalidListener'); + ->method('handle') + ->with($this->identicalTo($event)); - $this->expectException(\AssertionError::class); - $this->expectExceptionMessage('cannot be dispatched both before and after a unit of work is committed.'); + $unitOfWorkManager->execute(static function () use ($dispatcher, $event): void { + $dispatcher->dispatch($event); + }); - $this->dispatcher->dispatch($event); + $this->assertSame([ + ['level' => LogLevel::DEBUG, 'message' => 'Deferring listener to be handled after commit.', 'context' => $context], + ['level' => LogLevel::DEBUG, 'message' => 'Executing listener after commit.', 'context' => $context], + ], $logger->log); + $this->assertSame(1, $unitOfWork->commits); } - private function createDispatcher( + /** + * @param array $listeners + */ + private function makeDispatcher( UnitOfWorkManager $unitOfWorkManager, + array $listeners = [], ?PipeContainer $middleware = null, + ?FakeLogger $logger = null, ): UnitOfWorkAwareDispatcher { + $container = new ListenerContainer(); + + foreach ($listeners as $name => $listener) { + $container->bind($name, fn () => $listener); + } + return new class ( unitOfWorkManager: $unitOfWorkManager, - listeners: $this->listeners, - middleware: $middleware ?? $this->createStub(PipeContainer::class), + listeners: $container, + middleware: $middleware, + logger: $logger, ) extends UnitOfWorkAwareDispatcher {}; } } diff --git a/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php b/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php index 0d2f19a1..f76ecd4e 100644 --- a/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php +++ b/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php @@ -15,10 +15,9 @@ use CloudCreativity\Modules\Bus\BusException; use CloudCreativity\Modules\Bus\EventHandler; use CloudCreativity\Modules\Bus\EventHandlerContainer; -use CloudCreativity\Modules\Tests\Unit\Infrastructure\OutboundEventBus\TestOutboundEvent; +use CloudCreativity\Modules\Testing\FakeContainer; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; final class EventHandlerContainerTest extends TestCase { @@ -30,10 +29,10 @@ public function it_has_handler_bindings(): void $container = new EventHandlerContainer(); $container->bind(TestInboundEvent::class, fn () => $a); - $container->bind(TestOutboundEvent::class, fn () => $b); + $container->bind(TestOtherInboundEvent::class, fn () => $b); $this->assertEquals(new EventHandler($a), $container->get(TestInboundEvent::class)); - $this->assertEquals(new EventHandler($b), $container->get(TestOutboundEvent::class)); + $this->assertEquals(new EventHandler($b), $container->get(TestOtherInboundEvent::class)); } #[Test] @@ -42,57 +41,55 @@ public function it_uses_psr_container(): void $a = new class () extends TestEventHandler {}; $b = $this->createStub(TestEventHandler::class); - $psrContainer = $this->createMock(ContainerInterface::class); - $psrContainer - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $class) => match ($class) { - $a::class => $a, - $b::class => $b, - default => $this->fail('Unexpected class requested: ' . $class), - }); + $psrContainer = new FakeContainer(); + $psrContainer->instance($a::class, $a); + $psrContainer->instance($b::class, $b); $container = new EventHandlerContainer(container: $psrContainer); $container->bind(TestInboundEvent::class, $a::class); - $container->bind(TestOutboundEvent::class, $b::class); + $container->bind(TestOtherInboundEvent::class, $b::class); $this->assertEquals(new EventHandler($a), $container->get(TestInboundEvent::class)); - $this->assertEquals(new EventHandler($b), $container->get(TestOutboundEvent::class)); + $this->assertEquals(new EventHandler($b), $container->get(TestOtherInboundEvent::class)); } #[Test] - public function it_has_bound_default_handler(): void + public function it_prefers_a_bound_handler_over_the_default_handler(): void { - $a = new class () extends TestEventHandler {}; - $b = $this->createStub(TestEventHandler::class); + $handler = new class () extends TestEventHandler {}; + $container = new EventHandlerContainer(default: fn () => new class () extends TestEventHandler {}); + $container->bind(TestInboundEvent::class, fn () => $handler); - $container = new EventHandlerContainer(default: fn () => $b); - $container->bind(TestInboundEvent::class, fn () => $a); + $actual = $container->get(TestInboundEvent::class); - $this->assertEquals(new EventHandler($a), $container->get(TestInboundEvent::class)); - $this->assertEquals(new EventHandler($b), $container->get(TestOutboundEvent::class)); + $this->assertEquals(new EventHandler($handler), $actual); } #[Test] - public function it_has_default_handler_in_psr_container(): void + public function it_has_bound_default_handler(): void { - $a = new class () extends TestEventHandler {}; - $b = $this->createStub(TestEventHandler::class); + $default = $this->createStub(TestEventHandler::class); + $container = new EventHandlerContainer(default: fn () => $default); + $container->bind(TestInboundEvent::class, fn () => new class () extends TestEventHandler {}); - $psrContainer = $this->createMock(ContainerInterface::class); - $psrContainer - ->expects($this->once()) - ->method('get') - ->with('default-handler') - ->willReturn($b); + $actual = $container->get(TestOtherInboundEvent::class); + $this->assertEquals(new EventHandler($default), $actual); + } + + #[Test] + public function it_has_default_handler_in_psr_container(): void + { + $default = $this->createStub(TestEventHandler::class); + $psrContainer = new FakeContainer(); + $psrContainer->instance('default-handler', $default); $container = new EventHandlerContainer(default: 'default-handler', container: $psrContainer); - $container->bind(TestInboundEvent::class, fn () => $a); + $container->bind(TestInboundEvent::class, fn () => new class () extends TestEventHandler {}); - $this->assertEquals(new EventHandler($a), $container->get(TestInboundEvent::class)); - $this->assertEquals(new EventHandler($b), $container->get(TestOutboundEvent::class)); - } + $actual = $container->get(TestOtherInboundEvent::class); + $this->assertEquals(new EventHandler($default), $actual); + } #[Test] public function it_does_not_have_handler(): void @@ -102,9 +99,43 @@ public function it_does_not_have_handler(): void $this->expectException(BusException::class); $this->expectExceptionMessage( - 'No handler bound for integration event: ' . TestOutboundEvent::class, + 'No handler bound for integration event: ' . TestOtherInboundEvent::class, ); - $container->get(TestOutboundEvent::class); + $container->get(TestOtherInboundEvent::class); + } + + #[Test] + public function it_throws_when_binding_a_string_without_a_psr_container(): void + { + $container = new EventHandlerContainer(); + + $this->expectException(BusException::class); + $this->expectExceptionMessage('Cannot use a string event handler binding without a PSR container.'); + + $container->bind(TestInboundEvent::class, TestEventHandler::class); + } + + #[Test] + public function it_binds_a_default_handler(): void + { + $handler = new class () extends TestEventHandler {}; + $container = new EventHandlerContainer(); + $container->withDefault(fn () => $handler); + + $actual = $container->get(TestInboundEvent::class); + + $this->assertEquals(new EventHandler($handler), $actual); + } + + #[Test] + public function it_throws_when_the_default_handler_is_already_set(): void + { + $container = new EventHandlerContainer(default: fn () => new class () extends TestEventHandler {}); + + $this->expectException(BusException::class); + $this->expectExceptionMessage('Default event handler binding is already set.'); + + $container->withDefault(fn () => new class () extends TestEventHandler {}); } } diff --git a/tests/Unit/Application/InboundEventBus/EventHandlerTest.php b/tests/Unit/Application/InboundEventBus/EventHandlerTest.php index e3ba1a81..f3173689 100644 --- a/tests/Unit/Application/InboundEventBus/EventHandlerTest.php +++ b/tests/Unit/Application/InboundEventBus/EventHandlerTest.php @@ -19,39 +19,49 @@ final class EventHandlerTest extends TestCase { #[Test] - public function it_handles_the_event_and_returns_its_middleware(): void + public function it_handles_the_event(): void { $event = new TestInboundEvent(); - $innerHandler = $this->createMock(TestEventHandler::class); + $handler = new EventHandler($innerHandler); + $innerHandler ->expects($this->once()) ->method('handle') ->with($this->identicalTo($event)); - $innerHandler - ->expects($this->once()) - ->method('middleware') - ->willReturn($middleware = ['Middleware1', 'Middleware2']); + $handler($event); + } + #[Test] + public function it_returns_the_middleware_of_the_inner_handler(): void + { + $innerHandler = $this->createStub(TestEventHandler::class); + $innerHandler->method('middleware')->willReturn(['Middleware1', 'Middleware2']); $handler = new EventHandler($innerHandler); - $handler($event); - $this->assertSame($middleware, $handler->middleware()); + $actual = $handler->middleware(); + + $this->assertSame(['Middleware1', 'Middleware2'], $actual); } #[Test] - public function it_does_not_have_execute_method(): void + public function it_returns_middleware_from_the_through_attribute(): void { - $handler = new EventHandler(new \DateTime()); - $event = new TestInboundEvent(); - $eventClass = $event::class; + $handler = new EventHandler(new TestEventHandlerWithThrough()); - $this->expectException(\AssertionError::class); - $this->expectExceptionMessage( - "Cannot dispatch \"{$eventClass}\" - handler \"DateTime\" does not have a handle method.", - ); + $actual = $handler->middleware(); - $handler($event); + $this->assertSame(['Middleware1', 'Middleware2'], $actual); + } + + #[Test] + public function it_returns_no_middleware_when_none_is_declared(): void + { + $handler = new EventHandler(new \stdClass()); + + $actual = $handler->middleware(); + + $this->assertSame([], $actual); } } diff --git a/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php b/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php index 60951cfc..fd6dd3e1 100644 --- a/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php +++ b/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php @@ -12,59 +12,45 @@ namespace CloudCreativity\Modules\Tests\Unit\Application\InboundEventBus; +use Closure; use CloudCreativity\Modules\Bus\InboundEventDispatcher; +use CloudCreativity\Modules\Bus\PsrPipeContainer; +use CloudCreativity\Modules\Bus\SwallowInboundEvent; use CloudCreativity\Modules\Contracts\Bus\EventHandler; use CloudCreativity\Modules\Contracts\Bus\EventHandlerContainer; use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; -use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use CloudCreativity\Modules\Testing\FakeContainer; +use CloudCreativity\Modules\Testing\FakeLogger; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; final class InboundEventDispatcherTest extends TestCase { - private EventHandlerContainer&MockObject $handlers; - - private InboundEventDispatcher $dispatcher; - /** - * @var array + * @var list */ private array $sequence = []; - protected function setUp(): void - { - parent::setUp(); - - $this->dispatcher = new class ( - handlers: $this->handlers = $this->createMock(EventHandlerContainer::class), - middleware: $this->createStub(PipeContainer::class), - ) extends InboundEventDispatcher {}; - } - - protected function tearDown(): void - { - unset($this->handlers, $this->dispatcher, $this->sequence); - parent::tearDown(); - } - #[Test] public function it_dispatches_an_event(): void { $event = $this->createStub(IntegrationEvent::class); + $handler = $this->createMock(EventHandler::class); + $handlers = $this->createMock(EventHandlerContainer::class); + $dispatcher = new class ($handlers) extends InboundEventDispatcher {}; - $this->handlers + $handlers ->expects($this->once()) ->method('get') ->with($event::class) - ->willReturn($handler = $this->createMock(EventHandler::class)); + ->willReturn($handler); $handler ->expects($this->once()) ->method('__invoke') ->with($this->identicalTo($event)); - $this->dispatcher->dispatch($event); + $dispatcher->dispatch($event); } #[Test] @@ -75,29 +61,37 @@ public function it_dispatches_an_event_through_middleware(): void $event3 = new TestInboundEvent(); $event4 = new TestInboundEvent(); $handler = $this->createMock(EventHandler::class); + $handlers = $this->createMock(EventHandlerContainer::class); - $middleware1 = function (TestInboundEvent $event, \Closure $next) use ($event1, $event2): void { + $middleware1 = function (TestInboundEvent $event, Closure $next) use ($event1, $event2): void { $this->assertSame($event1, $event); $this->sequence[] = 'before1'; $next($event2); $this->sequence[] = 'after1'; }; - $middleware2 = function (TestInboundEvent $event, \Closure $next) use ($event2, $event3): void { + $middleware2 = function (TestInboundEvent $event, Closure $next) use ($event2, $event3): void { $this->assertSame($event2, $event); $this->sequence[] = 'before2'; $next($event3); $this->sequence[] = 'after2'; }; - $middleware3 = function (TestInboundEvent $event, \Closure $next) use ($event3, $event4): void { + $middleware3 = function (TestInboundEvent $event, Closure $next) use ($event3, $event4): void { $this->assertSame($event3, $event); $this->sequence[] = 'before3'; $next($event4); $this->sequence[] = 'after3'; }; - $this->handlers + $middleware = new PsrPipeContainer(); + $middleware->bind('MyFirstMiddleware', fn () => $middleware1); + $middleware->bind('MySecondMiddleware', fn () => $middleware2); + + $dispatcher = new class ($handlers, $middleware) extends InboundEventDispatcher {}; + $dispatcher->through(['MyFirstMiddleware']); + + $handlers ->expects($this->once()) ->method('get') ->with($event1::class) @@ -106,21 +100,6 @@ public function it_dispatches_an_event_through_middleware(): void return $handler; }); - $middleware = $this->createMock(PipeContainer::class); - $this->dispatcher = new class ( - handlers: $this->handlers, - middleware: $middleware, - ) extends InboundEventDispatcher {}; - - $middleware - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $name) => match ($name) { - 'MyFirstMiddleware' => $middleware1, - 'MySecondMiddleware' => $middleware2, - default => $this->fail('Unexpected middleware: ' . $name), - }); - $handler ->expects($this->once()) ->method('middleware') @@ -131,8 +110,7 @@ public function it_dispatches_an_event_through_middleware(): void ->method('__invoke') ->with($this->identicalTo($event4)); - $this->dispatcher->through(['MyFirstMiddleware']); - $this->dispatcher->dispatch($event1); + $dispatcher->dispatch($event1); $this->assertSame([ 'before1', @@ -143,4 +121,83 @@ public function it_dispatches_an_event_through_middleware(): void 'after1', ], $this->sequence); } + + #[Test] + public function it_autowires_handlers_and_middleware_from_a_psr_container(): void + { + $event = new TestInboundEvent(); + $handler = $this->createMock(TestEventHandler::class); + $container = new FakeContainer(); + $container->instance(TestEventHandler::class, $handler); + $container->instance('Middleware1', function (IntegrationEvent $actual, Closure $next): void { + $this->sequence[] = 'Middleware1'; + $next($actual); + }); + $dispatcher = new TestInboundEventDispatcherWithAttributes($container); + + $handler + ->expects($this->once()) + ->method('handle') + ->with($this->identicalTo($event)) + ->willReturnCallback(function (): void { + $this->sequence[] = 'handler'; + }); + + $dispatcher->dispatch($event); + + $this->assertSame(['Middleware1', 'handler'], $this->sequence); + } + + #[Test] + public function it_autowires_the_default_handler_from_a_psr_container(): void + { + $event = $this->createStub(IntegrationEvent::class); + $logger = new FakeLogger(); + $container = new FakeContainer(); + $container->instance(SwallowInboundEvent::class, new SwallowInboundEvent($logger)); + $container->instance('Middleware1', function (IntegrationEvent $actual, Closure $next): void { + $this->sequence[] = 'Middleware1'; + $next($actual); + }); + $dispatcher = new TestInboundEventDispatcherWithAttributes($container); + + $dispatcher->dispatch($event); + + $this->assertSame(['Middleware1'], $this->sequence); + $this->assertSame([ + 'DEBUG: Swallowing inbound integration event ' . $event::class . '.', + ], $logger->messages()); + } + + #[Test] + public function it_autowires_middleware_but_not_handlers_with_a_custom_handler_container(): void + { + $event = new TestInboundEvent(); + $middleware = new PsrPipeContainer(); + $middleware->bind('Middleware1', fn () => function (IntegrationEvent $actual, Closure $next): void { + $this->sequence[] = 'Middleware1'; + $next($actual); + }); + $handler = $this->createMock(EventHandler::class); + $handlers = $this->createMock(EventHandlerContainer::class); + $dispatcher = new TestInboundEventDispatcherWithAttributes($handlers, $middleware); + + $handlers + ->expects($this->once()) + ->method('get') + ->with(TestInboundEvent::class) + ->willReturn($handler); + + $handler + ->expects($this->once()) + ->method('__invoke') + ->with($this->identicalTo($event)) + ->willReturnCallback(function (): void { + $this->sequence[] = 'handler'; + }); + + $dispatcher->dispatch($event); + + $this->assertSame(['Middleware1', 'handler'], $this->sequence); + } } diff --git a/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php b/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php index 48c1e12f..e9f32ef5 100644 --- a/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php +++ b/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php @@ -13,10 +13,10 @@ namespace CloudCreativity\Modules\Tests\Unit\Application\InboundEventBus; use CloudCreativity\Modules\Bus\SwallowInboundEvent; +use CloudCreativity\Modules\Testing\FakeLogger; use CloudCreativity\Modules\Toolkit\ModuleBasename; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; final class SwallowInboundEventTest extends TestCase @@ -25,9 +25,10 @@ final class SwallowInboundEventTest extends TestCase public function it_does_nothing(): void { $handler = new SwallowInboundEvent(); + + $this->expectNotToPerformAssertions(); + $handler->handle(new TestInboundEvent()); - /** @phpstan-ignore-next-line */ - $this->assertTrue(true); } #[Test] @@ -35,18 +36,14 @@ public function it_logs_that_it_does_nothing(): void { $event = new TestInboundEvent(); $name = ModuleBasename::from($event); - $logger = $this->createMock(LoggerInterface::class); - $logger - ->expects($this->once()) - ->method('log') - ->with( - LogLevel::DEBUG, - "Swallowing inbound integration event {$name}.", - [], - ); - + $logger = new FakeLogger(); $handler = new SwallowInboundEvent($logger); + $handler->handle($event); + + $this->assertSame([ + ['level' => LogLevel::DEBUG, 'message' => "Swallowing inbound integration event {$name}.", 'context' => []], + ], $logger->log); } #[Test] @@ -54,17 +51,13 @@ public function it_logs_that_it_does_nothing_with_specified_log_level(): void { $event = new TestInboundEvent(); $name = ModuleBasename::from($event); - $logger = $this->createMock(LoggerInterface::class); - $logger - ->expects($this->once()) - ->method('log') - ->with( - LogLevel::NOTICE, - "Swallowing inbound integration event {$name}.", - [], - ); - + $logger = new FakeLogger(); $handler = new SwallowInboundEvent(logger: $logger, level: LogLevel::NOTICE); + $handler->handle($event); + + $this->assertSame([ + ['level' => LogLevel::NOTICE, 'message' => "Swallowing inbound integration event {$name}.", 'context' => []], + ], $logger->log); } } diff --git a/tests/Unit/Application/InboundEventBus/TestEventHandlerWithThrough.php b/tests/Unit/Application/InboundEventBus/TestEventHandlerWithThrough.php new file mode 100644 index 00000000..9f8451b8 --- /dev/null +++ b/tests/Unit/Application/InboundEventBus/TestEventHandlerWithThrough.php @@ -0,0 +1,24 @@ +manager = new UnitOfWorkManager( $this->unitOfWork = $this->createMock(UnitOfWork::class), - $this->createStub(ExceptionReporter::class), + $this->reporter = new FakeExceptionReporter(), ); } protected function tearDown(): void { - unset($this->manager, $this->unitOfWork); + unset($this->manager, $this->unitOfWork, $this->reporter); parent::tearDown(); } @@ -49,17 +52,6 @@ public function it_executes_callbacks(): void { $sequence = []; - $this->unitOfWork - ->expects($this->once()) - ->method('execute') - ->willReturnCallback(function (Closure $callback, int $attempts) use (&$sequence) { - $this->assertSame(1, $attempts); - $sequence[] = 'start'; - $result = $callback(); - $sequence[] = 'commit'; - return $result; - }); - $before1 = function () use (&$sequence): void { $this->assertSame(['start'], $sequence); $sequence[] = 'before1'; @@ -82,6 +74,17 @@ public function it_executes_callbacks(): void $expected = new \DateTime(); + $this->unitOfWork + ->expects($this->once()) + ->method('execute') + ->willReturnCallback(function (Closure $callback, int $attempts) use (&$sequence) { + $this->assertSame(1, $attempts); + $sequence[] = 'start'; + $result = $callback(); + $sequence[] = 'commit'; + return $result; + }); + $actual = $this->manager->execute(function () use ($before1, $before2, $after1, $after2, $expected) { $this->manager->beforeCommit($before1); $this->manager->afterCommit($after1); @@ -97,18 +100,9 @@ public function it_executes_callbacks(): void #[Test] public function it_executes_callback_when_transaction_fails_to_commit(): void { - $expected = new \RuntimeException('Boom'); + $expected = new RuntimeException('Boom'); $sequence = []; - - $this->unitOfWork - ->expects($this->once()) - ->method('execute') - ->willReturnCallback(function (Closure $callback, int $attempts) use (&$sequence, $expected) { - $this->assertSame(1, $attempts); - $sequence[] = 'start'; - $callback(); - throw $expected; - }); + $actual = null; $before1 = function () use (&$sequence): void { $this->assertSame(['start'], $sequence); @@ -124,17 +118,27 @@ public function it_executes_callback_when_transaction_fails_to_commit(): void $this->fail('Not expecting after callback to be executed.'); }; + $this->unitOfWork + ->expects($this->once()) + ->method('execute') + ->willReturnCallback(function (Closure $callback, int $attempts) use (&$sequence, $expected) { + $this->assertSame(1, $attempts); + $sequence[] = 'start'; + $callback(); + throw $expected; + }); + try { $this->manager->execute(function () use ($before1, $before2, $after) { $this->manager->beforeCommit($before1); $this->manager->afterCommit($after); $this->manager->beforeCommit($before2); }); - $this->fail('No exception thrown.'); - } catch (\RuntimeException $ex) { - $this->assertSame($expected, $ex); + } catch (RuntimeException $ex) { + $actual = $ex; } + $this->assertSame($expected, $actual); $this->assertSame(['start', 'before1', 'before2'], $sequence); } @@ -146,17 +150,6 @@ public function it_executes_additional_commit_callbacks(): void { $sequence = []; - $this->unitOfWork - ->expects($this->once()) - ->method('execute') - ->willReturnCallback(function (Closure $callback, int $attempts) use (&$sequence) { - $this->assertSame(1, $attempts); - $sequence[] = 'start'; - $result = $callback(); - $sequence[] = 'commit'; - return $result; - }); - $before = [ function () use (&$sequence): void { $this->assertSame(['start'], $sequence); @@ -192,6 +185,17 @@ function () use (&$sequence): void { $expected = new \DateTime(); + $this->unitOfWork + ->expects($this->once()) + ->method('execute') + ->willReturnCallback(function (Closure $callback, int $attempts) use (&$sequence) { + $this->assertSame(1, $attempts); + $sequence[] = 'start'; + $result = $callback(); + $sequence[] = 'commit'; + return $result; + }); + $actual = $this->manager->execute(function () use ($before, $after, $expected) { $this->manager->beforeCommit($before[0]); $this->manager->beforeCommit($before[1]); @@ -227,33 +231,23 @@ public function it_flushes_callbacks_on_successful_transaction(): void ->method('execute') ->willReturnCallback(fn (Closure $callback) => $callback()); - $result1 = $this->manager->execute(function () { + $this->manager->execute(function () { $this->manager->beforeCommit(fn () => null); $this->manager->afterCommit(fn () => null); - return 1; }); // this would error if the manager is not empty at this point (tests below prove that). - $result2 = $this->manager->execute(fn () => 2); + $actual = $this->manager->execute(fn () => 2); - $this->assertSame(1, $result1); - $this->assertSame(2, $result2); + $this->assertSame(2, $actual); } #[Test] public function it_flushes_callbacks_on_unsuccessful_transaction(): void { - $reporter = $this->createMock(ExceptionReporter::class); - $this->manager = new UnitOfWorkManager($this->unitOfWork, $reporter); - $ex = new LogicException('Boom'); $count = 0; - $reporter - ->expects($this->exactly(2)) // only "swallowed" exceptions are reported - ->method('report') - ->with($this->identicalTo($ex)); - $this->unitOfWork ->expects($this->exactly(4)) ->method('execute') @@ -271,15 +265,15 @@ public function it_flushes_callbacks_on_unsuccessful_transaction(): void $this->manager->beforeCommit(fn () => null); $this->manager->afterCommit(fn () => null); }, 2); - $this->fail('No exception thrown.'); - } catch (LogicException $ex) { - $this->assertSame($ex, $ex); + } catch (LogicException) { + // expected } // this would error if the manager is not empty at this point (tests below prove that). - $result = $this->manager->execute(fn () => true, 2); + $actual = $this->manager->execute(fn () => true, 2); - $this->assertTrue($result); + $this->assertTrue($actual); + $this->assertSame([$ex, $ex], $this->reporter->reported); // only "swallowed" exceptions are reported } /** @@ -296,18 +290,10 @@ public function it_flushes_callbacks_on_unsuccessful_transaction(): void #[Test] public function it_handles_callback_executing_multiple_times(): void { - $reporter = $this->createMock(ExceptionReporter::class); - $this->manager = new UnitOfWorkManager($this->unitOfWork, $reporter); - $ex = new LogicException('Boom!'); $sequence = []; $count = 0; - $reporter - ->expects($this->exactly(2)) - ->method('report') - ->with($this->identicalTo($ex)); - $before = [ function () use (&$sequence): void { $sequence[] = 'before1'; @@ -371,6 +357,7 @@ function () use (&$sequence): void { 'after1', 'after2', ], $sequence); + $this->assertSame([$ex, $ex], $this->reporter->reported); } /** @@ -389,18 +376,10 @@ function () use (&$sequence): void { #[Test] public function it_handles_unit_of_work_failing_multiple_times(): void { - $reporter = $this->createMock(ExceptionReporter::class); - $this->manager = new UnitOfWorkManager($this->unitOfWork, $reporter); - $ex = new LogicException('Boom!'); $sequence = []; $count = 0; - $reporter - ->expects($this->exactly(2)) - ->method('report') - ->with($this->identicalTo($ex)); - $before = [ function () use (&$sequence): void { $sequence[] = 'before1'; @@ -460,6 +439,7 @@ function () use (&$sequence): void { 'after1', 'after2', ], $sequence); + $this->assertSame([$ex, $ex], $this->reporter->reported); } #[Test] @@ -469,7 +449,7 @@ public function it_fails_if_before_callbacks_are_queued_before_transaction(): vo ->expects($this->never()) ->method('execute'); - $this->expectException(RuntimeException::class); + $this->expectException(ApplicationException::class); $this->expectExceptionMessage('Cannot queue a before commit callback when not executing a unit of work.'); $this->manager->beforeCommit(fn () => null); @@ -482,7 +462,7 @@ public function it_fails_if_after_callbacks_are_queued_before_transaction(): voi ->expects($this->never()) ->method('execute'); - $this->expectException(RuntimeException::class); + $this->expectException(ApplicationException::class); $this->expectExceptionMessage('Cannot queue an after commit callback when not executing a unit of work.'); $this->manager->afterCommit(fn () => null); @@ -496,7 +476,7 @@ public function it_cannot_start_transaction_within_an_existing_one(): void ->method('execute') ->willReturnCallback(fn (Closure $callback) => $callback()); - $this->expectException(RuntimeException::class); + $this->expectException(ApplicationException::class); $this->expectExceptionMessage( 'Not expecting unit of work manager to start a unit of work within an existing one.', ); @@ -514,7 +494,7 @@ public function it_fails_if_after_commit_callback_registers_before_commit_callba ->method('execute') ->willReturnCallback(fn (Closure $callback) => $callback()); - $this->expectException(RuntimeException::class); + $this->expectException(ApplicationException::class); $this->expectExceptionMessage('Cannot queue a before commit callback as unit of work has been committed.'); $this->manager->execute(function () { @@ -527,9 +507,6 @@ public function it_fails_if_after_commit_callback_registers_before_commit_callba #[Test] public function it_fails_if_attempts_is_not_greater_than_zero(): void { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Attempts must be greater than zero.'); - /** * Simulates an infinite loop if the zero attempts is not rejected. */ @@ -538,7 +515,10 @@ public function it_fails_if_attempts_is_not_greater_than_zero(): void ->method('execute') ->willReturnCallback(fn (Closure $callback) => $callback()); + $this->expectException(ApplicationException::class); + $this->expectExceptionMessage('Attempts must be greater than zero.'); + /** @phpstan-ignore-next-line */ - $this->manager->execute(fn () => throw new \LogicException('Boom!'), 0); + $this->manager->execute(fn () => throw new LogicException('Boom!'), 0); } } diff --git a/tests/Unit/Bus/PsrPipeContainerTest.php b/tests/Unit/Bus/PsrPipeContainerTest.php index eb8fdb77..3c39ab92 100644 --- a/tests/Unit/Bus/PsrPipeContainerTest.php +++ b/tests/Unit/Bus/PsrPipeContainerTest.php @@ -12,10 +12,11 @@ namespace CloudCreativity\Modules\Tests\Unit\Bus; +use CloudCreativity\Modules\Bus\BusException; use CloudCreativity\Modules\Bus\PsrPipeContainer; +use CloudCreativity\Modules\Testing\FakeContainer; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; final class PsrPipeContainerTest extends TestCase { @@ -31,8 +32,15 @@ public function it_resolves_bound_pipes(): void $this->assertSame($a, $container->get('PipeA')); $this->assertSame($b, $container->get('PipeB')); + } + + #[Test] + public function it_fails_to_resolve_an_unbound_pipe(): void + { + $container = new PsrPipeContainer(); + $container->bind('PipeA', fn () => fn () => 1); - $this->expectException(\RuntimeException::class); + $this->expectException(BusException::class); $this->expectExceptionMessage('Unrecognised pipe name: PipeC'); $container->get('PipeC'); @@ -41,24 +49,16 @@ public function it_resolves_bound_pipes(): void #[Test] public function it_falls_back_to_psr_container(): void { - $psrContainer = $this->createMock(ContainerInterface::class); - $a = fn () => 1; - $b = fn () => 2; $c = fn () => 3; + $psrContainer = new FakeContainer(); + $psrContainer->bind('PipeC', fn () => $c); + $container = new PsrPipeContainer($psrContainer); $container->bind('PipeA', fn () => $a); - $container->bind('PipeB', fn () => $b); - - $psrContainer - ->expects($this->once()) - ->method('get') - ->with('PipeC') - ->willReturn($c); $this->assertSame($a, $container->get('PipeA')); - $this->assertSame($b, $container->get('PipeB')); $this->assertSame($c, $container->get('PipeC')); } } diff --git a/tests/Unit/Domain/EntityTest.php b/tests/Unit/Domain/EntityTest.php index 77d8cb10..fb6d6d6b 100644 --- a/tests/Unit/Domain/EntityTest.php +++ b/tests/Unit/Domain/EntityTest.php @@ -13,8 +13,6 @@ namespace CloudCreativity\Modules\Tests\Unit\Domain; use CloudCreativity\Modules\Contracts\Domain\Entity; -use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; -use CloudCreativity\Modules\Domain\IsEntity; use CloudCreativity\Modules\Toolkit\Identifiers\Guid; use CloudCreativity\Modules\Toolkit\Identifiers\IntegerId; use PHPUnit\Framework\Attributes\Test; @@ -36,19 +34,8 @@ public function it_has_an_id(): void #[Test] public function it_is_the_same(): void { - $a = new TestEntity( - $id1 = $this->createMock(Identifier::class), - ); - - $b = new TestEntity( - $id2 = $this->createStub(Identifier::class), - ); - - $id1 - ->expects($this->exactly(2)) - ->method('is') - ->with($this->identicalTo($id2)) - ->willReturn(true); + $a = new TestEntity(new IntegerId(1)); + $b = new TestEntity(new IntegerId(1)); $this->assertTrue($a->is($b)); $this->assertFalse($a->isNot($b)); @@ -57,19 +44,8 @@ public function it_is_the_same(): void #[Test] public function it_is_not_the_same(): void { - $a = new TestEntity( - $id1 = $this->createMock(Identifier::class), - ); - - $b = new TestEntity( - $id2 = $this->createStub(Identifier::class), - ); - - $id1 - ->expects($this->exactly(2)) - ->method('is') - ->with($this->identicalTo($id2)) - ->willReturn(false); + $a = new TestEntity(new IntegerId(1)); + $b = new TestEntity(new IntegerId(2)); $this->assertFalse($a->is($b)); $this->assertTrue($a->isNot($b)); @@ -78,16 +54,9 @@ public function it_is_not_the_same(): void #[Test] public function it_is_different_class(): void { - $a = new TestEntity( - $id1 = $this->createMock(Identifier::class), - ); - + $a = new TestEntity(new IntegerId(1)); $b = $this->createStub(Entity::class); - $b->method('getId')->willReturn($this->createStub(Identifier::class)); - - $id1 - ->expects($this->never()) - ->method('is'); + $b->method('getId')->willReturn(new IntegerId(1)); $this->assertFalse($a->is($b)); $this->assertTrue($a->isNot($b)); @@ -96,30 +65,19 @@ public function it_is_different_class(): void #[Test] public function it_can_use_trait_on_non_readonly_class(): void { - $id = new IntegerId(123); - - $entity = new class ($id, 'Bob') implements Entity { - use IsEntity; - - public function __construct(Identifier $id, private string $name) - { - $this->id = $id; - } - - public function changeName(string $name): void - { - $this->name = $name; - } - - public function getName(): string - { - return $this->name; - } - }; + $entity = new MutableTestEntity($id = new IntegerId(123), 'Bob'); $this->assertSame($id, $entity->getId()); $this->assertSame('Bob', $entity->getName()); + } + + #[Test] + public function it_can_change_state_on_non_readonly_class(): void + { + $entity = new MutableTestEntity(new IntegerId(123), 'Bob'); + $entity->changeName('Chris'); + $this->assertSame('Chris', $entity->getName()); } } diff --git a/tests/Unit/Domain/EntityWithNullableGuidTest.php b/tests/Unit/Domain/EntityWithNullableGuidTest.php index 51342b2c..14ce36bb 100644 --- a/tests/Unit/Domain/EntityWithNullableGuidTest.php +++ b/tests/Unit/Domain/EntityWithNullableGuidTest.php @@ -13,10 +13,9 @@ namespace CloudCreativity\Modules\Tests\Unit\Domain; use CloudCreativity\Modules\Contracts\Domain\Entity; -use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; use CloudCreativity\Modules\Toolkit\ContractException; use CloudCreativity\Modules\Toolkit\Identifiers\Guid; -use PHPUnit\Framework\Attributes\Depends; +use CloudCreativity\Modules\Toolkit\Identifiers\IntegerId; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -37,7 +36,7 @@ public function it_has_an_id(): void } #[Test] - public function it_has_a_null_id(): TestEntityWithNullableId + public function it_has_a_null_id(): void { $entity = new TestEntityWithNullableId(); @@ -45,25 +44,15 @@ public function it_has_a_null_id(): TestEntityWithNullableId $this->assertFalse($entity->is(null)); $this->assertTrue($entity->isNot(null)); $this->assertFalse($entity->hasId()); - - return $entity; - } - - #[Depends('it_has_a_null_id')] - #[Test] - public function it_fails_to_get_the_id_when_it_is_null(TestEntityWithNullableId $entity): void - { - $this->expectException(\AssertionError::class); - $this->expectExceptionMessage('Entity does not have an identifier.'); - - $entity->getIdOrFail(); } #[Test] public function it_sets_the_id(): void { $entity = new TestEntityWithNullableId(); - $actual = $entity->setId($guid = Guid::fromInteger('SomeType', 99)); + $guid = Guid::fromInteger('SomeType', 99); + + $actual = $entity->setId($guid); $this->assertSame($entity, $actual); $this->assertSame($guid, $entity->getId()); @@ -75,25 +64,16 @@ public function it_cannot_set_the_id_when_the_entity_already_has_one(): void $entity = new TestEntityWithNullableId(Guid::fromInteger('SomeType', 1)); $this->expectException(ContractException::class); + $this->expectExceptionMessage('Cannot set identity as entity already has an identifier.'); + $entity->setId(Guid::fromInteger('SomeType', 2)); } #[Test] public function it_is_the_same(): void { - $a = new TestEntityWithNullableId( - $id1 = $this->createMock(Identifier::class), - ); - - $b = new TestEntityWithNullableId( - $id2 = $this->createStub(Identifier::class), - ); - - $id1 - ->expects($this->exactly(2)) - ->method('is') - ->with($this->identicalTo($id2)) - ->willReturn(true); + $a = new TestEntityWithNullableId(new IntegerId(1)); + $b = new TestEntityWithNullableId(new IntegerId(1)); $this->assertTrue($a->is($b)); $this->assertFalse($a->isNot($b)); @@ -103,34 +83,28 @@ public function it_is_the_same(): void public function it_is_not_the_same_with_null_id(): void { $a = new TestEntityWithNullableId(); + $b = new TestEntityWithNullableId(new IntegerId(1)); - $b = new TestEntityWithNullableId( - $id1 = $this->createMock(Identifier::class), - ); + $this->assertFalse($a->is($b)); + $this->assertTrue($a->isNot($b)); + } - $id1 - ->expects($this->never()) - ->method('is'); + #[Test] + public function it_is_not_the_same_when_other_has_null_id(): void + { + $a = new TestEntityWithNullableId(new IntegerId(1)); + $b = new TestEntityWithNullableId(); $this->assertFalse($a->is($b)); $this->assertTrue($a->isNot($b)); } #[Test] - public function it_is_the_same_when_other_has_null_id(): void + public function it_is_not_the_same_when_both_have_null_ids(): void { - $a = new TestEntityWithNullableId( - $id1 = $this->createMock(Identifier::class), - ); - + $a = new TestEntityWithNullableId(); $b = new TestEntityWithNullableId(); - $id1 - ->expects($this->exactly(2)) - ->method('is') - ->with(null) - ->willReturn(false); - $this->assertFalse($a->is($b)); $this->assertTrue($a->isNot($b)); } @@ -138,19 +112,8 @@ public function it_is_the_same_when_other_has_null_id(): void #[Test] public function it_is_not_the_same(): void { - $a = new TestEntityWithNullableId( - $id1 = $this->createMock(Identifier::class), - ); - - $b = new TestEntityWithNullableId( - $id2 = $this->createStub(Identifier::class), - ); - - $id1 - ->expects($this->exactly(2)) - ->method('is') - ->with($this->identicalTo($id2)) - ->willReturn(false); + $a = new TestEntityWithNullableId(new IntegerId(1)); + $b = new TestEntityWithNullableId(new IntegerId(2)); $this->assertFalse($a->is($b)); $this->assertTrue($a->isNot($b)); @@ -159,16 +122,9 @@ public function it_is_not_the_same(): void #[Test] public function it_is_different_class(): void { - $a = new TestEntityWithNullableId( - $id1 = $this->createMock(Identifier::class), - ); - + $a = new TestEntityWithNullableId(new IntegerId(1)); $b = $this->createStub(Entity::class); - $b->method('getId')->willReturn($this->createStub(Identifier::class)); - - $id1 - ->expects($this->never()) - ->method('is'); + $b->method('getId')->willReturn(new IntegerId(1)); $this->assertFalse($a->is($b)); $this->assertTrue($a->isNot($b)); diff --git a/tests/Unit/Domain/EntityWithTypedIdTest.php b/tests/Unit/Domain/EntityWithTypedIdTest.php index d6bb763f..c37e1c88 100644 --- a/tests/Unit/Domain/EntityWithTypedIdTest.php +++ b/tests/Unit/Domain/EntityWithTypedIdTest.php @@ -13,7 +13,6 @@ namespace CloudCreativity\Modules\Tests\Unit\Domain; use CloudCreativity\Modules\Contracts\Domain\Entity; -use CloudCreativity\Modules\Domain\IsEntityWithTypedId; use CloudCreativity\Modules\Toolkit\Identifiers\IntegerId; use CloudCreativity\Modules\Toolkit\Identifiers\UuidV7; use PHPUnit\Framework\Attributes\Test; @@ -72,24 +71,19 @@ public function it_is_different_class(): void #[Test] public function it_can_use_trait_on_non_readonly_class(): void { - $id = new IntegerId(123); - - $entity = new class ($id, 'Bob') implements Entity { - use IsEntityWithTypedId; - - public function __construct(public IntegerId $id, public private(set) string $name) - { - } - - public function changeName(string $name): void - { - $this->name = $name; - } - }; + $entity = new MutableTestEntityWithTypedId($id = new IntegerId(123), 'Bob'); $this->assertSame($id, $entity->getId()); $this->assertSame('Bob', $entity->name); + } + + #[Test] + public function it_can_change_state_on_non_readonly_class(): void + { + $entity = new MutableTestEntityWithTypedId(new IntegerId(123), 'Bob'); + $entity->changeName('Chris'); + $this->assertSame('Chris', $entity->name); } } diff --git a/tests/Unit/Domain/IdentifierOrEntityTest.php b/tests/Unit/Domain/IdentifierOrEntityTest.php index cd92115a..3ffe0907 100644 --- a/tests/Unit/Domain/IdentifierOrEntityTest.php +++ b/tests/Unit/Domain/IdentifierOrEntityTest.php @@ -13,8 +13,9 @@ namespace CloudCreativity\Modules\Tests\Unit\Domain; use CloudCreativity\Modules\Contracts\Domain\Entity; -use CloudCreativity\Modules\Domain\IdentifierOrEntity; +use CloudCreativity\Modules\Toolkit\ContractException; use CloudCreativity\Modules\Toolkit\Identifiers\Guid; +use CloudCreativity\Modules\Domain\IdentifierOrEntity; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -53,8 +54,16 @@ public function it_is_an_entity_without_guid(): void $this->assertNull($guidOrEntity->id()); $this->assertSame($entity, $guidOrEntity->entity); + } + + #[Test] + public function it_fails_to_get_the_id_when_the_entity_does_not_have_one(): void + { + $entity = $this->createStub(Entity::class); + $entity->method('getId')->willReturn(null); + $guidOrEntity = IdentifierOrEntity::make($entity); - $this->expectException(\LogicException::class); + $this->expectException(ContractException::class); $this->expectExceptionMessage('Entity does not have an identifier.'); $guidOrEntity->idOrFail(); diff --git a/tests/Unit/Domain/MutableTestEntity.php b/tests/Unit/Domain/MutableTestEntity.php new file mode 100644 index 00000000..df19b7ba --- /dev/null +++ b/tests/Unit/Domain/MutableTestEntity.php @@ -0,0 +1,37 @@ +id = $id; + } + + public function changeName(string $name): void + { + $this->name = $name; + } + + public function getName(): string + { + return $this->name; + } +} diff --git a/tests/Unit/Domain/MutableTestEntityWithTypedId.php b/tests/Unit/Domain/MutableTestEntityWithTypedId.php new file mode 100644 index 00000000..8a094a56 --- /dev/null +++ b/tests/Unit/Domain/MutableTestEntityWithTypedId.php @@ -0,0 +1,31 @@ +name = $name; + } +} diff --git a/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php b/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php index eb124256..6a68e688 100644 --- a/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php +++ b/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php @@ -14,22 +14,22 @@ use CloudCreativity\Modules\Contracts\Application\Ports\ExceptionReporter; use CloudCreativity\Modules\Infrastructure\ExceptionReporter\PsrLogExceptionReporter; +use CloudCreativity\Modules\Testing\FakeLogger; use LogicException; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; final class PsrLogExceptionReporterTest extends TestCase { - private LoggerInterface&MockObject $logger; + private FakeLogger $logger; private PsrLogExceptionReporter $reporter; protected function setUp(): void { parent::setUp(); - $this->logger = $this->createMock(LoggerInterface::class); + $this->logger = new FakeLogger(); $this->reporter = new PsrLogExceptionReporter($this->logger); } @@ -39,22 +39,22 @@ protected function tearDown(): void parent::tearDown(); } + #[Test] + public function it_is_an_exception_reporter(): void + { + $this->assertInstanceOf(ExceptionReporter::class, $this->reporter); + } + #[Test] public function it_reports_exception(): void { $exception = new LogicException('Test exception'); - $this->logger - ->expects($this->once()) - ->method('error') - ->with( - $exception->getMessage(), - ['exception' => $exception], - ); - $this->reporter->report($exception); - $this->assertInstanceOf(ExceptionReporter::class, $this->reporter); + $this->assertSame([ + ['level' => LogLevel::ERROR, 'message' => 'Test exception', 'context' => ['exception' => $exception]], + ], $this->logger->log); } #[Test] @@ -62,19 +62,19 @@ public function it_reports_default_message_if_exception_has_empty_message(): voi { $exception = new LogicException(); - $this->logger - ->expects($this->once()) - ->method('error') - ->with( - 'Unexpected error: LogicException', - ['exception' => $exception], - ); - $this->reporter->report($exception); + + $this->assertSame([ + [ + 'level' => LogLevel::ERROR, + 'message' => 'Unexpected error: LogicException', + 'context' => ['exception' => $exception], + ], + ], $this->logger->log); } #[Test] - public function it_logs_context_for_exception_that_implements_context_provider(): void + public function it_logs_context_for_exception_that_has_context_method(): void { $exception = new class ('Boom!') extends LogicException { /** @@ -86,48 +86,31 @@ public function context(): array } }; - $expected = [ - 'foo' => 'bar', - 'exception' => $exception, - ]; - - $this->logger - ->expects($this->once()) - ->method('error') - ->with( - $exception->getMessage(), - $this->identicalTo($expected), - ); - $this->reporter->report($exception); + + $this->assertSame([ + [ + 'level' => LogLevel::ERROR, + 'message' => 'Boom!', + 'context' => ['foo' => 'bar', 'exception' => $exception], + ], + ], $this->logger->log); } #[Test] - public function it_logs_context_for_exception_that_has_context_method(): void + public function it_ignores_context_that_is_not_an_array(): void { $exception = new class ('Boom!') extends LogicException { - /** - * @return array - */ - public function context(): array + public function context(): string { - return ['foo' => 'bar', 'exception' => null]; + return 'not an array'; } }; - $expected = [ - 'foo' => 'bar', - 'exception' => $exception, - ]; - - $this->logger - ->expects($this->once()) - ->method('error') - ->with( - $exception->getMessage(), - $this->identicalTo($expected), - ); - $this->reporter->report($exception); + + $this->assertSame([ + ['level' => LogLevel::ERROR, 'message' => 'Boom!', 'context' => ['exception' => $exception]], + ], $this->logger->log); } } diff --git a/tests/Unit/Infrastructure/Monolog/ContextualProcessorTest.php b/tests/Unit/Infrastructure/Monolog/ContextualProcessorTest.php new file mode 100644 index 00000000..24563e73 --- /dev/null +++ b/tests/Unit/Infrastructure/Monolog/ContextualProcessorTest.php @@ -0,0 +1,210 @@ +createRecord([ + 'foo' => $this->createContextual(['bar' => 'baz']), + 'bat' => 'foobar', + 'nested' => ['value' => $nested = $this->createContextual('blah!')], + ]); + + $processor = new ContextualProcessor(); + $actual = $processor($record); + + $this->assertEquals($record->with(context: [ + 'foo' => ['bar' => 'baz'], + 'bat' => 'foobar', + 'nested' => ['value' => $nested], + ]), $actual); + } + + #[Test] + public function it_does_not_modify_the_exception_value(): void + { + $exception = new LogicException('Boom!'); + $record = $this->createRecord(['exception' => $exception]); + + $processor = new ContextualProcessor(recursive: true); + $actual = $processor($record); + + $this->assertSame(['exception' => $exception], $actual->context); + } + + #[Test] + public function it_does_not_unwrap_a_contextual_exception_value(): void + { + $exception = $this->createContextual('unwrapped'); + $record = $this->createRecord(['exception' => $exception]); + + $processor = new ContextualProcessor(); + $actual = $processor($record); + + $this->assertSame(['exception' => $exception], $actual->context); + } + + #[Test] + public function it_parses_values_using_the_provided_parser(): void + { + $record = $this->createRecord([ + 'foo' => $this->createContextual('bar'), + 'baz' => 'bat', + 'exception' => 'not parsed', + ]); + + $parser = $this->createStub(ValueParser::class); + $parser + ->method('parse') + ->willReturnCallback(fn (mixed $value): mixed => is_string($value) ? strtoupper($value) : $value); + + $processor = new ContextualProcessor(parser: $parser); + $actual = $processor($record); + + $this->assertSame([ + 'foo' => 'BAR', + 'baz' => 'BAT', + 'exception' => 'not parsed', + ], $actual->context); + } + + #[Test] + public function it_recursively_parses_values(): void + { + $record = $this->createRecord([ + 'foo' => $this->createContextual([ + 'b' => $this->createContextual(['y' => 2, 'x' => 1]), + 'a' => 'value', + ]), + 'bar' => ['nested' => $this->createContextual('blah!')], + ]); + + $processor = new ContextualProcessor(recursive: true); + $actual = $processor($record); + + $this->assertSame([ + 'foo' => [ + 'b' => ['y' => 2, 'x' => 1], + 'a' => 'value', + ], + 'bar' => ['nested' => 'blah!'], + ], $actual->context); + } + + #[Test] + public function it_recursively_parses_and_sorts_values(): void + { + $record = $this->createRecord([ + 'foo' => $this->createContextual([ + 'b' => $this->createContextual(['y' => 2, 'x' => 1]), + 'a' => 'value', + ]), + ]); + + $processor = new ContextualProcessor(recursive: true, sorted: true); + $actual = $processor($record); + + $this->assertSame([ + 'foo' => [ + 'a' => 'value', + 'b' => ['x' => 1, 'y' => 2], + ], + ], $actual->context); + } + + #[Test] + public function it_recursively_parses_values_using_the_provided_parser(): void + { + $record = $this->createRecord([ + 'foo' => $this->createContextual(['bar' => 'baz', 'bat' => ['blah']]), + ]); + + $parser = $this->createStub(ValueParser::class); + $parser + ->method('parse') + ->willReturnCallback(fn (mixed $value): mixed => is_string($value) ? strtoupper($value) : $value); + + $processor = new ContextualProcessor(recursive: true, parser: $parser); + $actual = $processor($record); + + $this->assertSame([ + 'foo' => ['bar' => 'BAZ', 'bat' => ['BLAH']], + ], $actual->context); + } + + #[Test] + public function it_does_not_modify_the_rest_of_the_record(): void + { + $record = new LogRecord( + datetime: new DateTimeImmutable('2026-01-01 12:00:00'), + channel: 'my-channel', + level: Level::Warning, + message: 'Hello World!', + context: ['foo' => $this->createContextual('bar')], + extra: ['baz' => 'bat'], + ); + + $processor = new ContextualProcessor(); + $actual = $processor($record); + + $this->assertEquals(new LogRecord( + datetime: new DateTimeImmutable('2026-01-01 12:00:00'), + channel: 'my-channel', + level: Level::Warning, + message: 'Hello World!', + context: ['foo' => 'bar'], + extra: ['baz' => 'bat'], + ), $actual); + } + + /** + * @param array $context + */ + private function createRecord(array $context): LogRecord + { + return new LogRecord( + datetime: new DateTimeImmutable(), + channel: 'test', + level: Level::Debug, + message: 'Test message.', + context: $context, + ); + } + + private function createContextual(mixed $context): Contextual + { + return new readonly class ($context) implements Contextual { + public function __construct(private mixed $value) + { + } + + public function context(): mixed + { + return $this->value; + } + }; + } +} diff --git a/tests/Unit/Infrastructure/Monolog/RecursiveParserTest.php b/tests/Unit/Infrastructure/Monolog/RecursiveParserTest.php new file mode 100644 index 00000000..dde06661 --- /dev/null +++ b/tests/Unit/Infrastructure/Monolog/RecursiveParserTest.php @@ -0,0 +1,223 @@ + + */ + public static function scalarProvider(): array + { + return [ + 'null' => [null], + 'string' => ['foo'], + 'int' => [42], + 'float' => [1.5], + 'bool' => [true], + ]; + } + + #[DataProvider('scalarProvider')] + #[Test] + public function it_returns_non_iterable_values_unchanged(mixed $value): void + { + $parser = new RecursiveParser(); + + $actual = $parser->parse($value); + + $this->assertSame($value, $actual); + } + + #[Test] + public function it_returns_a_non_iterable_object_unchanged(): void + { + $value = new stdClass(); + $parser = new RecursiveParser(); + + $actual = $parser->parse($value); + + $this->assertSame($value, $actual); + } + + #[Test] + public function it_parses_a_contextual_value(): void + { + $value = $this->createContextual('foo'); + $parser = new RecursiveParser(); + + $actual = $parser->parse($value); + + $this->assertSame('foo', $actual); + } + + #[Test] + public function it_parses_a_contextual_value_that_returns_a_contextual_value(): void + { + $value = $this->createContextual($this->createContextual(['foo' => 'bar'])); + $parser = new RecursiveParser(); + + $actual = $parser->parse($value); + + $this->assertSame(['foo' => 'bar'], $actual); + } + + #[Test] + public function it_recursively_parses_iterable_values(): void + { + $value = [ + 'foo' => $this->createContextual(['bar' => $this->createContextual('baz')]), + 'bat' => new ArrayIterator(['a', $this->createContextual('b')]), + 'blah' => ['c', 'd'], + ]; + + $parser = new RecursiveParser(); + + $actual = $parser->parse($value); + + $this->assertSame([ + 'foo' => ['bar' => 'baz'], + 'bat' => ['a', 'b'], + 'blah' => ['c', 'd'], + ], $actual); + } + + #[Test] + public function it_converts_a_generator_to_an_array(): void + { + $value = (function (): Generator { + yield 'foo' => 'bar'; + yield 'baz' => $this->createContextual('bat'); + })(); + + $parser = new RecursiveParser(); + + $actual = $parser->parse($value); + + $this->assertSame(['foo' => 'bar', 'baz' => 'bat'], $actual); + } + + #[Test] + public function it_skips_iterable_values_that_do_not_have_string_or_integer_keys(): void + { + $value = (function (): Generator { + yield 'foo' => 'bar'; + yield new stdClass() => 'skipped'; + yield 1.5 => 'also skipped'; + yield 99 => 'baz'; + })(); + + $parser = new RecursiveParser(); + + $actual = $parser->parse($value); + + $this->assertSame(['foo' => 'bar', 99 => 'baz'], $actual); + } + + #[Test] + public function it_does_not_sort_by_default(): void + { + $value = ['b' => ['z' => 1, 'y' => 2], 'a' => 3]; + $parser = new RecursiveParser(); + + $actual = $parser->parse($value); + + $this->assertSame(['b' => ['z' => 1, 'y' => 2], 'a' => 3], $actual); + } + + #[Test] + public function it_recursively_sorts_by_key(): void + { + $value = [ + 'b' => ['z' => 1, 'y' => 2], + 'a' => $this->createContextual(['d' => 4, 'c' => 3]), + ]; + + $parser = new RecursiveParser(sorted: true); + + $actual = $parser->parse($value); + + $this->assertSame([ + 'a' => ['c' => 3, 'd' => 4], + 'b' => ['y' => 2, 'z' => 1], + ], $actual); + } + + #[Test] + public function it_uses_the_inner_parser_for_non_iterable_values(): void + { + $value = [ + 'foo' => 'bar', + 'baz' => ['bat' => $this->createContextual('blah')], + 'int' => 1, + ]; + + $inner = $this->createStub(ValueParser::class); + $inner + ->method('parse') + ->willReturnCallback(fn (mixed $value): mixed => is_string($value) ? strtoupper($value) : $value); + + $parser = new RecursiveParser(innerParser: $inner); + + $actual = $parser->parse($value); + + $this->assertSame([ + 'foo' => 'BAR', + 'baz' => ['bat' => 'BLAH'], + 'int' => 1, + ], $actual); + } + + #[Test] + public function it_does_not_pass_iterable_values_to_the_inner_parser(): void + { + $value = ['foo' => ['bar' => 'baz']]; + + $inner = $this->createMock(ValueParser::class); + $inner + ->expects($this->once()) + ->method('parse') + ->with('baz') + ->willReturn('BAZ'); + + $parser = new RecursiveParser(innerParser: $inner); + + $actual = $parser->parse($value); + + $this->assertSame(['foo' => ['bar' => 'BAZ']], $actual); + } + + private function createContextual(mixed $context): Contextual + { + return new readonly class ($context) implements Contextual { + public function __construct(private mixed $value) + { + } + + public function context(): mixed + { + return $this->value; + } + }; + } +} diff --git a/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php b/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php index fd7ad3d2..f0f6cf96 100644 --- a/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php +++ b/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php @@ -15,6 +15,9 @@ use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer as IPipeContainer; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\ClosurePublisher; +use CloudCreativity\Modules\Testing\FakeContainer; +use CloudCreativity\Modules\Toolkit\Pipeline\PipeContainer; +use CloudCreativity\Modules\Toolkit\Pipeline\Through; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; @@ -66,12 +69,8 @@ public function it_publishes_an_event_through_middleware(): void return $next($event4); }; - $middleware = $this->createMock(IPipeContainer::class); - $middleware - ->expects($this->once()) - ->method('get') - ->with('MySecondMiddleware') - ->willReturn($middleware2); + $middleware = new PipeContainer(); + $middleware->bind('MySecondMiddleware', fn () => $middleware2); $publisher = $this->createPublisher($middleware); $publisher->through([ @@ -102,12 +101,8 @@ public function it_publishes_through_middleware_resolved_from_a_psr_container(): return $next($event3); }; - $psrContainer = $this->createMock(ContainerInterface::class); - $psrContainer - ->expects($this->once()) - ->method('get') - ->with('MySecondMiddleware') - ->willReturn($middleware2); + $psrContainer = new FakeContainer(); + $psrContainer->instance('MySecondMiddleware', $middleware2); $publisher = $this->createPublisher($psrContainer); $publisher->through([ @@ -120,7 +115,6 @@ public function it_publishes_through_middleware_resolved_from_a_psr_container(): $this->assertSame([$event3], $this->actual); } - #[Test] public function it_publishes_using_the_handler_bound_to_the_event_class(): void { @@ -147,6 +141,30 @@ function (TestOutboundEvent $in) use (&$actual) { $this->assertSame($expected, $actual); } + #[Test] + public function it_publishes_through_middleware_from_the_through_attribute(): void + { + $event1 = $this->createStub(IntegrationEvent::class); + $event2 = $this->createStub(IntegrationEvent::class); + + $middleware = new PipeContainer(); + $middleware->bind('MyMiddleware', fn () => function ($event, \Closure $next) use ($event1, $event2) { + $this->assertSame($event1, $event); + return $next($event2); + }); + + $publisher = new #[Through('MyMiddleware')] class ( + function (IntegrationEvent $event): void { + $this->actual[] = $event; + }, + $middleware, + ) extends ClosurePublisher {}; + + $publisher->publish($event1); + + $this->assertSame([$event2], $this->actual); + } + private function createPublisher(ContainerInterface|IPipeContainer|null $middleware = null): ClosurePublisher { return new class ( diff --git a/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php b/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php index e50b2b2e..dd31c0e5 100644 --- a/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php +++ b/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php @@ -14,114 +14,198 @@ use Closure; use CloudCreativity\Modules\Contracts\Infrastructure\OutboundEventBus\PublisherHandler; -use CloudCreativity\Modules\Contracts\Infrastructure\OutboundEventBus\PublisherHandlerContainer; -use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use CloudCreativity\Modules\Contracts\Infrastructure\OutboundEventBus\PublisherHandlerContainer as IPublisherHandlerContainer; +use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; +use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer as IPipeContainer; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\ComponentPublisher; +use CloudCreativity\Modules\Infrastructure\OutboundEventBus\PublisherHandlerContainer; +use CloudCreativity\Modules\Testing\FakeContainer; +use CloudCreativity\Modules\Toolkit\Pipeline\PipeContainer; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; final class ComponentPublisherTest extends TestCase { - /** - * @var MockObject&PublisherHandlerContainer - */ - private PublisherHandlerContainer $handlers; - - private MockObject&PipeContainer $middleware; - - private ComponentPublisher $publisher; - /** * @var array */ private array $sequence = []; - protected function setUp(): void - { - parent::setUp(); - - $this->publisher = new class ( - handlers: $this->handlers = $this->createMock(PublisherHandlerContainer::class), - middleware: $this->middleware = $this->createMock(PipeContainer::class), - ) extends ComponentPublisher {}; - } - protected function tearDown(): void { - unset($this->publisher, $this->handlers, $this->middleware); + unset($this->sequence); parent::tearDown(); } #[Test] public function it_publishes_an_event(): void { - $event = new class () extends TestOutboundEvent {}; - - $this->handlers - ->expects($this->once()) - ->method('get') - ->with($event::class) - ->willReturn($handler = $this->createMock(PublisherHandler::class)); - - $handler - ->expects($this->once()) - ->method('__invoke') - ->with($this->identicalTo($event)); + $event = new TestNamedOutboundEvent(); + $handler = $this->createRecordingPublisher(); + $handlers = new PublisherHandlerContainer(); + $handlers->bind(TestNamedOutboundEvent::class, fn () => $handler); + $publisher = new class ( + handlers: $handlers, + middleware: new PipeContainer(), + ) extends ComponentPublisher {}; - $this->middleware - ->expects($this->never()) - ->method($this->anything()); + $publisher->publish($event); - $this->publisher->publish($event); + $this->assertSame([$event], $handler->published); } #[Test] public function it_publishes_an_event_through_middleware(): void { - $event1 = new class () extends TestOutboundEvent {}; - $event2 = new class () extends TestOutboundEvent {}; - $event3 = new class () extends TestOutboundEvent {}; + $event1 = new TestNamedOutboundEvent('one'); + $event2 = new TestNamedOutboundEvent('two'); + $event3 = new TestNamedOutboundEvent('three'); + $handler = $this->createRecordingPublisher(); + $handlers = new PublisherHandlerContainer(default: fn () => $handler); - $middleware1 = function ($actual, Closure $next) use ($event1, $event2): void { + $middleware1 = function (IntegrationEvent $actual, Closure $next) use ($event1, $event2): void { $this->assertSame($event1, $actual); $this->sequence[] = 'before1'; $next($event2); $this->sequence[] = 'after1'; }; - $middleware2 = function ($actual, Closure $next) use ($event2, $event3): void { + $middleware2 = function (IntegrationEvent $actual, Closure $next) use ($event2, $event3): void { $this->assertSame($event2, $actual); $this->sequence[] = 'before2'; $next($event3); $this->sequence[] = 'after2'; }; - $this->middleware - ->expects($this->once()) + $middleware = new PipeContainer(); + $middleware->bind('Middleware2', fn () => $middleware2); + + $publisher = new class ( + handlers: $handlers, + middleware: $middleware, + ) extends ComponentPublisher {}; + $publisher->through([$middleware1, 'Middleware2']); + + $publisher->publish($event1); + + $this->assertSame([$event3], $handler->published); + $this->assertSame(['before1', 'before2', 'published', 'after2', 'after1'], $this->sequence); + } + + #[Test] + public function it_publishes_via_a_publisher_bound_with_an_attribute(): void + { + $event = new TestNamedOutboundEvent(); + $publisher = new TestComponentPublisherWithAttributes($this->createContainer( + $bound = $this->createRecordingPublisher(), + $default = $this->createRecordingPublisher(), + )); + + $publisher->publish($event); + + $this->assertSame([$event], $bound->published); + $this->assertSame([], $default->published); + } + + #[Test] + public function it_publishes_via_the_default_publisher_bound_with_an_attribute(): void + { + $event = new class () extends TestOutboundEvent {}; + $publisher = new TestComponentPublisherWithAttributes($this->createContainer( + $bound = $this->createRecordingPublisher(), + $default = $this->createRecordingPublisher(), + )); + + $publisher->publish($event); + + $this->assertSame([], $bound->published); + $this->assertSame([$event], $default->published); + } + + #[Test] + public function it_publishes_through_middleware_from_the_through_attribute(): void + { + $publisher = new TestComponentPublisherWithAttributes($this->createContainer( + $this->createRecordingPublisher(), + $this->createRecordingPublisher(), + )); + + $publisher->publish(new TestNamedOutboundEvent()); + + $this->assertSame(['before1', 'before2', 'published', 'after2', 'after1'], $this->sequence); + } + + #[Test] + public function it_does_not_autowire_publisher_attributes_when_given_a_handler_container(): void + { + $event = new TestNamedOutboundEvent(); + $handlers = $this->createMock(IPublisherHandlerContainer::class); + $middleware = $this->createMock(IPipeContainer::class); + $publisher = new TestComponentPublisherWithAttributes($handlers, $middleware); + + $middleware + ->expects($this->exactly(2)) ->method('get') - ->with('Middleware2') - ->willReturn($middleware2); + ->willReturnCallback(fn (string $name): Closure => match ($name) { + 'Middleware1', 'Middleware2' => fn (IntegrationEvent $e, Closure $next) => $next($e), + default => $this->fail('Unexpected middleware: ' . $name), + }); - $handler = $this->createMock(PublisherHandler::class); + $handlers + ->expects($this->once()) + ->method('get') + ->with($event::class) + ->willReturn($handler = $this->createMock(PublisherHandler::class)); $handler ->expects($this->once()) ->method('__invoke') - ->with($this->identicalTo($event3)); + ->with($this->identicalTo($event)); - $this->handlers - ->expects($this->once()) - ->method('get') - ->with($event3::class) - ->willReturnCallback(function () use ($handler) { - $this->assertSame(['before1', 'before2'], $this->sequence); - return $handler; - }); + $publisher->publish($event); + } + + private function createContainer(TestPublisher $bound, TestPublisher $default): FakeContainer + { + $container = new FakeContainer(); + $container->instance(TestPublisher::class, $bound); + $container->instance('DefaultPublisher', $default); + $container->instance('Middleware1', function (IntegrationEvent $event, Closure $next): void { + $this->sequence[] = 'before1'; + $next($event); + $this->sequence[] = 'after1'; + }); + $container->instance('Middleware2', function (IntegrationEvent $event, Closure $next): void { + $this->sequence[] = 'before2'; + $next($event); + $this->sequence[] = 'after2'; + }); - $this->publisher->through([$middleware1, 'Middleware2']); - $this->publisher->publish($event1); + return $container; + } - $this->assertSame(['before1', 'before2', 'after2', 'after1'], $this->sequence); + /** + * @return object{published: list}&TestPublisher + */ + private function createRecordingPublisher(): TestPublisher + { + return new class (function (): void { + $this->sequence[] = 'published'; + }) extends TestPublisher { + /** + * @var list + */ + public array $published = []; + + public function __construct(private readonly Closure $onPublish) + { + } + + public function publish(TestOutboundEvent $event): void + { + $this->published[] = $event; + ($this->onPublish)(); + } + }; } } diff --git a/tests/Unit/Infrastructure/OutboundEventBus/Middleware/LogOutboundEventTest.php b/tests/Unit/Infrastructure/OutboundEventBus/Middleware/LogOutboundEventTest.php new file mode 100644 index 00000000..2cba3857 --- /dev/null +++ b/tests/Unit/Infrastructure/OutboundEventBus/Middleware/LogOutboundEventTest.php @@ -0,0 +1,123 @@ +logger = new FakeLogger(); + $this->event = new TestNamedOutboundEvent(name: 'bar'); + } + + protected function tearDown(): void + { + unset($this->logger, $this->event); + parent::tearDown(); + } + + #[Test] + public function it_logs_with_the_default_levels(): void + { + $passed = null; + $middleware = new LogOutboundEvent($this->logger); + + $middleware($this->event, function (IntegrationEvent $event) use (&$passed): void { + $passed = $event; + }); + + $context = ['event' => [ + 'name' => 'bar', + 'uuid' => $this->event->uuid, + 'occurredAt' => $this->event->occurredAt, + ]]; + + $this->assertSame($this->event, $passed); + $this->assertEquals([ + ['level' => LogLevel::DEBUG, 'message' => 'Publishing integration event Tests:TestNamedOutboundEvent.', 'context' => $context], + ['level' => LogLevel::INFO, 'message' => 'Published integration event Tests:TestNamedOutboundEvent.', 'context' => $context], + ], $this->logger->log); + } + + #[Test] + public function it_logs_with_custom_levels(): void + { + $middleware = new LogOutboundEvent($this->logger, LogLevel::NOTICE, LogLevel::WARNING); + + $middleware($this->event, function (): void { + }); + + $this->assertSame([ + 'NOTICE: Publishing integration event Tests:TestNamedOutboundEvent.', + 'WARNING: Published integration event Tests:TestNamedOutboundEvent.', + ], $this->logger->messages()); + } + + #[Test] + public function it_uses_the_fully_qualified_class_name_when_there_is_no_module_basename(): void + { + $event = new class () extends TestOutboundEvent {}; + $name = $event::class; + $middleware = new LogOutboundEvent($this->logger); + + $middleware($event, function (): void { + }); + + $this->assertSame([ + "DEBUG: Publishing integration event {$name}.", + "INFO: Published integration event {$name}.", + ], $this->logger->messages()); + } + + #[Test] + public function it_logs_before_the_next_closure_is_invoked(): void + { + $messages = null; + $middleware = new LogOutboundEvent($this->logger); + + $middleware($this->event, function () use (&$messages): void { + $messages = $this->logger->messages(); + }); + + $this->assertSame(['DEBUG: Publishing integration event Tests:TestNamedOutboundEvent.'], $messages); + } + + #[Test] + public function it_rethrows_an_exception_thrown_by_the_next_closure(): void + { + $middleware = new LogOutboundEvent($this->logger); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Boom!'); + + $middleware($this->event, static function (): never { + throw new LogicException('Boom!'); + }); + } +} diff --git a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php index 5dc09671..583c1f1e 100644 --- a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php +++ b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php @@ -12,114 +12,213 @@ namespace CloudCreativity\Modules\Tests\Unit\Infrastructure\OutboundEventBus; +use CloudCreativity\Modules\Infrastructure\InfrastructureException; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\PublisherHandler; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\PublisherHandlerContainer; +use CloudCreativity\Modules\Testing\FakeContainer; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; -use RuntimeException; final class PublisherHandlerContainerTest extends TestCase { #[Test] - public function it_publishes_via_bindings_without_default_handler(): void + public function it_gets_a_handler_bound_with_a_closure(): void { - $a = new class () extends TestPublisher {}; - $b = $this->createStub(TestPublisher::class); + $publisher = new class () extends TestPublisher {}; + $container = new PublisherHandlerContainer(); + $container->bind(TestNamedOutboundEvent::class, fn () => $publisher); - $event1 = new class () extends TestOutboundEvent {}; - $event2 = new class () extends TestOutboundEvent {}; - $event3 = new class () extends TestOutboundEvent {}; + $actual = $container->get(TestNamedOutboundEvent::class); - $container = new PublisherHandlerContainer(); - $container->bind($event1::class, fn () => $a); - $container->bind($event2::class, fn () => $b); + $this->assertEquals(new PublisherHandler($publisher), $actual); + } + + #[Test] + public function it_gets_the_closure_default_handler_when_the_event_is_not_bound(): void + { + $default = new class () extends TestPublisher {}; + $container = new PublisherHandlerContainer(default: fn () => $default); + + $actual = $container->get(TestNamedOutboundEvent::class); + + $this->assertEquals(new PublisherHandler($default), $actual); + } + + #[Test] + public function it_prefers_a_closure_binding_over_the_default_handler(): void + { + $bound = new class () extends TestPublisher {}; + $container = new PublisherHandlerContainer(default: fn () => $this->fail('Default handler resolved.')); + $container->bind(TestNamedOutboundEvent::class, fn () => $bound); + + $actual = $container->get(TestNamedOutboundEvent::class); + + $this->assertEquals(new PublisherHandler($bound), $actual); + } + + #[Test] + public function it_gets_a_handler_bound_with_a_string_from_the_psr_container(): void + { + $publisher = new class () extends TestPublisher {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance(TestPublisher::class, $publisher); + $container = new PublisherHandlerContainer(container: $psrContainer); + $container->bind(TestNamedOutboundEvent::class, TestPublisher::class); + + $actual = $container->get(TestNamedOutboundEvent::class); - $this->assertEquals(new PublisherHandler($a), $container->get($event1::class)); - $this->assertEquals(new PublisherHandler($b), $container->get($event2::class)); + $this->assertEquals(new PublisherHandler($publisher), $actual); + } - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('No handler bound for integration event: ' . $event3::class); + #[Test] + public function it_gets_the_psr_container_default_handler_when_the_event_is_not_bound(): void + { + $default = new class () extends TestPublisher {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance('DefaultPublisher', $default); + $container = new PublisherHandlerContainer(default: 'DefaultPublisher', container: $psrContainer); - $container->get($event3::class); + $actual = $container->get(TestNamedOutboundEvent::class); + + $this->assertEquals(new PublisherHandler($default), $actual); } #[Test] - public function it_publishes_via_bindings_with_default_handler(): void + public function it_prefers_a_psr_container_binding_over_the_default_handler(): void { - $a = new class () extends TestPublisher {}; - $b = $this->createStub(TestPublisher::class); + $bound = new class () extends TestPublisher {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance(TestPublisher::class, $bound); + $psrContainer->bind('DefaultPublisher', fn () => $this->fail('Default handler resolved.')); + $container = new PublisherHandlerContainer(default: 'DefaultPublisher', container: $psrContainer); + $container->bind(TestNamedOutboundEvent::class, TestPublisher::class); + + $actual = $container->get(TestNamedOutboundEvent::class); - $event1 = new class () extends TestOutboundEvent {}; - $event2 = new class () extends TestOutboundEvent {}; - $event3 = new class () extends TestOutboundEvent {}; + $this->assertEquals(new PublisherHandler($bound), $actual); + } - $container = new PublisherHandlerContainer(default: fn () => $b); - $container->bind($event1::class, fn () => $a); + #[Test] + public function it_throws_when_the_default_handler_is_a_string_without_a_psr_container(): void + { + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage( + 'Cannot bind default event publisher handler as a string without a PSR container.', + ); - $this->assertEquals(new PublisherHandler($a), $container->get($event1::class)); - $this->assertEquals($default = new PublisherHandler($b), $container->get($event2::class)); - $this->assertEquals($default, $container->get($event3::class)); + new PublisherHandlerContainer(default: TestPublisher::class); } #[Test] - public function it_publishes_via_psr_container_without_default_handler(): void + public function it_throws_when_binding_a_string_without_a_psr_container(): void { - $a = new class () extends TestPublisher {}; - $b = $this->createStub(TestPublisher::class); + $container = new PublisherHandlerContainer(); - $event1 = new class () extends TestOutboundEvent {}; - $event2 = new class () extends TestOutboundEvent {}; - $event3 = new class () extends TestOutboundEvent {}; + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('Cannot bind event publisher handler as a string without a PSR container.'); - $psrContainer = $this->createMock(ContainerInterface::class); - $psrContainer - ->expects($this->exactly(2)) - ->method('get') - ->willReturnCallback(fn (string $id) => match ($id) { - $a::class => $a, - $b::class => $b, - default => $this->fail('Unexpected container id: ' . $id), - }); + $container->bind(TestNamedOutboundEvent::class, TestPublisher::class); + } + #[Test] + public function it_throws_when_there_is_no_binding_and_no_default_handler(): void + { + $container = new PublisherHandlerContainer(); + $container->bind(TestOutboundEvent::class, fn () => new class () extends TestPublisher {}); + + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('No handler bound for integration event: ' . TestNamedOutboundEvent::class); + + $container->get(TestNamedOutboundEvent::class); + } + + #[Test] + public function it_throws_when_there_is_no_binding_and_no_default_handler_in_the_psr_container(): void + { + $psrContainer = new FakeContainer(); + $psrContainer->instance(TestPublisher::class, new class () extends TestPublisher {}); $container = new PublisherHandlerContainer(container: $psrContainer); - $container->bind($event1::class, $a::class); - $container->bind($event2::class, $b::class); + $container->bind(TestOutboundEvent::class, TestPublisher::class); + + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('No handler bound for integration event: ' . TestNamedOutboundEvent::class); + + $container->get(TestNamedOutboundEvent::class); + } + + #[Test] + public function it_uses_a_closure_default_handler_set_after_construction(): void + { + $default = new class () extends TestPublisher {}; + $container = new PublisherHandlerContainer(); - $this->assertEquals(new PublisherHandler($a), $container->get($event1::class)); - $this->assertEquals(new PublisherHandler($b), $container->get($event2::class)); + $container->withDefault(fn () => $default); + $actual = $container->get(TestNamedOutboundEvent::class); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('No handler bound for integration event: ' . $event3::class); + $this->assertEquals(new PublisherHandler($default), $actual); + } - $container->get($event3::class); + #[Test] + public function it_uses_a_psr_container_default_handler_set_after_construction(): void + { + $default = new class () extends TestPublisher {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance(TestPublisher::class, $default); + $container = new PublisherHandlerContainer(container: $psrContainer); + + $container->withDefault(TestPublisher::class); + $actual = $container->get(TestNamedOutboundEvent::class); + + $this->assertEquals(new PublisherHandler($default), $actual); } #[Test] - public function it_publishes_via_psr_container_with_default_handler(): void + public function it_prefers_a_binding_over_a_default_handler_set_after_construction(): void { - $a = new class () extends TestPublisher {}; - $b = $this->createStub(TestPublisher::class); + $bound = new class () extends TestPublisher {}; + $default = new class () extends TestPublisher {}; + $container = new PublisherHandlerContainer(); + $container->bind(TestNamedOutboundEvent::class, fn () => $bound); - $event1 = new class () extends TestOutboundEvent {}; - $event2 = new class () extends TestOutboundEvent {}; - $event3 = new class () extends TestOutboundEvent {}; + $container->withDefault(fn () => $default); + $actual = $container->get(TestNamedOutboundEvent::class); - $psrContainer = $this->createMock(ContainerInterface::class); - $psrContainer - ->expects($this->exactly(3)) - ->method('get') - ->willReturnCallback(fn (string $id) => match ($id) { - $a::class => $a, - $b::class => $b, - default => $this->fail('Unexpected container id: ' . $id), - }); + $this->assertEquals(new PublisherHandler($bound), $actual); + } + + #[Test] + public function it_throws_when_the_default_handler_is_already_set_via_the_constructor(): void + { + $container = new PublisherHandlerContainer(default: fn () => new class () extends TestPublisher {}); + + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('Default event publisher handler is already set.'); + + $container->withDefault(fn () => new class () extends TestPublisher {}); + } + + #[Test] + public function it_throws_when_the_default_handler_is_already_set_via_with_default(): void + { + $container = new PublisherHandlerContainer(); + $container->withDefault(fn () => new class () extends TestPublisher {}); + + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('Default event publisher handler is already set.'); + + $container->withDefault(fn () => new class () extends TestPublisher {}); + } + + #[Test] + public function it_throws_when_setting_a_string_default_handler_without_a_psr_container(): void + { + $container = new PublisherHandlerContainer(); - $container = new PublisherHandlerContainer(default: $b::class, container: $psrContainer); - $container->bind($event1::class, $a::class); + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage( + 'Cannot bind default event publisher handler as a string without a PSR container.', + ); - $this->assertEquals(new PublisherHandler($a), $container->get($event1::class)); - $this->assertEquals($default = new PublisherHandler($b), $container->get($event2::class)); - $this->assertEquals($default, $container->get($event3::class)); + $container->withDefault(TestPublisher::class); } } diff --git a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php index 3f2e52e2..fed11041 100644 --- a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php +++ b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php @@ -20,19 +20,32 @@ final class PublisherHandlerTest extends TestCase { #[Test] - public function it_publishes_the_event_via_the_inner_publisher(): void + public function it_is_a_publisher_handler(): void { - $event = new class () extends TestOutboundEvent {}; - $innerHandler = $this->createMock(TestPublisher::class); + $handler = new PublisherHandler(new class () extends TestPublisher {}); - $innerHandler - ->expects($this->once()) - ->method('publish') - ->with($this->identicalTo($event)); + $this->assertInstanceOf(IPublisherHandler::class, $handler); + } + #[Test] + public function it_publishes_the_event_via_the_inner_publisher(): void + { + $event = new class () extends TestOutboundEvent {}; + $innerHandler = new class () extends TestPublisher { + /** + * @var list + */ + public array $published = []; + + public function publish(TestOutboundEvent $event): void + { + $this->published[] = $event; + } + }; $handler = new PublisherHandler($innerHandler); + $handler($event); - $this->assertInstanceOf(IPublisherHandler::class, $handler); + $this->assertSame([$event], $innerHandler->published); } } diff --git a/tests/Unit/Infrastructure/OutboundEventBus/TestComponentPublisherWithAttributes.php b/tests/Unit/Infrastructure/OutboundEventBus/TestComponentPublisherWithAttributes.php new file mode 100644 index 00000000..77e8f8e0 --- /dev/null +++ b/tests/Unit/Infrastructure/OutboundEventBus/TestComponentPublisherWithAttributes.php @@ -0,0 +1,25 @@ +queue = $this->createQueue($this->createStub(PipeContainer::class)); - } - protected function tearDown(): void { - unset($this->queue, $this->actual); + unset($this->actual); parent::tearDown(); } @@ -45,8 +38,9 @@ protected function tearDown(): void public function it_queues_a_command(): void { $command = $this->createStub(Command::class); + $queue = $this->createQueue(); - $this->queue->push($command); + $queue->push($command); $this->assertSame([$command], $this->actual); } @@ -74,22 +68,17 @@ public function it_queues_a_command_through_middleware(): void return $next($command4); }; - $middleware = $this->createMock(PipeContainer::class); - $middleware - ->expects($this->once()) - ->method('get') - ->with('MySecondMiddleware') - ->willReturn($middleware2); - - $this->queue = $this->createQueue($middleware); + $middleware = new PipeContainer(); + $middleware->bind('MySecondMiddleware', fn () => $middleware2); - $this->queue->through([ + $queue = $this->createQueue($middleware); + $queue->through([ $middleware1, 'MySecondMiddleware', $middleware3, ]); - $this->queue->push($command1); + $queue->push($command1); $this->assertSame([$command4], $this->actual); } @@ -100,25 +89,50 @@ public function it_queues_using_the_handler_bound_to_the_command_class(): void $expected = new TestCommand(); $stub = $this->createStub(Command::class); $actual = null; + $queue = $this->createQueue(); - $this->queue->bind($stub::class, function (Command $cmd): never { + $queue->bind($stub::class, function (Command $cmd): never { $this->fail('Not expecting this closure to be called.'); }); - $this->queue->bind( + $queue->bind( TestCommand::class, function (TestCommand $cmd) use (&$actual) { $actual = $cmd; }, ); - $this->queue->push($expected); + $queue->push($expected); $this->assertEmpty($this->actual); $this->assertSame($expected, $actual); } - private function createQueue(PipeContainer $middleware): ClosureQueue + #[Test] + public function it_queues_through_middleware_from_the_through_attribute_resolved_from_a_psr_container(): void + { + $command1 = new TestCommand(); + $command2 = new TestCommand(); + + $container = new FakeContainer(); + $container->instance('MyMiddleware', function ($command, \Closure $next) use ($command1, $command2) { + $this->assertSame($command1, $command); + return $next($command2); + }); + + $queue = new #[Through('MyMiddleware')] class ( + function (Command $command): void { + $this->actual[] = $command; + }, + $container, + ) extends ClosureQueue {}; + + $queue->push($command1); + + $this->assertSame([$command2], $this->actual); + } + + private function createQueue(?PipeContainer $middleware = null): ClosureQueue { return new class ( function (Command $command): void { diff --git a/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php b/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php index f40dc45e..98d41d77 100644 --- a/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php +++ b/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php @@ -13,111 +13,215 @@ namespace CloudCreativity\Modules\Tests\Unit\Infrastructure\Queue; use CloudCreativity\Modules\Contracts\Infrastructure\Queue\Enqueuer; -use CloudCreativity\Modules\Contracts\Infrastructure\Queue\EnqueuerContainer; +use CloudCreativity\Modules\Contracts\Infrastructure\Queue\EnqueuerContainer as IEnqueuerContainer; use CloudCreativity\Modules\Contracts\Messaging\Command; -use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer as IPipeContainer; use CloudCreativity\Modules\Infrastructure\Queue\ComponentQueue; +use CloudCreativity\Modules\Infrastructure\Queue\EnqueuerContainer; +use CloudCreativity\Modules\Testing\FakeContainer; +use CloudCreativity\Modules\Tests\Unit\Application\Bus\TestCommand; +use CloudCreativity\Modules\Toolkit\Pipeline\PipeContainer; +use Closure; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; final class ComponentQueueTest extends TestCase { - private EnqueuerContainer&MockObject $enqueuers; - - private ComponentQueue $queue; - /** * @var array */ private array $sequence = []; - protected function setUp(): void - { - parent::setUp(); - - $this->queue = new class ( - enqueuers: $this->enqueuers = $this->createMock(EnqueuerContainer::class), - middleware: $this->createStub(PipeContainer::class), - ) extends ComponentQueue {}; - } - protected function tearDown(): void { - unset($this->queue, $this->enqueuers, $this->sequence); + unset($this->sequence); parent::tearDown(); } #[Test] public function it_queues_a_command(): void { - $command = $this->createStub(Command::class); - - $this->enqueuers - ->expects($this->once()) - ->method('get') - ->with($command::class) - ->willReturn($enqueuer = $this->createMock(Enqueuer::class)); + $command = new TestQueueableCommand(); + $enqueuer = $this->createRecordingEnqueuer(); + $enqueuers = new EnqueuerContainer(); + $enqueuers->bind(TestQueueableCommand::class, fn () => $enqueuer); + $queue = new class ( + enqueuers: $enqueuers, + middleware: new PipeContainer(), + ) extends ComponentQueue {}; - $enqueuer - ->expects($this->once()) - ->method('__invoke') - ->with($this->identicalTo($command)); + $queue->push($command); - $this->queue->push($command); + $this->assertSame([$command], $enqueuer->pushed); } #[Test] public function it_queues_through_middleware(): void { - $command1 = $this->createStub(Command::class); - $command2 = $this->createStub(Command::class); - $command3 = $this->createStub(Command::class); - $enqueuer = $this->createMock(Enqueuer::class); + $command1 = new TestQueueableCommand('one'); + $command2 = new TestQueueableCommand('two'); + $command3 = new TestQueueableCommand('three'); + $enqueuer = $this->createRecordingEnqueuer(); + $enqueuers = new EnqueuerContainer(default: fn () => $enqueuer); - $middleware1 = function ($actual, \Closure $next) use ($command1, $command2): void { + $middleware1 = function (Command $actual, Closure $next) use ($command1, $command2): void { $this->assertSame($command1, $actual); $this->sequence[] = 'before1'; $next($command2); $this->sequence[] = 'after1'; }; - $middleware2 = function ($actual, \Closure $next) use ($command2, $command3): void { + $middleware2 = function (Command $actual, Closure $next) use ($command2, $command3): void { $this->assertSame($command2, $actual); $this->sequence[] = 'before2'; $next($command3); $this->sequence[] = 'after2'; }; - $this->enqueuers - ->expects($this->once()) + $middleware = new PipeContainer(); + $middleware->bind('MySecondMiddleware', fn () => $middleware2); + + $queue = new class ( + enqueuers: $enqueuers, + middleware: $middleware, + ) extends ComponentQueue {}; + $queue->through([$middleware1, 'MySecondMiddleware']); + + $queue->push($command1); + + $this->assertSame([$command3], $enqueuer->pushed); + $this->assertSame(['before1', 'before2', 'pushed', 'after2', 'after1'], $this->sequence); + } + + #[Test] + public function it_queues_via_an_enqueuer_bound_with_an_attribute(): void + { + $command = new TestQueueableCommand(); + $queue = new TestComponentQueueWithAttributes($this->createContainer( + $bound = $this->createRecordingEnqueuer(), + $default = $this->createRecordingEnqueuer(), + )); + + $queue->push($command); + + $this->assertSame([$command], $bound->pushed); + $this->assertSame([], $default->pushed); + } + + #[Test] + public function it_queues_via_an_enqueuer_bound_to_an_array_of_commands_with_an_attribute(): void + { + $command = new TestCommand(); + $queue = new TestComponentQueueWithAttributes($this->createContainer( + $bound = $this->createRecordingEnqueuer(), + $default = $this->createRecordingEnqueuer(), + )); + + $queue->push($command); + + $this->assertSame([$command], $bound->pushed); + $this->assertSame([], $default->pushed); + } + + #[Test] + public function it_queues_via_the_default_enqueuer_bound_with_an_attribute(): void + { + $command = $this->createStub(Command::class); + $queue = new TestComponentQueueWithAttributes($this->createContainer( + $bound = $this->createRecordingEnqueuer(), + $default = $this->createRecordingEnqueuer(), + )); + + $queue->push($command); + + $this->assertSame([], $bound->pushed); + $this->assertSame([$command], $default->pushed); + } + + #[Test] + public function it_queues_through_middleware_from_the_through_attribute(): void + { + $queue = new TestComponentQueueWithAttributes($this->createContainer( + $this->createRecordingEnqueuer(), + $this->createRecordingEnqueuer(), + )); + + $queue->push(new TestQueueableCommand()); + + $this->assertSame(['before1', 'before2', 'pushed', 'after2', 'after1'], $this->sequence); + } + + #[Test] + public function it_does_not_autowire_enqueuer_attributes_when_given_an_enqueuer_container(): void + { + $command = new TestQueueableCommand(); + $enqueuers = $this->createMock(IEnqueuerContainer::class); + $middleware = $this->createMock(IPipeContainer::class); + $queue = new TestComponentQueueWithAttributes($enqueuers, $middleware); + + $middleware + ->expects($this->exactly(2)) ->method('get') - ->with($command3::class) - ->willReturnCallback(function () use ($enqueuer) { - $this->assertSame(['before1', 'before2'], $this->sequence); - return $enqueuer; + ->willReturnCallback(fn (string $name): Closure => match ($name) { + 'Middleware1', 'Middleware2' => fn (Command $c, Closure $next) => $next($c), + default => $this->fail('Unexpected middleware: ' . $name), }); + $enqueuers + ->expects($this->once()) + ->method('get') + ->with($command::class) + ->willReturn($enqueuer = $this->createMock(Enqueuer::class)); + $enqueuer ->expects($this->once()) ->method('__invoke') - ->with($this->identicalTo($command3)); + ->with($this->identicalTo($command)); - $middleware = $this->createMock(PipeContainer::class); - $middleware - ->expects($this->once()) - ->method('get') - ->with('MySecondMiddleware') - ->willReturn($middleware2); + $queue->push($command); + } - $this->queue = new class ( - enqueuers: $this->enqueuers, - middleware: $middleware, - ) extends ComponentQueue {}; + private function createContainer(TestEnqueuer $bound, TestEnqueuer $default): FakeContainer + { + $container = new FakeContainer(); + $container->instance(TestEnqueuer::class, $bound); + $container->instance('DefaultEnqueuer', $default); + $container->instance('Middleware1', function (Command $command, Closure $next): void { + $this->sequence[] = 'before1'; + $next($command); + $this->sequence[] = 'after1'; + }); + $container->instance('Middleware2', function (Command $command, Closure $next): void { + $this->sequence[] = 'before2'; + $next($command); + $this->sequence[] = 'after2'; + }); - $this->queue->through([$middleware1, 'MySecondMiddleware']); - $this->queue->push($command1); + return $container; + } - $this->assertSame(['before1', 'before2', 'after2', 'after1'], $this->sequence); + /** + * @return object{pushed: list}&TestEnqueuer + */ + private function createRecordingEnqueuer(): TestEnqueuer + { + return new class (function (): void { + $this->sequence[] = 'pushed'; + }) extends TestEnqueuer { + /** + * @var list + */ + public array $pushed = []; + + public function __construct(private readonly Closure $onPush) + { + } + + public function push(Command $command): void + { + $this->pushed[] = $command; + ($this->onPush)(); + } + }; } } diff --git a/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php b/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php index 9a3c11a1..8eaaca10 100644 --- a/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php +++ b/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php @@ -13,61 +13,213 @@ namespace CloudCreativity\Modules\Tests\Unit\Infrastructure\Queue; use CloudCreativity\Modules\Contracts\Messaging\Command; +use CloudCreativity\Modules\Infrastructure\InfrastructureException; use CloudCreativity\Modules\Infrastructure\Queue\Enqueuer; use CloudCreativity\Modules\Infrastructure\Queue\EnqueuerContainer; +use CloudCreativity\Modules\Testing\FakeContainer; use CloudCreativity\Modules\Tests\Unit\Application\Bus\TestCommand; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; final class EnqueuerContainerTest extends TestCase { + /** + * @return array}> + */ + public static function multipleCommandsProvider(): array + { + return [ + 'first command' => [TestCommand::class], + 'second command' => [TestQueueableCommand::class], + ]; + } + #[Test] - public function it_uses_bindings(): void + public function it_gets_an_enqueuer_bound_with_a_closure(): void { - $command1 = new class () implements Command {}; - $command2 = new class () implements Command {}; + $enqueuer = new class () extends TestEnqueuer {}; + $container = new EnqueuerContainer(); + $container->bind(TestQueueableCommand::class, fn () => $enqueuer); - $a = new class () extends TestEnqueuer {}; - $b = $this->createStub(TestEnqueuer::class); - $default = $this->createStub(TestEnqueuer::class); + $actual = $container->get(TestQueueableCommand::class); + $this->assertEquals(new Enqueuer($enqueuer), $actual); + } + + #[Test] + public function it_gets_the_closure_default_enqueuer_when_the_command_is_not_bound(): void + { + $default = new class () extends TestEnqueuer {}; $container = new EnqueuerContainer(fn () => $default); - $container->bind($command1::class, fn () => $a); - $container->bind($command2::class, fn () => $b); - $this->assertEquals(new Enqueuer($a), $container->get($command1::class)); - $this->assertEquals(new Enqueuer($b), $container->get($command2::class)); - $this->assertEquals(new Enqueuer($default), $container->get(TestCommand::class)); + $actual = $container->get(TestQueueableCommand::class); + + $this->assertEquals(new Enqueuer($default), $actual); + } + + #[Test] + public function it_prefers_a_closure_binding_over_the_default_enqueuer(): void + { + $bound = new class () extends TestEnqueuer {}; + $container = new EnqueuerContainer(fn () => $this->fail('Default enqueuer resolved.')); + $container->bind(TestQueueableCommand::class, fn () => $bound); + + $actual = $container->get(TestQueueableCommand::class); + + $this->assertEquals(new Enqueuer($bound), $actual); + } + + #[Test] + public function it_gets_an_enqueuer_bound_with_a_string_from_the_psr_container(): void + { + $enqueuer = new class () extends TestEnqueuer {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance(TestEnqueuer::class, $enqueuer); + $container = new EnqueuerContainer(container: $psrContainer); + $container->bind(TestQueueableCommand::class, TestEnqueuer::class); + + $actual = $container->get(TestQueueableCommand::class); + + $this->assertEquals(new Enqueuer($enqueuer), $actual); + } + + #[Test] + public function it_gets_the_psr_container_default_enqueuer_when_the_command_is_not_bound(): void + { + $default = new class () extends TestEnqueuer {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance('DefaultEnqueuer', $default); + $container = new EnqueuerContainer(default: 'DefaultEnqueuer', container: $psrContainer); + + $actual = $container->get(TestQueueableCommand::class); + + $this->assertEquals(new Enqueuer($default), $actual); + } + + #[Test] + public function it_prefers_a_psr_container_binding_over_the_default_enqueuer(): void + { + $bound = new class () extends TestEnqueuer {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance(TestEnqueuer::class, $bound); + $psrContainer->bind('DefaultEnqueuer', fn () => $this->fail('Default enqueuer resolved.')); + $container = new EnqueuerContainer(default: 'DefaultEnqueuer', container: $psrContainer); + $container->bind(TestQueueableCommand::class, TestEnqueuer::class); + + $actual = $container->get(TestQueueableCommand::class); + + $this->assertEquals(new Enqueuer($bound), $actual); + } + + /** + * @param class-string $command + */ + #[DataProvider('multipleCommandsProvider')] + #[Test] + public function it_binds_multiple_commands_to_one_enqueuer(string $command): void + { + $enqueuer = new class () extends TestEnqueuer {}; + $container = new EnqueuerContainer(); + $container->bind([TestCommand::class, TestQueueableCommand::class], fn () => $enqueuer); + + $actual = $container->get($command); + + $this->assertEquals(new Enqueuer($enqueuer), $actual); + } + + #[Test] + public function it_throws_when_the_default_enqueuer_is_a_string_without_a_psr_container(): void + { + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('Cannot bind default enqueuer as a string without a PSR container.'); + + new EnqueuerContainer(default: TestEnqueuer::class); } #[Test] - public function it_uses_psr_container(): void - { - $command1 = new class () implements Command {}; - $command2 = new class () implements Command {}; - - $a = new class () extends TestEnqueuer {}; - $b = $this->createStub(TestEnqueuer::class); - $default = $this->createStub(TestEnqueuer::class); - - $psrContainer = $this->createMock(ContainerInterface::class); - $psrContainer - ->expects($this->exactly(3)) - ->method('get') - ->willReturnCallback(fn (string $id) => match ($id) { - $a::class => $a, - $b::class => $b, - $default::class => $default, - default => $this->fail('Unexpected binding: ' . $id), - }); - - $container = new EnqueuerContainer(default: $default::class, container: $psrContainer); - $container->bind($command1::class, $a::class); - $container->bind($command2::class, $b::class); - - $this->assertEquals(new Enqueuer($a), $container->get($command1::class)); - $this->assertEquals(new Enqueuer($b), $container->get($command2::class)); - $this->assertEquals(new Enqueuer($default), $container->get(TestCommand::class)); + public function it_throws_when_there_is_no_binding_and_no_default_enqueuer(): void + { + $container = new EnqueuerContainer(); + $container->bind(TestCommand::class, fn () => new class () extends TestEnqueuer {}); + + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('No enqueuer bound for command: ' . TestQueueableCommand::class); + + $container->get(TestQueueableCommand::class); + } + + #[Test] + public function it_uses_a_closure_default_enqueuer_set_after_construction(): void + { + $default = new class () extends TestEnqueuer {}; + $container = new EnqueuerContainer(); + + $container->withDefault(fn () => $default); + $actual = $container->get(TestQueueableCommand::class); + + $this->assertEquals(new Enqueuer($default), $actual); + } + + #[Test] + public function it_uses_a_psr_container_default_enqueuer_set_after_construction(): void + { + $default = new class () extends TestEnqueuer {}; + $psrContainer = new FakeContainer(); + $psrContainer->instance(TestEnqueuer::class, $default); + $container = new EnqueuerContainer(container: $psrContainer); + + $container->withDefault(TestEnqueuer::class); + $actual = $container->get(TestQueueableCommand::class); + + $this->assertEquals(new Enqueuer($default), $actual); + } + + #[Test] + public function it_prefers_a_binding_over_a_default_enqueuer_set_after_construction(): void + { + $bound = new class () extends TestEnqueuer {}; + $default = new class () extends TestEnqueuer {}; + $container = new EnqueuerContainer(); + $container->bind(TestQueueableCommand::class, fn () => $bound); + + $container->withDefault(fn () => $default); + $actual = $container->get(TestQueueableCommand::class); + + $this->assertEquals(new Enqueuer($bound), $actual); + } + + #[Test] + public function it_throws_when_the_default_enqueuer_is_already_set_via_the_constructor(): void + { + $container = new EnqueuerContainer(default: fn () => new class () extends TestEnqueuer {}); + + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('Default enqueuer is already set.'); + + $container->withDefault(fn () => new class () extends TestEnqueuer {}); + } + + #[Test] + public function it_throws_when_the_default_enqueuer_is_already_set_via_with_default(): void + { + $container = new EnqueuerContainer(); + $container->withDefault(fn () => new class () extends TestEnqueuer {}); + + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('Default enqueuer is already set.'); + + $container->withDefault(fn () => new class () extends TestEnqueuer {}); + } + + #[Test] + public function it_throws_when_setting_a_string_default_enqueuer_without_a_psr_container(): void + { + $container = new EnqueuerContainer(); + + $this->expectException(InfrastructureException::class); + $this->expectExceptionMessage('Cannot bind default enqueuer as a string without a PSR container.'); + + $container->withDefault(TestEnqueuer::class); } } diff --git a/tests/Unit/Infrastructure/Queue/EnqueuerTest.php b/tests/Unit/Infrastructure/Queue/EnqueuerTest.php index b5e05a8d..7dee31d4 100644 --- a/tests/Unit/Infrastructure/Queue/EnqueuerTest.php +++ b/tests/Unit/Infrastructure/Queue/EnqueuerTest.php @@ -23,14 +23,21 @@ final class EnqueuerTest extends TestCase public function it_pushes_the_command_to_the_inner_enqueuer(): void { $command = $this->createStub(Command::class); - $innerEnqueuer = $this->createMock(TestEnqueuer::class); - - $innerEnqueuer - ->expects($this->once()) - ->method('push') - ->with($this->identicalTo($command)); + $innerEnqueuer = new class () extends TestEnqueuer { + /** + * @var list + */ + public array $pushed = []; + public function push(Command $command): void + { + $this->pushed[] = $command; + } + }; $enqueuer = new Enqueuer($innerEnqueuer); + $enqueuer($command); + + $this->assertSame([$command], $innerEnqueuer->pushed); } } diff --git a/tests/Unit/Infrastructure/Queue/Middleware/LogPushedToQueueTest.php b/tests/Unit/Infrastructure/Queue/Middleware/LogPushedToQueueTest.php new file mode 100644 index 00000000..91a86887 --- /dev/null +++ b/tests/Unit/Infrastructure/Queue/Middleware/LogPushedToQueueTest.php @@ -0,0 +1,119 @@ +logger = new FakeLogger(); + $this->command = new TestQueueableCommand(name: 'bar'); + } + + protected function tearDown(): void + { + unset($this->logger, $this->command); + parent::tearDown(); + } + + #[Test] + public function it_logs_with_the_default_levels(): void + { + $passed = null; + $middleware = new LogPushedToQueue($this->logger); + + $middleware($this->command, function (Command $command) use (&$passed): Result { + $passed = $command; + return Result::ok(); + }); + + $context = ['command' => ['name' => 'bar']]; + + $this->assertSame($this->command, $passed); + $this->assertSame([ + ['level' => LogLevel::DEBUG, 'message' => 'Queuing command Tests:TestQueueableCommand.', 'context' => $context], + ['level' => LogLevel::INFO, 'message' => 'Queued command Tests:TestQueueableCommand.', 'context' => $context], + ], $this->logger->log); + } + + #[Test] + public function it_logs_with_custom_levels(): void + { + $middleware = new LogPushedToQueue($this->logger, LogLevel::NOTICE, LogLevel::WARNING); + + $middleware($this->command, fn (): Result => Result::ok()); + + $this->assertSame([ + 'NOTICE: Queuing command Tests:TestQueueableCommand.', + 'WARNING: Queued command Tests:TestQueueableCommand.', + ], $this->logger->messages()); + } + + #[Test] + public function it_uses_the_fully_qualified_class_name_when_there_is_no_module_basename(): void + { + $command = new class () implements Command {}; + $name = $command::class; + $middleware = new LogPushedToQueue($this->logger); + + $middleware($command, fn (): Result => Result::ok()); + + $this->assertSame([ + "DEBUG: Queuing command {$name}.", + "INFO: Queued command {$name}.", + ], $this->logger->messages()); + } + + #[Test] + public function it_logs_before_the_next_closure_is_invoked(): void + { + $messages = null; + $middleware = new LogPushedToQueue($this->logger); + + $middleware($this->command, function () use (&$messages): Result { + $messages = $this->logger->messages(); + return Result::ok(); + }); + + $this->assertSame(['DEBUG: Queuing command Tests:TestQueueableCommand.'], $messages); + } + + #[Test] + public function it_rethrows_an_exception_thrown_by_the_next_closure(): void + { + $middleware = new LogPushedToQueue($this->logger); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Boom!'); + + $middleware($this->command, static function (): never { + throw new LogicException('Boom!'); + }); + } +} diff --git a/tests/Unit/Infrastructure/Queue/TestComponentQueueWithAttributes.php b/tests/Unit/Infrastructure/Queue/TestComponentQueueWithAttributes.php new file mode 100644 index 00000000..5cc0aeb4 --- /dev/null +++ b/tests/Unit/Infrastructure/Queue/TestComponentQueueWithAttributes.php @@ -0,0 +1,27 @@ +container = new FakeContainer(); + } + + protected function tearDown(): void + { + unset($this->container); + parent::tearDown(); + } + + #[Test] + public function it_is_a_psr_container(): void + { + $this->assertInstanceOf(ContainerInterface::class, $this->container); + } + + #[Test] + public function it_shares_the_exception_reporter_with_the_unit_of_work(): void + { + $actual = $this->container->unitOfWork->exceptions; + + $this->assertSame($this->container->reporter, $actual); + } + + // ------------------------------------------------------------------------- + // get() + // ------------------------------------------------------------------------- + + #[Test] + public function it_resolves_the_exception_reporter(): void + { + $actual = $this->container->get(ExceptionReporter::class); + + $this->assertSame($this->container->reporter, $actual); + } + + #[Test] + public function it_resolves_the_logger(): void + { + $actual = $this->container->get(LoggerInterface::class); + + $this->assertSame($this->container->logger, $actual); + } + + #[Test] + public function it_resolves_the_unit_of_work(): void + { + $actual = $this->container->get(UnitOfWork::class); + + $this->assertSame($this->container->unitOfWork, $actual); + } + + #[Test] + public function it_resolves_a_binding_each_time_it_is_requested(): void + { + $this->container->bind('foo', fn (): stdClass => new stdClass()); + + $first = $this->container->get('foo'); + $second = $this->container->get('foo'); + + $this->assertInstanceOf(stdClass::class, $first); + $this->assertInstanceOf(stdClass::class, $second); + $this->assertNotSame($first, $second); + } + + #[Test] + public function it_replaces_an_existing_binding(): void + { + $this->container->bind('foo', fn (): string => 'bar'); + $this->container->bind('foo', fn (): string => 'baz'); + + $actual = $this->container->get('foo'); + + $this->assertSame('baz', $actual); + } + + #[Test] + public function it_resolves_an_instance(): void + { + $instance = new stdClass(); + $this->container->instance('foo', $instance); + + $actual = $this->container->get('foo'); + + $this->assertSame($instance, $actual); + } + + #[Test] + public function it_resolves_a_falsy_instance(): void + { + $this->container->instance('foo', false); + + $actual = $this->container->get('foo'); + + $this->assertFalse($actual); + } + + #[Test] + public function it_throws_when_the_service_is_not_found(): void + { + $this->expectException(NotFoundExceptionInterface::class); + $this->expectExceptionMessage('Test service not found: foo'); + + $this->container->get('foo'); + } + + #[Test] + public function it_throws_when_the_binding_resolves_to_null(): void + { + $this->container->instance('foo', null); + + $this->expectException(NotFoundExceptionInterface::class); + $this->expectExceptionMessage('Test service not found: foo'); + + $this->container->get('foo'); + } + + // ------------------------------------------------------------------------- + // has() + // ------------------------------------------------------------------------- + + /** + * @return array + */ + public static function builtInServiceProvider(): array + { + return [ + 'exception reporter' => [ExceptionReporter::class], + 'logger' => [LoggerInterface::class], + 'unit of work' => [UnitOfWork::class], + ]; + } + + /** + * @param class-string $id + */ + #[DataProvider('builtInServiceProvider')] + #[Test] + public function it_has_the_built_in_services(string $id): void + { + $actual = $this->container->has($id); + + $this->assertTrue($actual); + } + + #[Test] + public function it_has_a_bound_service(): void + { + $this->container->bind('foo', fn (): string => 'bar'); + + $actual = $this->container->has('foo'); + + $this->assertTrue($actual); + } + + #[Test] + public function it_has_an_instance(): void + { + $this->container->instance('foo', new stdClass()); + + $actual = $this->container->has('foo'); + + $this->assertTrue($actual); + } + + #[Test] + public function it_does_not_have_an_unknown_service(): void + { + $actual = $this->container->has('foo'); + + $this->assertFalse($actual); + } +} diff --git a/tests/Unit/Testing/FakeDomainEventDispatcherTest.php b/tests/Unit/Testing/FakeDomainEventDispatcherTest.php index 3c27ffb2..d345ebde 100644 --- a/tests/Unit/Testing/FakeDomainEventDispatcherTest.php +++ b/tests/Unit/Testing/FakeDomainEventDispatcherTest.php @@ -21,62 +21,162 @@ final class FakeDomainEventDispatcherTest extends TestCase { + private FakeDomainEventDispatcher $dispatcher; + + protected function setUp(): void + { + parent::setUp(); + $this->dispatcher = new class () extends FakeDomainEventDispatcher {}; + } + + protected function tearDown(): void + { + unset($this->dispatcher); + parent::tearDown(); + } + + #[Test] + public function it_is_a_domain_event_dispatcher(): void + { + $this->assertInstanceOf(DomainEventDispatcher::class, $this->dispatcher); + } + + #[Test] + public function it_is_empty_by_default(): void + { + $actual = [count($this->dispatcher), iterator_to_array($this->dispatcher)]; + + $this->assertSame([0, []], $actual); + } + + // ------------------------------------------------------------------------- + // dispatch() + // ------------------------------------------------------------------------- + #[Test] - public function it_publishes_events(): void + public function it_dispatches_events(): void { - $dispatcher = new class () extends FakeDomainEventDispatcher {}; + $event1 = $this->createStub(DomainEvent::class); + $event2 = $this->createStub(DomainEvent::class); + + $this->dispatcher->dispatch($event1); + $this->dispatcher->dispatch($event2); + + $this->assertSame([$event1, $event2], $this->dispatcher->events); + } + + // ------------------------------------------------------------------------- + // count() and getIterator() + // ------------------------------------------------------------------------- + + #[Test] + public function it_counts_the_dispatched_events(): void + { + $this->dispatcher->events = [ + $this->createStub(DomainEvent::class), + $this->createStub(DomainEvent::class), + ]; + $actual = count($this->dispatcher); + + $this->assertSame(2, $actual); + } + + #[Test] + public function it_iterates_over_the_dispatched_events(): void + { $event1 = $this->createStub(DomainEvent::class); $event2 = $this->createStub(DomainEvent::class); + $this->dispatcher->events = [$event1, $event2]; + + $actual = iterator_to_array($this->dispatcher); - $dispatcher->dispatch($event1); - $dispatcher->dispatch($event2); - - $this->assertInstanceOf(DomainEventDispatcher::class, $dispatcher); - $this->assertCount(2, $dispatcher); - $this->assertSame([$event1, $event2], $dispatcher->events); - $this->assertSame([$event1, $event2], iterator_to_array($dispatcher)); - $this->assertSame($event1, $dispatcher->events[0]); - $this->assertSame($event2, $dispatcher->events[1]); - $this->assertSame($event1, $dispatcher[0]); - $this->assertSame($event2, $dispatcher[1]); + $this->assertSame([$event1, $event2], $actual); } + // ------------------------------------------------------------------------- + // ArrayAccess + // ------------------------------------------------------------------------- + + #[Test] + public function it_gets_an_event_by_offset(): void + { + $event1 = $this->createStub(DomainEvent::class); + $event2 = $this->createStub(DomainEvent::class); + $this->dispatcher->events = [$event1, $event2]; + + $actual = [$this->dispatcher[0], $this->dispatcher[1]]; + + $this->assertSame([$event1, $event2], $actual); + } + + #[Test] + public function it_checks_whether_an_offset_exists(): void + { + $this->dispatcher->events = [$this->createStub(DomainEvent::class)]; + + $actual = [isset($this->dispatcher[0]), isset($this->dispatcher[1])]; + + $this->assertSame([true, false], $actual); + } + + #[Test] + public function it_cannot_set_an_offset(): void + { + $event = $this->createStub(DomainEvent::class); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot set domain events.'); + + $this->dispatcher[0] = $event; + } + + #[Test] + public function it_cannot_unset_an_offset(): void + { + $this->dispatcher->events = [$this->createStub(DomainEvent::class)]; + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot unset domain events.'); + + unset($this->dispatcher[0]); + } + + // ------------------------------------------------------------------------- + // sole() + // ------------------------------------------------------------------------- + #[Test] public function it_returns_sole_event(): void { - $dispatcher = new class () extends FakeDomainEventDispatcher {}; $event = $this->createStub(DomainEvent::class); + $this->dispatcher->events = [$event]; - $dispatcher->dispatch($event); + $actual = $this->dispatcher->sole(); - $this->assertSame($event, $dispatcher->sole()); + $this->assertSame($event, $actual); } #[Test] public function it_throws_exception_if_no_events(): void { - $dispatcher = new class () extends FakeDomainEventDispatcher {}; - $this->expectException(LogicException::class); $this->expectExceptionMessage('Expected one event to be dispatched but there are 0 events.'); - $dispatcher->sole(); + $this->dispatcher->sole(); } #[Test] public function it_throws_exception_if_multiple_events(): void { - $dispatcher = new class () extends FakeDomainEventDispatcher {}; - $event1 = $this->createStub(DomainEvent::class); - $event2 = $this->createStub(DomainEvent::class); - - $dispatcher->dispatch($event1); - $dispatcher->dispatch($event2); + $this->dispatcher->events = [ + $this->createStub(DomainEvent::class), + $this->createStub(DomainEvent::class), + ]; $this->expectException(LogicException::class); $this->expectExceptionMessage('Expected one event to be dispatched but there are 2 events.'); - $dispatcher->sole(); + $this->dispatcher->sole(); } } diff --git a/tests/Unit/Testing/FakeExceptionReporterTest.php b/tests/Unit/Testing/FakeExceptionReporterTest.php index adff2698..5d3f2cd6 100644 --- a/tests/Unit/Testing/FakeExceptionReporterTest.php +++ b/tests/Unit/Testing/FakeExceptionReporterTest.php @@ -21,79 +21,206 @@ final class FakeExceptionReporterTest extends TestCase { + private FakeExceptionReporter $reporter; + + protected function setUp(): void + { + parent::setUp(); + $this->reporter = new FakeExceptionReporter(); + } + + protected function tearDown(): void + { + unset($this->reporter); + parent::tearDown(); + } + + #[Test] + public function it_is_an_exception_reporter(): void + { + $this->assertInstanceOf(ExceptionReporter::class, $this->reporter); + } + + #[Test] + public function it_is_empty_by_default(): void + { + $actual = [count($this->reporter), iterator_to_array($this->reporter)]; + + $this->assertSame([0, []], $actual); + } + + // ------------------------------------------------------------------------- + // report() + // ------------------------------------------------------------------------- + #[Test] public function it_reports_exceptions(): void { - $reporter = new FakeExceptionReporter(); - $reporter->report($ex1 = new RuntimeException('Whoops!')); - $reporter->report($ex2 = new RuntimeException('Whoops again!')); + $ex1 = new RuntimeException('Whoops!'); + $ex2 = new RuntimeException('Whoops again!'); + + $this->reporter->report($ex1); + $this->reporter->report($ex2); - $this->assertInstanceOf(ExceptionReporter::class, $reporter); - $this->assertCount(2, $reporter); - $this->assertSame([$ex1, $ex2], $reporter->reported); - $this->assertSame([$ex1, $ex2], iterator_to_array($reporter)); - $this->assertSame($ex1, $reporter[0]); - $this->assertSame($ex2, $reporter[1]); + $this->assertSame([$ex1, $ex2], $this->reporter->reported); } + // ------------------------------------------------------------------------- + // none() and expect() + // ------------------------------------------------------------------------- + #[Test] public function it_does_not_expect_exceptions(): void { $expected = new RuntimeException('Boom! That was a surprise.'); - - $reporter = new FakeExceptionReporter(); - $reporter->none(); + $this->reporter->none(); $this->expectExceptionObject($expected); - $reporter->report($expected); + + $this->reporter->report($expected); + } + + #[Test] + public function it_records_exceptions_until_the_expected_count_is_reached(): void + { + $ex1 = new RuntimeException('Whoops!'); + $ex2 = new RuntimeException('Whoops again!'); + $this->reporter->reported = [$ex1]; + $this->reporter->expect(2); + + $this->reporter->report($ex2); + + $this->assertSame([$ex1, $ex2], $this->reporter->reported); } #[Test] - public function it_expects_exceptions(): void + public function it_rethrows_once_the_expected_count_is_reached(): void { $expected = new RuntimeException('Boom! That was a surprise.'); + $this->reporter->reported = [ + new LogicException('Whoops 0!'), + new LogicException('Whoops 1!'), + new LogicException('Whoops 2!'), + ]; + $this->reporter->expect(3); $this->expectExceptionObject($expected); - $reporter = new FakeExceptionReporter(); - $reporter->expect(3); + $this->reporter->report($expected); + } + + // ------------------------------------------------------------------------- + // count() and getIterator() + // ------------------------------------------------------------------------- + + #[Test] + public function it_counts_the_reported_exceptions(): void + { + $this->reporter->reported = [ + new RuntimeException('Whoops!'), + new RuntimeException('Whoops again!'), + ]; + + $actual = count($this->reporter); + + $this->assertSame(2, $actual); + } + + #[Test] + public function it_iterates_over_the_reported_exceptions(): void + { + $ex1 = new RuntimeException('Whoops!'); + $ex2 = new RuntimeException('Whoops again!'); + $this->reporter->reported = [$ex1, $ex2]; + + $actual = iterator_to_array($this->reporter); + + $this->assertSame([$ex1, $ex2], $actual); + } + + // ------------------------------------------------------------------------- + // ArrayAccess + // ------------------------------------------------------------------------- + + #[Test] + public function it_gets_an_exception_by_offset(): void + { + $ex1 = new RuntimeException('Whoops!'); + $ex2 = new RuntimeException('Whoops again!'); + $this->reporter->reported = [$ex1, $ex2]; + + $actual = [$this->reporter[0], $this->reporter[1]]; + + $this->assertSame([$ex1, $ex2], $actual); + } + + #[Test] + public function it_checks_whether_an_offset_exists(): void + { + $this->reporter->reported = [new RuntimeException('Whoops!')]; + + $actual = [isset($this->reporter[0]), isset($this->reporter[1])]; + + $this->assertSame([true, false], $actual); + } - for ($i = 0; $i < 3; $i++) { - $reporter->report(new LogicException("Whoops {$i}!")); - } + #[Test] + public function it_cannot_set_an_offset(): void + { + $ex = new RuntimeException('Whoops!'); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot set reported exceptions.'); + + $this->reporter[0] = $ex; + } + + #[Test] + public function it_cannot_unset_an_offset(): void + { + $this->reporter->reported = [new RuntimeException('Whoops!')]; - $this->assertCount(3, $reporter); - $reporter->report($expected); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot unset reported exceptions.'); + + unset($this->reporter[0]); } + // ------------------------------------------------------------------------- + // sole() + // ------------------------------------------------------------------------- + #[Test] public function it_has_sole_exception(): void { - $reporter = new FakeExceptionReporter(); - $reporter->report($ex = new RuntimeException('Whoops!')); + $ex = new RuntimeException('Whoops!'); + $this->reporter->reported = [$ex]; - $this->assertSame($ex, $reporter->sole()); + $actual = $this->reporter->sole(); + + $this->assertSame($ex, $actual); } #[Test] public function it_fails_when_there_is_no_sole_exception(): void { - $this->expectExceptionMessage('Expected one exception to be reported but there are 0 exceptions.'); $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected one exception to be reported but there are 0 exceptions.'); - $reporter = new FakeExceptionReporter(); - $reporter->sole(); + $this->reporter->sole(); } #[Test] public function it_fails_when_there_is_more_than_one_sole_exception(): void { - $this->expectExceptionMessage('Expected one exception to be reported but there are 2 exceptions.'); + $this->reporter->reported = [ + new RuntimeException('Whoops!'), + new RuntimeException('Whoops again!'), + ]; + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected one exception to be reported but there are 2 exceptions.'); - $reporter = new FakeExceptionReporter(); - $reporter->report(new RuntimeException('Whoops!')); - $reporter->report(new RuntimeException('Whoops again!')); - $reporter->sole(); + $this->reporter->sole(); } } diff --git a/tests/Unit/Testing/FakeLoggerTest.php b/tests/Unit/Testing/FakeLoggerTest.php new file mode 100644 index 00000000..d059e6ce --- /dev/null +++ b/tests/Unit/Testing/FakeLoggerTest.php @@ -0,0 +1,127 @@ +logger = new FakeLogger(); + } + + protected function tearDown(): void + { + unset($this->logger); + parent::tearDown(); + } + + #[Test] + public function it_is_a_psr_logger(): void + { + $this->assertInstanceOf(LoggerInterface::class, $this->logger); + } + + #[Test] + public function it_is_empty_by_default(): void + { + $actual = [count($this->logger), $this->logger->log, $this->logger->messages()]; + + $this->assertSame([0, [], []], $actual); + } + + // ------------------------------------------------------------------------- + // log() + // ------------------------------------------------------------------------- + + #[Test] + public function it_records_log_entries(): void + { + $this->logger->log(LogLevel::INFO, 'First message', ['foo' => 'bar']); + $this->logger->debug('Second message'); + + $this->assertSame([ + ['level' => LogLevel::INFO, 'message' => 'First message', 'context' => ['foo' => 'bar']], + ['level' => LogLevel::DEBUG, 'message' => 'Second message', 'context' => []], + ], $this->logger->log); + } + + #[Test] + public function it_counts_the_log_entries(): void + { + $this->logger->log = [ + ['level' => LogLevel::INFO, 'message' => 'First message', 'context' => []], + ['level' => LogLevel::DEBUG, 'message' => 'Second message', 'context' => []], + ]; + + $actual = count($this->logger); + + $this->assertSame(2, $actual); + } + + #[Test] + public function it_casts_a_stringable_message_to_a_string(): void + { + $message = new class () implements Stringable { + public function __toString(): string + { + return 'Stringable message'; + } + }; + + $this->logger->warning($message); + + $this->assertSame([ + ['level' => LogLevel::WARNING, 'message' => 'Stringable message', 'context' => []], + ], $this->logger->log); + } + + // ------------------------------------------------------------------------- + // messages() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_messages_prefixed_with_the_level(): void + { + $this->logger->log = [ + ['level' => LogLevel::INFO, 'message' => 'First message', 'context' => ['foo' => 'bar']], + ['level' => LogLevel::ERROR, 'message' => 'Second message', 'context' => []], + ]; + + $actual = $this->logger->messages(); + + $this->assertSame(['INFO: First message', 'ERROR: Second message'], $actual); + } + + #[Test] + public function it_returns_messages_without_a_prefix_when_the_level_is_not_scalar(): void + { + $this->logger->log = [ + ['level' => new stdClass(), 'message' => 'Some message', 'context' => []], + ]; + + $actual = $this->logger->messages(); + + $this->assertSame(['Some message'], $actual); + } +} diff --git a/tests/Unit/Testing/FakeOutboundEventPublisherTest.php b/tests/Unit/Testing/FakeOutboundEventPublisherTest.php index f25cf3b7..03a9c021 100644 --- a/tests/Unit/Testing/FakeOutboundEventPublisherTest.php +++ b/tests/Unit/Testing/FakeOutboundEventPublisherTest.php @@ -21,60 +21,162 @@ final class FakeOutboundEventPublisherTest extends TestCase { + private FakeOutboundEventPublisher $publisher; + + protected function setUp(): void + { + parent::setUp(); + $this->publisher = new class () extends FakeOutboundEventPublisher {}; + } + + protected function tearDown(): void + { + unset($this->publisher); + parent::tearDown(); + } + + #[Test] + public function it_is_an_outbound_event_publisher(): void + { + $this->assertInstanceOf(OutboundEventPublisher::class, $this->publisher); + } + + #[Test] + public function it_is_empty_by_default(): void + { + $actual = [count($this->publisher), iterator_to_array($this->publisher)]; + + $this->assertSame([0, []], $actual); + } + + // ------------------------------------------------------------------------- + // publish() + // ------------------------------------------------------------------------- + #[Test] public function it_publishes_events(): void { - $publisher = new class () extends FakeOutboundEventPublisher {}; + $event1 = $this->createStub(IntegrationEvent::class); + $event2 = $this->createStub(IntegrationEvent::class); + + $this->publisher->publish($event1); + $this->publisher->publish($event2); + + $this->assertSame([$event1, $event2], $this->publisher->events); + } + + // ------------------------------------------------------------------------- + // count() and getIterator() + // ------------------------------------------------------------------------- + + #[Test] + public function it_counts_the_published_events(): void + { + $this->publisher->events = [ + $this->createStub(IntegrationEvent::class), + $this->createStub(IntegrationEvent::class), + ]; + + $actual = count($this->publisher); + + $this->assertSame(2, $actual); + } + + #[Test] + public function it_iterates_over_the_published_events(): void + { + $event1 = $this->createStub(IntegrationEvent::class); + $event2 = $this->createStub(IntegrationEvent::class); + $this->publisher->events = [$event1, $event2]; + + $actual = iterator_to_array($this->publisher); + + $this->assertSame([$event1, $event2], $actual); + } + + // ------------------------------------------------------------------------- + // ArrayAccess + // ------------------------------------------------------------------------- + #[Test] + public function it_gets_an_event_by_offset(): void + { $event1 = $this->createStub(IntegrationEvent::class); $event2 = $this->createStub(IntegrationEvent::class); + $this->publisher->events = [$event1, $event2]; - $publisher->publish($event1); - $publisher->publish($event2); + $actual = [$this->publisher[0], $this->publisher[1]]; - $this->assertInstanceOf(OutboundEventPublisher::class, $publisher); - $this->assertCount(2, $publisher); - $this->assertSame([$event1, $event2], $publisher->events); - $this->assertSame([$event1, $event2], iterator_to_array($publisher)); - $this->assertSame($event1, $publisher[0]); - $this->assertSame($event2, $publisher[1]); + $this->assertSame([$event1, $event2], $actual); } + #[Test] + public function it_checks_whether_an_offset_exists(): void + { + $this->publisher->events = [$this->createStub(IntegrationEvent::class)]; + + $actual = [isset($this->publisher[0]), isset($this->publisher[1])]; + + $this->assertSame([true, false], $actual); + } + + #[Test] + public function it_cannot_set_an_offset(): void + { + $event = $this->createStub(IntegrationEvent::class); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot set integration events.'); + + $this->publisher[0] = $event; + } + + #[Test] + public function it_cannot_unset_an_offset(): void + { + $this->publisher->events = [$this->createStub(IntegrationEvent::class)]; + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot unset integration events.'); + + unset($this->publisher[0]); + } + + // ------------------------------------------------------------------------- + // sole() + // ------------------------------------------------------------------------- + #[Test] public function it_returns_sole_event(): void { - $publisher = new class () extends FakeOutboundEventPublisher {}; $event = $this->createStub(IntegrationEvent::class); + $this->publisher->events = [$event]; - $publisher->publish($event); + $actual = $this->publisher->sole(); - $this->assertSame($event, $publisher->sole()); + $this->assertSame($event, $actual); } #[Test] public function it_throws_exception_if_no_events(): void { - $publisher = new class () extends FakeOutboundEventPublisher {}; - $this->expectException(LogicException::class); $this->expectExceptionMessage('Expected one event to be published but there are 0 events.'); - $publisher->sole(); + $this->publisher->sole(); } #[Test] public function it_throws_exception_if_multiple_events(): void { - $publisher = new class () extends FakeOutboundEventPublisher {}; - $event1 = $this->createStub(IntegrationEvent::class); - $event2 = $this->createStub(IntegrationEvent::class); - - $publisher->publish($event1); - $publisher->publish($event2); + $this->publisher->events = [ + $this->createStub(IntegrationEvent::class), + $this->createStub(IntegrationEvent::class), + ]; $this->expectException(LogicException::class); $this->expectExceptionMessage('Expected one event to be published but there are 2 events.'); - $publisher->sole(); + $this->publisher->sole(); } } diff --git a/tests/Unit/Testing/FakeQueueTest.php b/tests/Unit/Testing/FakeQueueTest.php index beb4a469..6de20421 100644 --- a/tests/Unit/Testing/FakeQueueTest.php +++ b/tests/Unit/Testing/FakeQueueTest.php @@ -21,49 +21,162 @@ final class FakeQueueTest extends TestCase { + private FakeQueue $queue; + + protected function setUp(): void + { + parent::setUp(); + $this->queue = new class () extends FakeQueue {}; + } + + protected function tearDown(): void + { + unset($this->queue); + parent::tearDown(); + } + + #[Test] + public function it_is_a_queue(): void + { + $this->assertInstanceOf(Queue::class, $this->queue); + } + + #[Test] + public function it_is_empty_by_default(): void + { + $actual = [count($this->queue), iterator_to_array($this->queue)]; + + $this->assertSame([0, []], $actual); + } + + // ------------------------------------------------------------------------- + // push() + // ------------------------------------------------------------------------- + #[Test] public function it_queues_commands(): void { - $queue = new class () extends FakeQueue {}; - $queue->push($command1 = $this->createStub(Command::class)); - $queue->push($command2 = $this->createStub(Command::class)); - - $this->assertInstanceOf(Queue::class, $queue); - $this->assertCount(2, $queue); - $this->assertSame([$command1, $command2], $queue->commands); - $this->assertSame([$command1, $command2], iterator_to_array($queue)); - $this->assertSame($command1, $queue[0]); - $this->assertSame($command2, $queue[1]); + $command1 = $this->createStub(Command::class); + $command2 = $this->createStub(Command::class); + + $this->queue->push($command1); + $this->queue->push($command2); + + $this->assertSame([$command1, $command2], $this->queue->commands); + } + + // ------------------------------------------------------------------------- + // count() and getIterator() + // ------------------------------------------------------------------------- + + #[Test] + public function it_counts_the_queued_commands(): void + { + $this->queue->commands = [ + $this->createStub(Command::class), + $this->createStub(Command::class), + ]; + + $actual = count($this->queue); + + $this->assertSame(2, $actual); + } + + #[Test] + public function it_iterates_over_the_queued_commands(): void + { + $command1 = $this->createStub(Command::class); + $command2 = $this->createStub(Command::class); + $this->queue->commands = [$command1, $command2]; + + $actual = iterator_to_array($this->queue); + + $this->assertSame([$command1, $command2], $actual); + } + + // ------------------------------------------------------------------------- + // ArrayAccess + // ------------------------------------------------------------------------- + + #[Test] + public function it_gets_a_command_by_offset(): void + { + $command1 = $this->createStub(Command::class); + $command2 = $this->createStub(Command::class); + $this->queue->commands = [$command1, $command2]; + + $actual = [$this->queue[0], $this->queue[1]]; + + $this->assertSame([$command1, $command2], $actual); } + #[Test] + public function it_checks_whether_an_offset_exists(): void + { + $this->queue->commands = [$this->createStub(Command::class)]; + + $actual = [isset($this->queue[0]), isset($this->queue[1])]; + + $this->assertSame([true, false], $actual); + } + + #[Test] + public function it_cannot_set_an_offset(): void + { + $command = $this->createStub(Command::class); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot set commands.'); + + $this->queue[0] = $command; + } + + #[Test] + public function it_cannot_unset_an_offset(): void + { + $this->queue->commands = [$this->createStub(Command::class)]; + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot unset commands.'); + + unset($this->queue[0]); + } + + // ------------------------------------------------------------------------- + // sole() + // ------------------------------------------------------------------------- + #[Test] public function it_has_sole_command(): void { - $queue = new class () extends FakeQueue {}; - $queue->push($command = $this->createStub(Command::class)); + $command = $this->createStub(Command::class); + $this->queue->commands = [$command]; - $this->assertSame($command, $queue->sole()); + $actual = $this->queue->sole(); + + $this->assertSame($command, $actual); } #[Test] public function it_fails_when_there_is_no_sole_command(): void { - $this->expectExceptionMessage('Expected one command in the queue but there are 0 commands.'); $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected one command in the queue but there are 0 commands.'); - $queue = new class () extends FakeQueue {}; - $queue->sole(); + $this->queue->sole(); } #[Test] public function it_fails_when_there_is_more_than_one_sole_command(): void { - $this->expectExceptionMessage('Expected one command in the queue but there are 2 commands.'); + $this->queue->commands = [ + $this->createStub(Command::class), + $this->createStub(Command::class), + ]; + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected one command in the queue but there are 2 commands.'); - $queue = new class () extends FakeQueue {}; - $queue->push($this->createStub(Command::class)); - $queue->push($this->createStub(Command::class)); - $queue->sole(); + $this->queue->sole(); } } diff --git a/tests/Unit/Testing/FakeUnitOfWorkTest.php b/tests/Unit/Testing/FakeUnitOfWorkTest.php index 2f5cd5f0..f6f1636e 100644 --- a/tests/Unit/Testing/FakeUnitOfWorkTest.php +++ b/tests/Unit/Testing/FakeUnitOfWorkTest.php @@ -12,46 +12,80 @@ namespace CloudCreativity\Modules\Tests\Unit\Testing; +use Closure; use CloudCreativity\Modules\Contracts\Application\Ports\UnitOfWork; +use CloudCreativity\Modules\Testing\FakeExceptionReporter; use CloudCreativity\Modules\Testing\FakeUnitOfWork; +use InvalidArgumentException; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use RuntimeException; +use Throwable; final class FakeUnitOfWorkTest extends TestCase { + #[Test] + public function it_is_a_unit_of_work(): void + { + $unitOfWork = new FakeUnitOfWork(); + + $this->assertInstanceOf(UnitOfWork::class, $unitOfWork); + } + + #[Test] + public function it_exposes_the_provided_exception_reporter(): void + { + $reporter = new FakeExceptionReporter(); + + $unitOfWork = new FakeUnitOfWork($reporter); + + $this->assertSame($reporter, $unitOfWork->exceptions); + } + + // ------------------------------------------------------------------------- + // execute() + // ------------------------------------------------------------------------- + #[Test] public function it_is_successful_on_first_attempt(): void { $unitOfWork = new FakeUnitOfWork(); + $result = $unitOfWork->execute(fn () => 'result'); - $this->assertInstanceOf(UnitOfWork::class, $unitOfWork); $this->assertSame('result', $result); $this->assertSame(['attempt:1', 'commit:1'], $unitOfWork->sequence); - $this->assertEmpty($unitOfWork->exceptions->reported); + $this->assertSame([], $unitOfWork->exceptions->reported); $this->assertSame(1, $unitOfWork->attempts); $this->assertSame(1, $unitOfWork->commits); $this->assertSame(0, $unitOfWork->rollbacks); } + /** + * @return array}> + */ + public static function successfulRetryProvider(): array + { + return [ + 'before max attempts' => [4], + 'on max attempts' => [3], + ]; + } + + /** + * @param int<1, max> $attempts + */ + #[DataProvider('successfulRetryProvider')] #[Test] - public function it_is_successful_before_max_attempts(): void + public function it_is_successful_after_retrying(int $attempts): void { $ex1 = new RuntimeException('An error occurred.'); $ex2 = new RuntimeException('Another error occurred.'); - $exceptions = [$ex1, $ex2]; - $unitOfWork = new FakeUnitOfWork(); - $result = $unitOfWork->execute(function () use (&$exceptions): string { - $ex = array_shift($exceptions); - if ($ex) { - throw $ex; - } - return 'result'; - }, 4); - $this->assertInstanceOf(UnitOfWork::class, $unitOfWork); + $result = $unitOfWork->execute($this->failThenSucceed([$ex1, $ex2]), $attempts); + $this->assertSame('result', $result); $this->assertSame([ 'attempt:1', @@ -61,70 +95,124 @@ public function it_is_successful_before_max_attempts(): void 'attempt:3', 'commit:3', ], $unitOfWork->sequence); - $this->assertSame($unitOfWork->exceptions->reported, [$ex1, $ex2]); + $this->assertSame([$ex1, $ex2], $unitOfWork->exceptions->reported); $this->assertSame(3, $unitOfWork->attempts); $this->assertSame(1, $unitOfWork->commits); $this->assertSame(2, $unitOfWork->rollbacks); } #[Test] - public function it_is_successful_on_max_attempts(): void + public function it_rethrows_the_last_exception_when_not_successful(): void { $ex1 = new RuntimeException('An error occurred.'); $ex2 = new RuntimeException('Another error occurred.'); - $exceptions = [$ex1, $ex2]; + $unitOfWork = new FakeUnitOfWork(); + + $this->expectExceptionObject($ex2); + $unitOfWork->execute($this->failThenSucceed([$ex1, $ex2]), 2); + } + + #[Test] + public function it_rolls_back_every_attempt_when_not_successful(): void + { + $ex1 = new RuntimeException('An error occurred.'); + $ex2 = new RuntimeException('Another error occurred.'); $unitOfWork = new FakeUnitOfWork(); - $result = $unitOfWork->execute(function () use (&$exceptions): string { - $ex = array_shift($exceptions); - if ($ex) { - throw $ex; - } - return 'result'; - }, 3); - $this->assertInstanceOf(UnitOfWork::class, $unitOfWork); - $this->assertSame('result', $result); + try { + $unitOfWork->execute($this->failThenSucceed([$ex1, $ex2]), 2); + } catch (RuntimeException) { + // expected + } + $this->assertSame([ 'attempt:1', 'rollback:1', 'attempt:2', 'rollback:2', - 'attempt:3', - 'commit:3', ], $unitOfWork->sequence); - $this->assertSame($unitOfWork->exceptions->reported, [$ex1, $ex2]); - $this->assertSame(3, $unitOfWork->attempts); - $this->assertSame(1, $unitOfWork->commits); + $this->assertSame([$ex1, $ex2], $unitOfWork->exceptions->reported); + $this->assertSame(2, $unitOfWork->attempts); + $this->assertSame(0, $unitOfWork->commits); $this->assertSame(2, $unitOfWork->rollbacks); } #[Test] - public function it_is_not_successful(): void + public function it_reports_exceptions_to_the_provided_exception_reporter(): void { - $ex1 = new RuntimeException('An error occurred.'); - $ex2 = new RuntimeException('Another error occurred.'); - $exceptions = [$ex1, $ex2]; + $reporter = new FakeExceptionReporter(); + $ex = new RuntimeException('An error occurred.'); + $unitOfWork = new FakeUnitOfWork($reporter); - $unitOfWork = new FakeUnitOfWork(); + $unitOfWork->execute($this->failThenSucceed([$ex]), 2); - $this->expectExceptionObject($ex2); + $this->assertSame([$ex], $reporter->reported); + } + + #[Test] + public function it_does_not_retry_when_the_exception_reporter_rethrows(): void + { + $reporter = new FakeExceptionReporter(); + $reporter->none(); + $ex = new RuntimeException('An error occurred.'); + $unitOfWork = new FakeUnitOfWork($reporter); + $actual = null; try { - $unitOfWork->execute(function () use (&$exceptions): never { - throw array_shift($exceptions); - }, 2); - } finally { - $this->assertSame([ - 'attempt:1', - 'rollback:1', - 'attempt:2', - 'rollback:2', - ], $unitOfWork->sequence); - $this->assertSame($unitOfWork->exceptions->reported, [$ex1, $ex2]); - $this->assertSame(2, $unitOfWork->attempts); - $this->assertSame(0, $unitOfWork->commits); - $this->assertSame(2, $unitOfWork->rollbacks); + $unitOfWork->execute(fn () => throw $ex, 3); + } catch (RuntimeException $caught) { + $actual = $caught; } + + $this->assertSame($ex, $actual); + $this->assertSame(['attempt:1', 'rollback:1'], $unitOfWork->sequence); + $this->assertSame(1, $unitOfWork->attempts); + $this->assertSame(0, $unitOfWork->commits); + $this->assertSame(1, $unitOfWork->rollbacks); + $this->assertSame([], $reporter->reported); + } + + /** + * @return array + */ + public static function invalidAttemptsProvider(): array + { + return [ + 'zero' => [0], + 'negative' => [-1], + ]; + } + + #[DataProvider('invalidAttemptsProvider')] + #[Test] + public function it_throws_when_attempts_is_less_than_one(int $attempts): void + { + $unitOfWork = new FakeUnitOfWork(); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The number of attempts must be at least 1.'); + + // @phpstan-ignore argument.type (deliberately violates the int<1, max> contract) + $unitOfWork->execute(fn () => 'result', $attempts); + } + + /** + * Create a callback that throws each of the provided exceptions in turn, then returns a result. + * + * @param list $exceptions + * @return Closure(): string + */ + private function failThenSucceed(array $exceptions): Closure + { + return function () use (&$exceptions): string { + $ex = array_shift($exceptions); + + if ($ex) { + throw $ex; + } + + return 'result'; + }; } } diff --git a/tests/Unit/Toolkit/ContractsTest.php b/tests/Unit/Toolkit/ContractsTest.php index 5e78ad77..c2a08d12 100644 --- a/tests/Unit/Toolkit/ContractsTest.php +++ b/tests/Unit/Toolkit/ContractsTest.php @@ -16,27 +16,26 @@ use CloudCreativity\Modules\Toolkit\Contracts; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use ReflectionClass; final class ContractsTest extends TestCase { #[Test] public function it_does_not_throw_when_precondition_is_true(): void { - /** @phpstan-ignore-next-line */ - Contracts::assert(true, 'Not expected error.'); + $this->expectNotToPerformAssertions(); /** @phpstan-ignore-next-line */ - $this->assertTrue(true); + Contracts::assert(true, 'Not expected error.'); } #[Test] public function it_does_not_throw_when_precondition_is_true_with_lazy_message(): void { - /** @phpstan-ignore-next-line */ - Contracts::assert(true, fn () => $this->fail('Not expected error.')); + $this->expectNotToPerformAssertions(); /** @phpstan-ignore-next-line */ - $this->assertTrue(true); + Contracts::assert(true, fn () => $this->fail('Not expected error.')); } #[Test] @@ -58,4 +57,22 @@ public function it_throws_when_precondition_is_false_with_lazy_message(): void /** @phpstan-ignore-next-line */ Contracts::assert(false, fn () => $expected); } + + #[Test] + public function it_throws_with_an_empty_message_by_default(): void + { + $this->expectException(ContractException::class); + $this->expectExceptionMessageMatches('/^$/'); + + /** @phpstan-ignore-next-line */ + Contracts::assert(false); + } + + #[Test] + public function it_cannot_be_instantiated(): void + { + $reflection = new ReflectionClass(Contracts::class); + + $this->assertFalse($reflection->isInstantiable()); + } } diff --git a/tests/Unit/Toolkit/Identifiers/GuidTest.php b/tests/Unit/Toolkit/Identifiers/GuidTest.php index 08aece24..a622d12a 100644 --- a/tests/Unit/Toolkit/Identifiers/GuidTest.php +++ b/tests/Unit/Toolkit/Identifiers/GuidTest.php @@ -27,12 +27,17 @@ use PHPUnit\Framework\TestCase; use Ramsey\Uuid\Uuid as BaseUuid; use Ramsey\Uuid\UuidInterface; +use Stringable; use UnitEnum; final class GuidTest extends TestCase { + private const string UUID = '6dcbad65-ed92-4e60-973b-9ba58a022816'; + + private const string OTHER_UUID = '38c7be26-6887-4742-8b6b-7d07b30ca596'; + /** - * @return array> + * @return array */ public static function typeProvider(): array { @@ -53,10 +58,10 @@ public static function typeProvider(): array ]; } - /** - * @param string|TestUnitEnum $type - * @param string|TestUnitEnum $other - */ + // ------------------------------------------------------------------------- + // Creation + // ------------------------------------------------------------------------- + #[DataProvider('typeProvider')] #[Test] public function it_can_be_created_from_a_string_id( @@ -67,31 +72,12 @@ public function it_can_be_created_from_a_string_id( ): void { $guid = Guid::fromString($type, '123'); - $others = [ - Guid::fromInteger($type, 123), - Guid::fromString($type, '234'), - Guid::fromString($other, '123'), - ]; - - $this->assertInstanceOf(\Stringable::class, $guid); + $this->assertInstanceOf(Stringable::class, $guid); $this->assertSame($type, $guid->type); $this->assertObjectEquals(new StringId('123'), $guid->id); $this->assertSame($value . ':123', $guid->toString()); $this->assertSame($value . ':123', (string) $guid); - $this->assertTrue($guid->isType($type)); - $this->assertTrue($guid->is($guid)); - $this->assertTrue($guid->is(clone $guid)); - $this->assertTrue($guid->any($others[0], $others[1], clone $guid)); - $this->assertFalse($guid->is($others[0])); - $this->assertFalse($guid->is($others[1])); - $this->assertFalse($guid->is($others[2])); - $this->assertFalse($guid->is(null)); - $this->assertFalse($guid->any(...$others)); - $this->assertFalse($guid->any(null, ...$others)); $this->assertSame(['type' => $value, 'id' => '123'], $guid->context()); - $this->assertEquals($guid, Guid::fromString($type, '123')); - $this->assertObjectEquals($guid, Guid::fromString($type, '123')); - $this->assertFalse($guid->equals(Guid::fromInteger($type, 123))); } #[DataProvider('typeProvider')] @@ -108,47 +94,85 @@ public function it_can_be_created_from_an_integer_id( $this->assertObjectEquals(new IntegerId(123), $guid->id); $this->assertSame($value . ':123', $guid->toString()); $this->assertSame($value . ':123', (string) $guid); - $this->assertTrue($guid->isType($type)); - $this->assertTrue($guid->is($guid)); - $this->assertTrue($guid->is(clone $guid)); - $this->assertFalse($guid->is(Guid::fromString($type, '123'))); - $this->assertFalse($guid->is(Guid::fromInteger($type, 234))); - $this->assertFalse($guid->is(Guid::fromInteger($other, 123))); - $this->assertFalse($guid->is(null)); $this->assertSame(['type' => $value, 'id' => 123], $guid->context()); - $this->assertEquals($guid, Guid::fromInteger($type, 123)); - $this->assertObjectEquals($guid, Guid::fromInteger($type, 123)); - $this->assertFalse($guid->equals(Guid::fromString($type, '123'))); } #[DataProvider('typeProvider')] #[Test] - public function it_can_be_created_from_a_uuid( + public function it_can_be_created_from_a_base_uuid( string|UnitEnum $type, string $value, string|UnitEnum $other, string $otherValue, ): void { - $uuid = Uuid::random(); + $uuid = new Uuid(BaseUuid::fromString(self::UUID)); + $guid = Guid::fromUuid($type, $uuid->value); $this->assertSame($type, $guid->type); $this->assertTrue($uuid->is($guid->id)); - $this->assertObjectEquals($guid, Guid::fromUuid($type, $uuid)); - $this->assertSame($value . ':' . $uuid->toString(), $guid->toString()); - $this->assertSame($value . ':' . $uuid->toString(), (string) $guid); - $this->assertTrue($guid->isType($type)); - $this->assertTrue($guid->is($guid)); - $this->assertTrue($guid->is(clone $guid)); - $this->assertFalse($guid->is(Guid::fromUuid($other, $uuid->value))); - $this->assertFalse($guid->is(Guid::fromUuid($type, BaseUuid::uuid4()))); - $this->assertFalse($guid->is(Guid::fromString($type, $uuid->toString()))); - $this->assertFalse($guid->is(Guid::fromInteger($type, 234))); - $this->assertFalse($guid->is(null)); - $this->assertSame(['type' => $value, 'id' => $uuid->toString()], $guid->context()); - $this->assertObjectEquals($guid, Guid::fromUuid($type, $uuid->value)); + $this->assertSame($value . ':' . self::UUID, $guid->toString()); + $this->assertSame($value . ':' . self::UUID, (string) $guid); + $this->assertSame(['type' => $value, 'id' => self::UUID], $guid->context()); } + #[DataProvider('typeProvider')] + #[Test] + public function it_can_be_created_from_a_uuid_identifier( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { + $uuid = new Uuid(BaseUuid::fromString(self::UUID)); + + $actual = Guid::fromUuid($type, $uuid); + + $this->assertObjectEquals(Guid::fromUuid($type, $uuid->value), $actual); + } + + #[Test] + public function it_rejects_an_empty_type(): void + { + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Type must be a non-empty string.'); + + Guid::fromString('', '123'); + } + + #[Test] + public function it_rejects_an_empty_type_when_constructed(): void + { + $id = new IntegerId(1); + + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Type must be a non-empty string.'); + + new Guid('', $id); + } + + #[Test] + public function it_rejects_an_empty_string_id(): void + { + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Identifier value must be a non-empty string.'); + + Guid::fromString('SomeType', ''); + } + + #[Test] + public function it_rejects_a_negative_integer_id(): void + { + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Identifier value must be greater than zero.'); + + Guid::fromInteger('SomeType', -1); + } + + // ------------------------------------------------------------------------- + // make() + // ------------------------------------------------------------------------- + /** * @return array */ @@ -170,58 +194,241 @@ public static function makeProvider(): array public function it_makes_guid(int|IUuid|string|UuidInterface $value, Identifier $expected): void { $guid = Guid::make('SomeType', $value); + + $this->assertSame('SomeType', $guid->type); $this->assertTrue($expected->is($guid->id)); - $this->assertSame($guid, Guid::from($guid)); - $this->assertSame($guid, Guid::tryFrom($guid)); } + // ------------------------------------------------------------------------- + // from() and tryFrom() + // ------------------------------------------------------------------------- + #[Test] - public function it_does_not_accept_null(): void + public function it_returns_the_same_instance_when_created_from_a_guid(): void { - $this->assertNull(Guid::tryFrom(null)); + $guid = Guid::fromInteger('SomeType', 1); - $this->expectException(ContractException::class); - Guid::from(null); + $actual = Guid::from($guid); + + $this->assertSame($guid, $actual); } #[Test] - public function it_rejects_an_empty_type(): void + public function it_returns_the_same_instance_when_trying_from_a_guid(): void { - $this->expectException(ContractException::class); - Guid::fromString('', '123'); + $guid = Guid::fromInteger('SomeType', 1); + + $actual = Guid::tryFrom($guid); + + $this->assertSame($guid, $actual); + } + + /** + * @return array + */ + public static function notGuidProvider(): array + { + return [ + 'null' => [null], + 'integer id' => [new IntegerId(1)], + 'string id' => [new StringId('SomeType:1')], + 'uuid' => [new Uuid(BaseUuid::fromString(self::UUID))], + ]; } + #[DataProvider('notGuidProvider')] #[Test] - public function it_rejects_an_empty_string_id(): void + public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void { $this->expectException(ContractException::class); - Guid::fromString('SomeType', ''); + $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); + + Guid::from($other); } + #[DataProvider('notGuidProvider')] #[Test] - public function it_rejects_a_negative_integer_id(): void + public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { - $this->expectException(ContractException::class); - Guid::fromInteger('SomeType', -1); + $actual = Guid::tryFrom($other); + + $this->assertNull($actual); } + // ------------------------------------------------------------------------- + // is(), any() and equals() + // ------------------------------------------------------------------------- + + /** + * @return array + */ + public static function guidProvider(): array + { + return [ + 'string id' => [Guid::fromString('SomeType', '123')], + 'string id with enum type' => [Guid::fromString(TestUnitEnum::Baz, '123')], + 'integer id' => [Guid::fromInteger('SomeType', 123)], + 'integer id with enum type' => [Guid::fromInteger(TestBackedEnum::Foo, 123)], + 'uuid' => [Guid::fromUuid('SomeType', self::UUID)], + 'uuid with enum type' => [Guid::fromUuid(TestUnitEnum::Bat, self::UUID)], + ]; + } + + #[DataProvider('guidProvider')] #[Test] - public function it_wraps_an_integer_in_an_integer_id(): void + public function it_is_the_same_instance(Guid $guid): void + { + $actual = $guid->is($guid); + + $this->assertTrue($actual); + } + + #[DataProvider('guidProvider')] + #[Test] + public function it_is_a_guid_with_the_same_values(Guid $guid): void + { + $other = clone $guid; + + $actual = $guid->is($other); + + $this->assertTrue($actual); + } + + #[DataProvider('guidProvider')] + #[Test] + public function it_equals_a_guid_with_the_same_values(Guid $guid): void + { + $other = new Guid($guid->type, $guid->id); + + $this->assertObjectEquals($other, $guid); + } + + /** + * @return array + */ + public static function differentGuidProvider(): array + { + return [ + 'string id vs integer id' => [Guid::fromString('SomeType', '123'), Guid::fromInteger('SomeType', 123)], + 'different string id' => [Guid::fromString('SomeType', '123'), Guid::fromString('SomeType', '234')], + 'string id with different type' => [Guid::fromString('SomeType', '123'), Guid::fromString('Other', '123')], + 'string id with different enum type' => [ + Guid::fromString(TestUnitEnum::Baz, '123'), + Guid::fromString(TestUnitEnum::Bat, '123'), + ], + 'integer id vs string id' => [Guid::fromInteger('SomeType', 123), Guid::fromString('SomeType', '123')], + 'different integer id' => [Guid::fromInteger('SomeType', 123), Guid::fromInteger('SomeType', 234)], + 'integer id with different type' => [Guid::fromInteger('SomeType', 123), Guid::fromInteger('Other', 123)], + 'integer id with different enum type' => [ + Guid::fromInteger(TestBackedEnum::Foo, 123), + Guid::fromInteger(TestBackedEnum::Bar, 123), + ], + 'uuid with different type' => [Guid::fromUuid('SomeType', self::UUID), Guid::fromUuid('Other', self::UUID)], + 'different uuid' => [Guid::fromUuid('SomeType', self::UUID), Guid::fromUuid('SomeType', self::OTHER_UUID)], + 'uuid vs string id' => [Guid::fromUuid('SomeType', self::UUID), Guid::fromString('SomeType', self::UUID)], + 'uuid vs integer id' => [Guid::fromUuid('SomeType', self::UUID), Guid::fromInteger('SomeType', 234)], + ]; + } + + #[DataProvider('differentGuidProvider')] + #[Test] + public function it_is_not_a_guid_with_different_values(Guid $guid, Guid $other): void + { + $actual = $guid->is($other); + + $this->assertFalse($actual); + } + + #[DataProvider('differentGuidProvider')] + #[Test] + public function it_does_not_equal_a_guid_with_different_values(Guid $guid, Guid $other): void + { + $this->assertObjectNotEquals($other, $guid); + } + + #[DataProvider('notGuidProvider')] + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void { $guid = Guid::fromInteger('SomeType', 1); - $this->assertObjectEquals(new IntegerId(1), $guid->id); + + $actual = $guid->is($other); + + $this->assertFalse($actual); } + #[DataProvider('notGuidProvider')] #[Test] - public function it_wraps_a_string_in_a_string_id(): void + public function it_is_not_any_of_other_identifier_types(?Identifier $other): void { - $guid = Guid::fromString('SomeType', '1'); - $this->assertObjectEquals(new StringId('1'), $guid->id); + $guid = Guid::fromInteger('SomeType', 1); + + $actual = $guid->any($other); + + $this->assertFalse($actual); } #[DataProvider('typeProvider')] #[Test] - public function it_checks_if_it_is_any_of_multiple_types( + public function it_is_any_of_the_provided_guids_when_one_matches( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { + $guid = Guid::fromString($type, '123'); + + $actual = $guid->any(Guid::fromInteger($type, 123), Guid::fromString($type, '234'), clone $guid); + + $this->assertTrue($actual); + } + + #[DataProvider('typeProvider')] + #[Test] + public function it_is_not_any_of_the_provided_guids_when_none_match( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { + $guid = Guid::fromString($type, '123'); + + $actual = $guid->any( + Guid::fromInteger($type, 123), + Guid::fromString($type, '234'), + Guid::fromString($other, '123'), + ); + + $this->assertFalse($actual); + } + + #[DataProvider('typeProvider')] + #[Test] + public function it_is_not_any_of_the_provided_guids_including_null_when_none_match( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { + $guid = Guid::fromString($type, '123'); + + $actual = $guid->any( + null, + Guid::fromInteger($type, 123), + Guid::fromString($type, '234'), + Guid::fromString($other, '123'), + ); + + $this->assertFalse($actual); + } + + // ------------------------------------------------------------------------- + // isType() and assertType() + // ------------------------------------------------------------------------- + + #[DataProvider('typeProvider')] + #[Test] + public function it_is_the_type( string|UnitEnum $type, string $value, string|UnitEnum $other, @@ -229,9 +436,54 @@ public function it_checks_if_it_is_any_of_multiple_types( ): void { $guid = Guid::fromInteger($type, 1); - $this->assertTrue($guid->isType($other, $type)); - $this->assertFalse($guid->isType($other, 'Blah!')); - $this->assertFalse($guid->isType()); + $actual = $guid->isType($type); + + $this->assertTrue($actual); + } + + #[DataProvider('typeProvider')] + #[Test] + public function it_is_any_of_multiple_types( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { + $guid = Guid::fromInteger($type, 1); + + $actual = $guid->isType($other, $type); + + $this->assertTrue($actual); + } + + #[DataProvider('typeProvider')] + #[Test] + public function it_is_not_any_of_other_types( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { + $guid = Guid::fromInteger($type, 1); + + $actual = $guid->isType($other, 'Blah!'); + + $this->assertFalse($actual); + } + + #[DataProvider('typeProvider')] + #[Test] + public function it_is_not_a_type_when_no_types_are_provided( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { + $guid = Guid::fromInteger($type, 1); + + $actual = $guid->isType(); + + $this->assertFalse($actual); } #[DataProvider('typeProvider')] @@ -245,6 +497,7 @@ public function it_does_not_throw_when_asserting_the_expected_type( $guid = Guid::fromInteger($type, 1); $actual = $guid->assertType($type); + $this->assertSame($guid, $actual); } @@ -256,6 +509,8 @@ public function it_throws_when_asserting_an_unexpected_type( string|UnitEnum $other, string $otherValue, ): void { + $guid = Guid::fromInteger($type, 1); + $this->expectException(ContractException::class); $this->expectExceptionMessage(sprintf( 'Expecting type "%s", received "%s".', @@ -263,6 +518,51 @@ public function it_throws_when_asserting_an_unexpected_type( $value, )); - Guid::fromInteger($type, 1)->assertType($other); + $guid->assertType($other); + } + + #[Test] + public function it_throws_with_a_custom_message_when_asserting_an_unexpected_type(): void + { + $guid = Guid::fromInteger('SomeType', 1); + + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Not the expected type!'); + + $guid->assertType('OtherType', 'Not the expected type!'); + } + + // ------------------------------------------------------------------------- + // key() and toString() + // ------------------------------------------------------------------------- + + #[DataProvider('typeProvider')] + #[Test] + public function it_returns_a_key( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { + $guid = Guid::fromInteger($type, 123); + + $actual = $guid->key(); + + $this->assertSame($value . ':123', $actual); + } + + #[DataProvider('typeProvider')] + #[Test] + public function it_converts_to_a_string_with_a_custom_glue( + string|UnitEnum $type, + string $value, + string|UnitEnum $other, + string $otherValue, + ): void { + $guid = Guid::fromString($type, 'abc'); + + $actual = $guid->toString('/'); + + $this->assertSame($value . '/abc', $actual); } } diff --git a/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php b/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php index 215f8b8a..254049af 100644 --- a/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php +++ b/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php @@ -12,100 +12,139 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Identifiers; -use AssertionError; use CloudCreativity\Modules\Tests\TestBackedEnum; use CloudCreativity\Modules\Tests\TestBackedIntEnum; use CloudCreativity\Modules\Tests\TestUnitEnum; use CloudCreativity\Modules\Toolkit\Identifiers\Guid; use CloudCreativity\Modules\Toolkit\Identifiers\GuidTypeMap; -use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; -use PHPUnit\Framework\Attributes\Depends; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use UnitEnum; final class GuidTypeMapTest extends TestCase { + private const string UUID = '6dcbad65-ed92-4e60-973b-9ba58a022816'; + + /** + * @return array + */ + public static function stringTypeProvider(): array + { + return [ + 'a' => ['SomeTypeA', 'SomeOtherTypeA'], + 'b' => ['SomeTypeB', 'SomeOtherTypeB'], + 'c' => ['SomeTypeC', 'SomeOtherTypeC'], + ]; + } + + #[DataProvider('stringTypeProvider')] #[Test] - public function it_returns_expected_type(): GuidTypeMap + public function it_returns_expected_type(string $alias, string $expected): void { $map = new GuidTypeMap([ 'SomeTypeA' => 'SomeOtherTypeA', 'SomeTypeB' => 'SomeOtherTypeB', 'SomeTypeC' => 'SomeOtherTypeC', - 'NotString' => true, - 'EmptyString' => '', ]); - $this->assertSame('SomeOtherTypeA', $map->typeFor('SomeTypeA')); - $this->assertSame('SomeOtherTypeB', $map->typeFor('SomeTypeB')); - $this->assertSame('SomeOtherTypeC', $map->typeFor('SomeTypeC')); + $actual = $map->typeFor($alias); - return $map; + $this->assertSame($expected, $actual); } - #[Depends('it_returns_expected_type')] - #[Test] - public function it_returns_expected_guid(GuidTypeMap $map): void + /** + * @return array + */ + public static function stringGuidProvider(): array { - $this->assertEquals( - Guid::fromInteger('SomeOtherTypeA', 99), - $map->guidFor('SomeTypeA', 99), - ); - - $this->assertEquals( - Guid::fromString('SomeOtherTypeC', 'foobar'), - $map->guidFor('SomeTypeC', 'foobar'), - ); + return [ + 'integer id' => ['SomeTypeA', 99, Guid::fromInteger('SomeOtherTypeA', 99)], + 'string id' => ['SomeTypeC', 'foobar', Guid::fromString('SomeOtherTypeC', 'foobar')], + 'uuid' => ['SomeTypeB', self::UUID, Guid::fromUuid('SomeOtherTypeB', self::UUID)], + ]; } - #[Depends('it_returns_expected_type')] + #[DataProvider('stringGuidProvider')] #[Test] - public function it_throws_if_type_is_not_valid_string(GuidTypeMap $map): void + public function it_returns_expected_guid(string $alias, int|string $id, Guid $expected): void { - $this->expectException(AssertionError::class); - $this->expectExceptionMessage('Expecting type for alias "NotString" to be a non-empty string.'); + $map = new GuidTypeMap([ + 'SomeTypeA' => 'SomeOtherTypeA', + 'SomeTypeB' => 'SomeOtherTypeB', + 'SomeTypeC' => 'SomeOtherTypeC', + ]); - $map->typeFor('NotString'); + $actual = $map->guidFor($alias, $id); + + $this->assertObjectEquals($expected, $actual); } - #[Depends('it_returns_expected_type')] + /** + * @return array + */ + public static function enumTypeProvider(): array + { + return [ + 'backed enum to string' => [TestBackedEnum::Foo, 'SomeFooType'], + 'backed enum to enum' => [TestBackedEnum::Bar, TestBackedIntEnum::FooBar], + 'unit enum to string' => [TestUnitEnum::Baz, 'SomeBazType'], + 'unit enum to enum' => [TestUnitEnum::Bat, TestBackedIntEnum::BazBat], + ]; + } + + #[DataProvider('enumTypeProvider')] #[Test] - public function it_throws_if_type_is_empty_string(GuidTypeMap $map): void + public function it_returns_expected_type_with_enums(UnitEnum $alias, string|UnitEnum $expected): void { - $this->expectException(AssertionError::class); - $this->expectExceptionMessage('Expecting type for alias "EmptyString" to be a non-empty string.'); + $map = $this->makeEnumMap(); + + $actual = $map->typeFor($alias); - $map->typeFor('EmptyString'); + $this->assertSame($expected, $actual); } - #[Depends('it_returns_expected_type')] + #[DataProvider('enumTypeProvider')] #[Test] - public function it_throws_if_type_is_not_defined(GuidTypeMap $map): void + public function it_returns_expected_guid_with_enums(UnitEnum $alias, string|UnitEnum $type): void { - $this->expectException(AssertionError::class); - $this->expectExceptionMessage('Alias "NotDefined" is not defined in the type map.'); + $map = $this->makeEnumMap(); + + $actual = $map->guidFor($alias, self::UUID); - $map->typeFor('NotDefined'); + $this->assertObjectEquals(Guid::fromUuid($type, self::UUID), $actual); + } + + /** + * @return array + */ + public static function defineProvider(): array + { + return [ + 'string alias' => ['SomeAlias', 'SomeType'], + 'backed enum alias' => [TestBackedEnum::Foo, TestBackedIntEnum::FooBar], + 'unit enum alias' => [TestUnitEnum::Baz, 'SomeBazType'], + ]; } + #[DataProvider('defineProvider')] #[Test] - public function it_returns_expected_type_with_enums(): void + public function it_defines_a_type(string|UnitEnum $alias, string|UnitEnum $type): void { $map = new GuidTypeMap(); - $map->define(TestBackedEnum::Foo, 'SomeFooType'); - $map->define(TestBackedEnum::Bar, TestBackedIntEnum::FooBar); - $map->define(TestUnitEnum::Baz, 'SomeBazType'); - $map->define(TestUnitEnum::Bat, TestBackedIntEnum::BazBat); - - $id = Uuid::random(); - - $this->assertSame('SomeFooType', $map->typeFor(TestBackedEnum::Foo)); - $this->assertObjectEquals(Guid::fromUuid('SomeFooType', $id), $map->guidFor(TestBackedEnum::Foo, $id)); - $this->assertSame(TestBackedIntEnum::FooBar, $map->typeFor(TestBackedEnum::Bar)); - $this->assertObjectEquals(Guid::fromUuid(TestBackedIntEnum::FooBar, $id), $map->guidFor(TestBackedEnum::Bar, $id)); - $this->assertSame('SomeBazType', $map->typeFor(TestUnitEnum::Baz)); - $this->assertObjectEquals(Guid::fromUuid('SomeBazType', $id), $map->guidFor(TestUnitEnum::Baz, $id)); - $this->assertSame(TestBackedIntEnum::BazBat, $map->typeFor(TestUnitEnum::Bat)); - $this->assertObjectEquals(Guid::fromUuid(TestBackedIntEnum::BazBat, $id), $map->guidFor(TestUnitEnum::Bat, $id)); + + $map->define($alias, $type); + + $this->assertSame($type, $map->typeFor($alias)); + } + + private function makeEnumMap(): GuidTypeMap + { + return new GuidTypeMap([ + TestBackedEnum::Foo->value => 'SomeFooType', + TestBackedEnum::Bar->value => TestBackedIntEnum::FooBar, + TestUnitEnum::Baz->name => 'SomeBazType', + TestUnitEnum::Bat->name => TestBackedIntEnum::BazBat, + ]); } } diff --git a/tests/Unit/Toolkit/Identifiers/IdentifierFactoryTest.php b/tests/Unit/Toolkit/Identifiers/IdentifierFactoryTest.php new file mode 100644 index 00000000..f41103f8 --- /dev/null +++ b/tests/Unit/Toolkit/Identifiers/IdentifierFactoryTest.php @@ -0,0 +1,154 @@ +assertInstanceOf(IIdentifierFactory::class, $factory); + } + + /** + * @return array + */ + public static function identifierProvider(): array + { + return [ + 'integer id' => [new IntegerId(1)], + 'string id' => [new StringId('foo')], + 'uuid' => [Uuid::random()], + 'uuid v7' => [UuidV7::make()], + 'guid' => [Guid::fromInteger('SomeType', 1)], + ]; + } + + #[DataProvider('identifierProvider')] + #[Test] + public function it_returns_an_identifier_as_is(Identifier $id): void + { + $factory = new IdentifierFactory(); + + $actual = $factory->make($id); + + $this->assertSame($id, $actual); + } + + #[Test] + public function it_wraps_a_base_uuid(): void + { + $base = RamseyUuid::uuid4(); + $factory = new IdentifierFactory(); + + $actual = $factory->make($base); + + $this->assertObjectEquals(new Uuid($base), $actual); + } + + #[Test] + public function it_wraps_an_integer(): void + { + $factory = new IdentifierFactory(); + + $actual = $factory->make(123); + + $this->assertObjectEquals(new IntegerId(123), $actual); + } + + #[Test] + public function it_wraps_a_string(): void + { + $factory = new IdentifierFactory(); + + $actual = $factory->make('foo'); + + $this->assertObjectEquals(new StringId('foo'), $actual); + } + + #[Test] + public function it_wraps_a_uuid_string_in_a_string_id(): void + { + $value = RamseyUuid::uuid4()->toString(); + $factory = new IdentifierFactory(); + + $actual = $factory->make($value); + + $this->assertObjectEquals(new StringId($value), $actual); + } + + #[Test] + public function it_rejects_an_invalid_integer(): void + { + $factory = new IdentifierFactory(); + + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Identifier value must be greater than zero.'); + + $factory->make(0); + } + + #[Test] + public function it_rejects_an_empty_string(): void + { + $factory = new IdentifierFactory(); + + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Identifier value must be a non-empty string.'); + + $factory->make(''); + } + + /** + * @return array + */ + public static function invalidProvider(): array + { + return [ + 'null' => [null, 'null'], + 'float' => [1.5, 'float'], + 'bool' => [true, 'bool'], + 'array' => [[1], 'array'], + 'object' => [new stdClass(), 'stdClass'], + ]; + } + + #[DataProvider('invalidProvider')] + #[Test] + public function it_rejects_unexpected_values(mixed $value, string $type): void + { + $factory = new IdentifierFactory(); + + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Unexpected identifier type, received: ' . $type); + + $factory->make($value); + } +} diff --git a/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php b/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php index 00980f01..cd98f47e 100644 --- a/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php +++ b/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php @@ -18,10 +18,10 @@ use CloudCreativity\Modules\Toolkit\Identifiers\IntegerId; use CloudCreativity\Modules\Toolkit\Identifiers\StringId; use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; -use LogicException; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use Ramsey\Uuid\Uuid as RamseyUuid; final class IntegerIdTest extends TestCase { @@ -46,74 +46,172 @@ public function it_must_be_greater_than_zero(): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Identifier value must be greater than zero.'); + new IntegerId(0); } + // ------------------------------------------------------------------------- + // from() and tryFrom() + // ------------------------------------------------------------------------- + #[Test] - public function it_is_equals(): void + public function it_is_created_from_an_integer(): void { - $this->assertObjectEquals($id = new IntegerId(99), $other = IntegerId::from(99)); - $this->assertSame($id, IntegerId::from($id)); - $this->assertTrue($id->is($other)); - $this->assertTrue($id->any(new IntegerId(1), new IntegerId(2), $other)); - $this->assertEquals($id, IntegerId::tryFrom(99) ?? throw new LogicException()); - $this->assertSame($id, IntegerId::tryFrom($id)); + $actual = IntegerId::from(99); + + $this->assertObjectEquals(new IntegerId(99), $actual); } #[Test] - public function it_is_not_equal(): void + public function it_returns_the_same_instance_when_created_from_an_integer_id(): void { $id = new IntegerId(99); - $this->assertFalse($id->equals($other = new IntegerId(100))); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any($other, new IntegerId(200), new IntegerId(300))); - $this->assertFalse($id->any()); + + $actual = IntegerId::from($id); + + $this->assertSame($id, $actual); + } + + #[Test] + public function it_tries_to_create_from_an_integer(): void + { + $actual = IntegerId::tryFrom(99); + + $this->assertNotNull($actual); + $this->assertObjectEquals(new IntegerId(99), $actual); + } + + #[Test] + public function it_returns_the_same_instance_when_trying_from_an_integer_id(): void + { + $id = new IntegerId(99); + + $actual = IntegerId::tryFrom($id); + + $this->assertSame($id, $actual); } /** - * @return array> + * @return array */ public static function notIntegerIdProvider(): array { return [ - [null], - [new StringId('1')], - [new Guid('SomeType', new IntegerId(1))], - [new Uuid(\Ramsey\Uuid\Uuid::uuid4())], + 'null' => [null], + 'string id' => [new StringId('1')], + 'guid' => [new Guid('SomeType', new IntegerId(1))], + 'uuid' => [new Uuid(RamseyUuid::uuid4())], ]; } #[DataProvider('notIntegerIdProvider')] #[Test] - public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void + public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void { - $id = new IntegerId(1); + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any(new IntegerId(2), null, $other)); + IntegerId::from($other); } #[DataProvider('notIntegerIdProvider')] #[Test] public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { - $this->assertNull(IntegerId::tryFrom($other)); + $actual = IntegerId::tryFrom($other); + + $this->assertNull($actual); + } + + // ------------------------------------------------------------------------- + // is(), any() and equals() + // ------------------------------------------------------------------------- + + #[Test] + public function it_equals_an_integer_id_with_the_same_value(): void + { + $id = new IntegerId(99); + + $this->assertObjectEquals(new IntegerId(99), $id); + } + + #[Test] + public function it_does_not_equal_an_integer_id_with_a_different_value(): void + { + $id = new IntegerId(99); + + $this->assertObjectNotEquals(new IntegerId(100), $id); + } + + #[Test] + public function it_is_an_integer_id_with_the_same_value(): void + { + $id = new IntegerId(99); + + $actual = $id->is(new IntegerId(99)); + + $this->assertTrue($actual); } #[Test] - public function it_is_not_equal_to_null(): void + public function it_is_not_an_integer_id_with_a_different_value(): void + { + $id = new IntegerId(99); + + $actual = $id->is(new IntegerId(100)); + + $this->assertFalse($actual); + } + + #[DataProvider('notIntegerIdProvider')] + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void { $id = new IntegerId(1); - $this->assertFalse($id->is(null)); + $actual = $id->is($other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_any_of_the_provided_identifiers_when_one_matches(): void + { + $id = new IntegerId(99); + + $actual = $id->any(new IntegerId(1), new IntegerId(2), new IntegerId(99)); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_any_of_the_provided_identifiers_when_none_match(): void + { + $id = new IntegerId(99); + + $actual = $id->any(new IntegerId(100), new IntegerId(200), new IntegerId(300)); + + $this->assertFalse($actual); } #[DataProvider('notIntegerIdProvider')] #[Test] - public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void + public function it_is_not_any_of_other_identifier_types(?Identifier $other): void { - $this->expectException(ContractException::class); - $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); - IntegerId::from($other); + $id = new IntegerId(1); + + $actual = $id->any(new IntegerId(2), null, $other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_not_any_when_no_identifiers_are_provided(): void + { + $id = new IntegerId(99); + + $actual = $id->any(); + + $this->assertFalse($actual); } } diff --git a/tests/Unit/Toolkit/Identifiers/IsIdentifierTest.php b/tests/Unit/Toolkit/Identifiers/IsIdentifierTest.php new file mode 100644 index 00000000..cdff67ba --- /dev/null +++ b/tests/Unit/Toolkit/Identifiers/IsIdentifierTest.php @@ -0,0 +1,60 @@ +any(new TestIdentifier('bar'), null, new TestIdentifier('foo')); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_any_of_the_provided_identifiers_when_none_match(): void + { + $id = new TestIdentifier('foo'); + + $actual = $id->any(new TestIdentifier('bar'), new IntegerId(1), new TestIdentifier('baz')); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_not_any_of_only_null_identifiers(): void + { + $id = new TestIdentifier('foo'); + + $actual = $id->any(null, null); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_not_any_when_no_identifiers_are_provided(): void + { + $id = new TestIdentifier('foo'); + + $actual = $id->any(); + + $this->assertFalse($actual); + } +} diff --git a/tests/Unit/Toolkit/Identifiers/IsUuidTest.php b/tests/Unit/Toolkit/Identifiers/IsUuidTest.php new file mode 100644 index 00000000..2303245c --- /dev/null +++ b/tests/Unit/Toolkit/Identifiers/IsUuidTest.php @@ -0,0 +1,170 @@ + $uuid->toString(), + 'cast' => (string) $uuid, + 'key' => $uuid->key(), + 'context' => $uuid->context(), + 'json' => $uuid->jsonSerialize(), + ]; + + $this->assertSame([ + 'toString' => self::UUID, + 'cast' => self::UUID, + 'key' => self::UUID, + 'context' => self::UUID, + 'json' => self::UUID, + ], $actual); + } + + #[Test] + public function it_returns_the_bytes(): void + { + $base = RamseyUuid::fromString(self::UUID); + $uuid = new TestUuid($base); + + $actual = $uuid->getBytes(); + + $this->assertSame($base->getBytes(), $actual); + } + + #[Test] + public function it_returns_the_base_uuid(): void + { + $base = RamseyUuid::fromString(self::UUID); + $uuid = new TestUuid($base); + + $actual = $uuid->toBase(); + + $this->assertSame($base, $actual); + } + + #[Test] + public function it_is_the_same_as_another_uuid_class_with_the_same_value(): void + { + $uuid = new TestUuid(RamseyUuid::fromString(self::UUID)); + $other = new Uuid(RamseyUuid::fromString(self::UUID)); + + $actual = $uuid->is($other); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_the_same_as_a_uuid_with_a_different_value(): void + { + $uuid = new TestUuid(RamseyUuid::fromString(self::UUID)); + $other = new TestUuid(RamseyUuid::fromString(self::OTHER_UUID)); + + $actual = $uuid->is($other); + + $this->assertFalse($actual); + } + + /** + * @return array + */ + public static function notUuidProvider(): array + { + return [ + 'null' => [null], + 'integer id' => [new IntegerId(1)], + 'string id' => [new StringId(self::UUID)], + 'guid' => [Guid::fromUuid('SomeType', self::UUID)], + ]; + } + + #[DataProvider('notUuidProvider')] + #[Test] + public function it_is_not_the_same_as_other_identifier_types(?Identifier $other): void + { + $uuid = new TestUuid(RamseyUuid::fromString(self::UUID)); + + $actual = $uuid->is($other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_any_of_the_provided_identifiers(): void + { + $uuid = new TestUuid(RamseyUuid::fromString(self::UUID)); + + $actual = $uuid->any(null, new StringId(self::UUID), new Uuid(RamseyUuid::fromString(self::UUID))); + + $this->assertTrue($actual); + } + + #[Test] + public function it_equals_a_uuid_with_the_same_value(): void + { + $uuid = new TestUuid(RamseyUuid::fromString(self::UUID)); + + $this->assertObjectEquals(new TestUuid(RamseyUuid::fromString(self::UUID)), $uuid); + } + + #[Test] + public function it_does_not_equal_a_uuid_with_a_different_value(): void + { + $uuid = new TestUuid(RamseyUuid::fromString(self::UUID)); + + $this->assertObjectNotEquals(new TestUuid(RamseyUuid::fromString(self::OTHER_UUID)), $uuid); + } + + /** + * @return array + */ + public static function compareProvider(): array + { + return [ + 'equal' => [self::UUID, 0], + 'less than' => ['7dcbad65-ed92-4e60-973b-9ba58a022816', -1], + 'greater than' => ['5dcbad65-ed92-4e60-973b-9ba58a022816', 1], + ]; + } + + #[DataProvider('compareProvider')] + #[Test] + public function it_compares_to_another_uuid(string $other, int $expected): void + { + $uuid = new TestUuid(RamseyUuid::fromString(self::UUID)); + + $actual = $uuid->compareTo(UuidV4::from($other)); + + $this->assertSame($expected, $actual); + } +} diff --git a/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php b/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php index 1b438c4d..965ac52a 100644 --- a/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php +++ b/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php @@ -22,17 +22,17 @@ final class PossiblyNumericIdTest extends TestCase { /** - * @return array> + * @return array */ public static function valueProvider(): array { return [ - [1, 1], - ['1', 1], - ['0001', 1], - ['999', 999], - ['foobar', 'foobar'], - [' 0009 ', ' 0009 '], + 'integer' => [1, 1], + 'numeric string' => ['1', 1], + 'numeric string with leading zeros' => ['0001', 1], + 'larger numeric string' => ['999', 999], + 'non-numeric string' => ['foobar', 'foobar'], + 'numeric string with whitespace' => [' 0009 ', ' 0009 '], ]; } @@ -41,16 +41,40 @@ public static function valueProvider(): array public function it_converts_numeric_strings_to_integers(int|string $value, int|string $expected): void { $actual = new PossiblyNumericId($value); - $expectedId = is_string($expected) ? new StringId($expected) : new IntegerId($expected); $this->assertSame($expected, $actual->value); - $this->assertSame($expected, PossiblyNumericId::from($value)->value); - $this->assertSame((string) $expected, (string) $actual); $this->assertSame((string) $expected, $actual->toString()); - $this->assertObjectEquals($expectedId, $actual->toId()); - $this->assertJsonStringEqualsJsonString( - json_encode(['value' => $expected], JSON_THROW_ON_ERROR), - json_encode(['value' => $actual], JSON_THROW_ON_ERROR), - ); + $this->assertSame((string) $expected, (string) $actual); + } + + #[DataProvider('valueProvider')] + #[Test] + public function it_is_created_using_from(int|string $value, int|string $expected): void + { + $actual = PossiblyNumericId::from($value); + + $this->assertSame($expected, $actual->value); + } + + #[DataProvider('valueProvider')] + #[Test] + public function it_converts_to_an_identifier(int|string $value, int|string $expected): void + { + $id = new PossiblyNumericId($value); + + $actual = $id->toId(); + + $this->assertObjectEquals(is_string($expected) ? new StringId($expected) : new IntegerId($expected), $actual); + } + + #[DataProvider('valueProvider')] + #[Test] + public function it_serializes_to_json(int|string $value, int|string $expected): void + { + $id = new PossiblyNumericId($value); + + $actual = json_encode(['value' => $id], JSON_THROW_ON_ERROR); + + $this->assertJsonStringEqualsJsonString(json_encode(['value' => $expected], JSON_THROW_ON_ERROR), $actual); } } diff --git a/tests/Unit/Toolkit/Identifiers/StringIdTest.php b/tests/Unit/Toolkit/Identifiers/StringIdTest.php index 91724a10..0b9ca147 100644 --- a/tests/Unit/Toolkit/Identifiers/StringIdTest.php +++ b/tests/Unit/Toolkit/Identifiers/StringIdTest.php @@ -21,6 +21,7 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use Ramsey\Uuid\Uuid as RamseyUuid; final class StringIdTest extends TestCase { @@ -44,6 +45,7 @@ public function it_wraps_a_string(): void public function it_can_be_zero(): void { $id = new StringId('0'); + $this->assertSame('0', $id->value); } @@ -52,66 +54,172 @@ public function it_must_not_be_empty(): void { $this->expectException(ContractException::class); $this->expectExceptionMessage('Identifier value must be a non-empty string.'); + new StringId(''); } + // ------------------------------------------------------------------------- + // from() and tryFrom() + // ------------------------------------------------------------------------- + #[Test] - public function it_is_equals(): void + public function it_is_created_from_a_string(): void { - $this->assertObjectEquals($id = new StringId('99'), $other = StringId::from('99')); - $this->assertSame($id, StringId::from($id)); - $this->assertTrue($id->is($other)); - $this->assertTrue($id->any(new StringId('foo'), new StringId('bar'), null, $other)); - $this->assertEquals($id, StringId::tryFrom('99')); - $this->assertSame($id, StringId::tryFrom($id)); + $actual = StringId::from('99'); + + $this->assertObjectEquals(new StringId('99'), $actual); } #[Test] - public function it_is_not_equal(): void + public function it_returns_the_same_instance_when_created_from_a_string_id(): void { $id = new StringId('99'); - $this->assertFalse($id->equals($other = new StringId('100'))); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any(new StringId('foo'), new StringId('bar'), null, $other)); - $this->assertFalse($id->any()); + + $actual = StringId::from($id); + + $this->assertSame($id, $actual); + } + + #[Test] + public function it_tries_to_create_from_a_string(): void + { + $actual = StringId::tryFrom('99'); + + $this->assertNotNull($actual); + $this->assertObjectEquals(new StringId('99'), $actual); + } + + #[Test] + public function it_returns_the_same_instance_when_trying_from_a_string_id(): void + { + $id = new StringId('99'); + + $actual = StringId::tryFrom($id); + + $this->assertSame($id, $actual); } /** - * @return array> + * @return array */ public static function notStringIdProvider(): array { return [ - [null], - [new IntegerId(1)], - [new Guid('SomeType', new StringId('1'))], - [new Uuid(\Ramsey\Uuid\Uuid::uuid4())], + 'null' => [null], + 'integer id' => [new IntegerId(1)], + 'guid' => [new Guid('SomeType', new StringId('1'))], + 'uuid' => [new Uuid(RamseyUuid::uuid4())], ]; } #[DataProvider('notStringIdProvider')] #[Test] - public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void + public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void { - $id = new StringId('1'); + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any($other, new StringId('foo'), null)); + StringId::from($other); } #[DataProvider('notStringIdProvider')] #[Test] public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { - $this->assertNull(StringId::tryFrom($other)); + $actual = StringId::tryFrom($other); + + $this->assertNull($actual); + } + + // ------------------------------------------------------------------------- + // is(), any() and equals() + // ------------------------------------------------------------------------- + + #[Test] + public function it_equals_a_string_id_with_the_same_value(): void + { + $id = new StringId('99'); + + $this->assertObjectEquals(new StringId('99'), $id); + } + + #[Test] + public function it_does_not_equal_a_string_id_with_a_different_value(): void + { + $id = new StringId('99'); + + $this->assertObjectNotEquals(new StringId('100'), $id); + } + + #[Test] + public function it_is_a_string_id_with_the_same_value(): void + { + $id = new StringId('99'); + + $actual = $id->is(new StringId('99')); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_a_string_id_with_a_different_value(): void + { + $id = new StringId('99'); + + $actual = $id->is(new StringId('100')); + + $this->assertFalse($actual); } #[DataProvider('notStringIdProvider')] #[Test] - public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void { - $this->expectException(ContractException::class); - $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); - StringId::from($other); + $id = new StringId('1'); + + $actual = $id->is($other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_any_of_the_provided_identifiers_when_one_matches(): void + { + $id = new StringId('99'); + + $actual = $id->any(new StringId('foo'), new StringId('bar'), null, new StringId('99')); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_any_of_the_provided_identifiers_when_none_match(): void + { + $id = new StringId('99'); + + $actual = $id->any(new StringId('foo'), new StringId('bar'), null, new StringId('100')); + + $this->assertFalse($actual); + } + + #[DataProvider('notStringIdProvider')] + #[Test] + public function it_is_not_any_of_other_identifier_types(?Identifier $other): void + { + $id = new StringId('1'); + + $actual = $id->any($other, new StringId('foo'), null); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_not_any_when_no_identifiers_are_provided(): void + { + $id = new StringId('99'); + + $actual = $id->any(); + + $this->assertFalse($actual); } } diff --git a/tests/Unit/Toolkit/Identifiers/TestIdentifier.php b/tests/Unit/Toolkit/Identifiers/TestIdentifier.php new file mode 100644 index 00000000..9e40f786 --- /dev/null +++ b/tests/Unit/Toolkit/Identifiers/TestIdentifier.php @@ -0,0 +1,50 @@ +value; + } + + public function is(?Identifier $other): bool + { + return $other instanceof self && $this->value === $other->value; + } + + public function toString(): string + { + return $this->value; + } + + public function key(): string + { + return $this->value; + } + + public function context(): string + { + return $this->value; + } +} diff --git a/tests/Unit/Toolkit/Identifiers/TestUuid.php b/tests/Unit/Toolkit/Identifiers/TestUuid.php new file mode 100644 index 00000000..4391f50e --- /dev/null +++ b/tests/Unit/Toolkit/Identifiers/TestUuid.php @@ -0,0 +1,26 @@ +baseFactory ->expects($this->never()) ->method($this->anything()); - $uuid = $this->factory->from($base = BaseUuid::uuid4()); + $uuid = $this->factory->from($base); $this->assertInstanceOf(Uuid::class, $uuid); $this->assertSame($base, $uuid->value); @@ -65,11 +67,13 @@ public function it_wraps_a_base_uuid(): void #[Test] public function it_returns_the_same_uuid_instance(): void { + $expected = Uuid::random(); + $this->baseFactory ->expects($this->never()) ->method($this->anything()); - $actual = $this->factory->from($expected = Uuid::random()); + $actual = $this->factory->from($expected); $this->assertSame($expected, $actual); } @@ -77,15 +81,16 @@ public function it_returns_the_same_uuid_instance(): void #[Test] public function it_rejects_a_non_uuid_identifier(): void { + $id = new IntegerId(1); + $this->baseFactory ->expects($this->never()) ->method($this->anything()); $this->expectException(ContractException::class); + $this->expectExceptionMessage('Unexpected identifier type, received: ' . IntegerId::class); - $this->factory->from( - $this->createStub(Identifier::class), - ); + $this->factory->from($id); } #[Test] @@ -100,7 +105,7 @@ public function it_creates_from_bytes(): void $uuid = $this->factory->fromBytes($bytes); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] @@ -119,7 +124,7 @@ public function it_creates_from_a_date_time(): void $uuid = $this->factory->fromDateTime($dateTime, $hex, $int); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] @@ -134,7 +139,7 @@ public function it_creates_from_an_integer(): void $uuid = $this->factory->fromInteger($integer); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] @@ -149,7 +154,7 @@ public function it_creates_from_a_string(): void $uuid = $this->factory->fromString($string); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] @@ -167,7 +172,7 @@ public function it_creates_a_uuid_v1(): void $uuid = $this->factory->uuid1($hex, $int); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] @@ -187,7 +192,7 @@ public function it_creates_a_uuid_v2(): void $uuid = $this->factory->uuid2($int, $integer, $hex, $seq); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] @@ -205,7 +210,7 @@ public function it_creates_a_uuid_v3(): void $uuid = $this->factory->uuid3($ns, $name); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] @@ -219,7 +224,7 @@ public function it_creates_a_uuid_v4(): void $uuid = $this->factory->uuid4(); $this->assertInstanceOf(UuidV4::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] @@ -237,7 +242,7 @@ public function it_creates_a_uuid_v5(): void $uuid = $this->factory->uuid5($ns, $name); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] @@ -255,13 +260,13 @@ public function it_creates_a_uuid_v6(): void $uuid = $this->factory->uuid6($hex, $int); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] public function it_creates_a_uuid_v7(): void { - $date = new \DateTimeImmutable(); + $date = new DateTimeImmutable(); $this->baseFactory ->expects($this->once()) @@ -272,20 +277,20 @@ public function it_creates_a_uuid_v7(): void $uuid = $this->factory->uuid7($date); $this->assertInstanceOf(UuidV7::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] public function it_throws_if_uuid_v7_is_not_supported(): void { - $this->baseFactory - ->expects($this->never()) - ->method($this->anything()); - $factory = new UuidFactory( $this->createStub(BaseUuidFactoryInterface::class), ); + $this->baseFactory + ->expects($this->never()) + ->method($this->anything()); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('UUID version 7 is not supported by the underlying factory.'); @@ -306,20 +311,20 @@ public function it_creates_a_uuid_v8(): void $uuid = $this->factory->uuid8($bytes); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertSame($uuid->value, $base); + $this->assertSame($base, $uuid->value); } #[Test] public function it_throws_if_uuid_v8_is_not_supported(): void { - $this->baseFactory - ->expects($this->never()) - ->method($this->anything()); - $factory = new UuidFactory( $this->createStub(BaseUuidFactoryInterface::class), ); + $this->baseFactory + ->expects($this->never()) + ->method($this->anything()); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('UUID version 8 is not supported by the underlying factory.'); diff --git a/tests/Unit/Toolkit/Identifiers/UuidTest.php b/tests/Unit/Toolkit/Identifiers/UuidTest.php index 6025e2a4..2e998d6b 100644 --- a/tests/Unit/Toolkit/Identifiers/UuidTest.php +++ b/tests/Unit/Toolkit/Identifiers/UuidTest.php @@ -19,6 +19,8 @@ use CloudCreativity\Modules\Toolkit\Identifiers\IntegerId; use CloudCreativity\Modules\Toolkit\Identifiers\StringId; use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; +use CloudCreativity\Modules\Toolkit\Identifiers\UuidFactory as ConcreteUuidFactory; +use CloudCreativity\Modules\Toolkit\Identifiers\UuidV4; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -26,6 +28,10 @@ final class UuidTest extends TestCase { + private const string UUID = '6dcbad65-ed92-4e60-973b-9ba58a022816'; + + private const string OTHER_UUID = '38c7be26-6887-4742-8b6b-7d07b30ca596'; + protected function tearDown(): void { Uuid::setFactory(null); @@ -36,6 +42,7 @@ protected function tearDown(): void public function it_wraps_a_ramsey_uuid(): void { $base = RamseyUuid::uuid4(); + $id = new Uuid($base); $this->assertSame($base, $id->value); @@ -51,148 +58,364 @@ public function it_wraps_a_ramsey_uuid(): void } #[Test] - public function it_is_equals(): void + public function it_creates_a_nil_uuid(): void { - $base = RamseyUuid::uuid4(); - $id = new Uuid($base); + $base = RamseyUuid::fromString(RamseyUuid::NIL); - $this->assertTrue($id->is($other = Uuid::from($base))); - $this->assertSame($id, Uuid::from($id)); - $this->assertTrue($id->is($other)); - $this->assertTrue($id->any(null, Uuid::random(), $other)); - $this->assertEquals($id, Uuid::tryFrom($base)); - $this->assertSame($id, Uuid::tryFrom($id)); + $actual = Uuid::nil(); + + $this->assertTrue($actual->toBase()->equals($base)); } #[Test] - public function it_is_not_equal(): void + public function it_can_be_compared_for_sorting(): void { - $id = new Uuid(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')); - $this->assertFalse($id->is($other = new Uuid( - RamseyUuid::fromString('38c7be26-6887-4742-8b6b-7d07b30ca596'), - ))); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any(null, Uuid::random(), $other)); + $uuid1 = Uuid::random(); + $uuid2 = Uuid::random(); + $uuid3 = Uuid::random(); + $expected = [$uuid3->value, $uuid1->value, $uuid2->value]; + usort($expected, fn ($a, $b) => $a->compareTo($b)); + $actual = [$uuid2, $uuid1, $uuid3]; + + usort($actual, fn ($a, $b) => $a->compareTo($b)); + + $this->assertSame($expected, array_map(fn ($id) => $id->value, $actual)); } - /** - * @return array> - */ - public static function notUuidProvider(): array + // ------------------------------------------------------------------------- + // from() and tryFrom() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_the_same_instance_when_created_from_a_uuid(): void { - return [ - [null], - [new IntegerId(1)], - [new StringId('foo')], - [new Guid('SomeType', new Uuid(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')))], - ]; + $id = new Uuid(RamseyUuid::uuid4()); + + $actual = Uuid::from($id); + + $this->assertSame($id, $actual); } - #[DataProvider('notUuidProvider')] #[Test] - public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void + public function it_returns_the_same_instance_when_trying_from_a_uuid(): void { - $id = new Uuid(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')); + $id = new Uuid(RamseyUuid::uuid4()); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any(null, Uuid::random(), $other)); - $this->assertFalse($id->any()); + $actual = Uuid::tryFrom($id); + + $this->assertSame($id, $actual); } - #[DataProvider('notUuidProvider')] #[Test] - public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void + public function it_returns_the_same_instance_when_created_from_another_uuid_type(): void { - $this->expectException(ContractException::class); - $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); - Uuid::from($other); + $other = UuidV4::make(); + + $actual = Uuid::from($other); + + $this->assertSame($other, $actual); } - #[DataProvider('notUuidProvider')] #[Test] - public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void + public function it_returns_the_same_instance_when_trying_from_another_uuid_type(): void { - $this->assertNull(Uuid::tryFrom($other)); + $other = UuidV4::make(); + + $actual = Uuid::tryFrom($other); + + $this->assertSame($other, $actual); } #[Test] public function it_can_be_created_from_a_string(): void { - Uuid::setFactory($factory = $this->createMock(UuidFactory::class)); + $factory = $this->createMock(UuidFactory::class); + Uuid::setFactory($factory); + $expected = new Uuid(RamseyUuid::uuid4()); $factory ->expects($this->once()) ->method('fromString') - ->with($str = 'blah!') - ->willReturn($expected = new Uuid(RamseyUuid::uuid4())); + ->with('blah!') + ->willReturn($expected); - $this->assertSame($expected, Uuid::from($str)); + $actual = Uuid::from('blah!'); + + $this->assertSame($expected, $actual); } #[Test] public function it_can_try_to_create_from_a_string(): void { - Uuid::setFactory($factory = $this->createMock(UuidFactory::class)); + $factory = $this->createMock(UuidFactory::class); + Uuid::setFactory($factory); + $expected = new Uuid(RamseyUuid::fromString(self::UUID)); $factory ->expects($this->once()) ->method('fromString') - ->with($valid = '10562dcc-faf0-4444-91b9-a9d374e5501f') - ->willReturn($expected = new Uuid(RamseyUuid::fromString('10562dcc-faf0-4444-91b9-a9d374e5501f'))); + ->with(self::UUID) + ->willReturn($expected); + + $actual = Uuid::tryFrom(self::UUID); + + $this->assertSame($expected, $actual); + } - $this->assertSame($expected, Uuid::tryFrom($valid)); - $this->assertNull(Uuid::tryFrom('invalid')); + #[Test] + public function it_returns_null_when_trying_from_an_invalid_string(): void + { + $factory = $this->createMock(UuidFactory::class); + Uuid::setFactory($factory); + + $factory + ->expects($this->never()) + ->method($this->anything()); + + $actual = Uuid::tryFrom('invalid'); + + $this->assertNull($actual); } #[Test] public function it_can_be_created_from_a_base_uuid(): void { - Uuid::setFactory($factory = $this->createMock(UuidFactory::class)); + $factory = $this->createMock(UuidFactory::class); + Uuid::setFactory($factory); + $base = RamseyUuid::uuid4(); + $expected = new Uuid($base); $factory - ->expects($this->exactly(2)) + ->expects($this->once()) ->method('from') - ->with($this->identicalTo($base = RamseyUuid::uuid4())) - ->willReturn($expected = new Uuid($base)); + ->with($this->identicalTo($base)) + ->willReturn($expected); - $this->assertSame($expected, Uuid::from($base)); - $this->assertSame($expected, Uuid::tryFrom($base)); + $actual = Uuid::from($base); + + $this->assertSame($expected, $actual); + } + + #[Test] + public function it_can_try_to_create_from_a_base_uuid(): void + { + $factory = $this->createMock(UuidFactory::class); + Uuid::setFactory($factory); + $base = RamseyUuid::uuid4(); + $expected = new Uuid($base); + + $factory + ->expects($this->once()) + ->method('from') + ->with($this->identicalTo($base)) + ->willReturn($expected); + + $actual = Uuid::tryFrom($base); + + $this->assertSame($expected, $actual); } #[Test] public function it_returns_null_when_trying_from_null(): void { - Uuid::setFactory($factory = $this->createMock(UuidFactory::class)); + $factory = $this->createMock(UuidFactory::class); + Uuid::setFactory($factory); $factory ->expects($this->never()) ->method($this->anything()); - $this->assertNull(Uuid::tryFrom(null)); + $actual = Uuid::tryFrom(null); + + $this->assertNull($actual); } + /** + * @return array + */ + public static function notUuidProvider(): array + { + return [ + 'null' => [null], + 'integer id' => [new IntegerId(1)], + 'string id' => [new StringId('foo')], + 'guid' => [new Guid('SomeType', new Uuid(RamseyUuid::fromString(self::UUID)))], + ]; + } + + #[DataProvider('notUuidProvider')] #[Test] - public function it_creates_a_nil_uuid(): void + public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void { - $base = RamseyUuid::fromString(RamseyUuid::NIL); - $actual = Uuid::nil(); + $this->expectException(ContractException::class); + $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); - $this->assertTrue($actual->toBase()->equals($base)); + Uuid::from($other); } + #[DataProvider('notUuidProvider')] #[Test] - public function it_can_be_compared_for_sorting(): void + public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { - $uuid1 = Uuid::random(); - $uuid2 = Uuid::random(); - $uuid3 = Uuid::random(); + $actual = Uuid::tryFrom($other); - $expected = [$uuid3->value, $uuid1->value, $uuid2->value]; - usort($expected, fn ($a, $b) => $a->compareTo($b)); + $this->assertNull($actual); + } - $actual = [$uuid2, $uuid1, $uuid3]; - usort($actual, fn ($a, $b) => $a->compareTo($b)); - $actual = array_map(fn ($id) => $id->value, $actual); + // ------------------------------------------------------------------------- + // is(), any() and equals() + // ------------------------------------------------------------------------- + + #[Test] + public function it_equals_a_uuid_with_the_same_value(): void + { + $id = new Uuid(RamseyUuid::fromString(self::UUID)); + + $this->assertObjectEquals(new Uuid(RamseyUuid::fromString(self::UUID)), $id); + } + + #[Test] + public function it_does_not_equal_a_uuid_with_a_different_value(): void + { + $id = new Uuid(RamseyUuid::fromString(self::UUID)); + + $this->assertObjectNotEquals(new Uuid(RamseyUuid::fromString(self::OTHER_UUID)), $id); + } + + #[Test] + public function it_is_a_uuid_with_the_same_value(): void + { + $base = RamseyUuid::uuid4(); + $id = new Uuid($base); + + $actual = $id->is(new Uuid($base)); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_a_uuid_with_a_different_value(): void + { + $id = new Uuid(RamseyUuid::fromString(self::UUID)); + + $actual = $id->is(new Uuid(RamseyUuid::fromString(self::OTHER_UUID))); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_the_same_as_a_uuid_v4_with_the_same_value(): void + { + $other = UuidV4::make(); + $id = new Uuid($other->value); + + $actual = $id->is($other); + + $this->assertTrue($actual); + } + + #[DataProvider('notUuidProvider')] + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void + { + $id = new Uuid(RamseyUuid::fromString(self::UUID)); + + $actual = $id->is($other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_any_of_the_provided_identifiers_when_one_matches(): void + { + $base = RamseyUuid::uuid4(); + $id = new Uuid($base); + + $actual = $id->any(null, Uuid::random(), new Uuid($base)); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_any_of_the_provided_identifiers_when_none_match(): void + { + $id = new Uuid(RamseyUuid::fromString(self::UUID)); + + $actual = $id->any(null, Uuid::random(), new Uuid(RamseyUuid::fromString(self::OTHER_UUID))); + + $this->assertFalse($actual); + } + + #[DataProvider('notUuidProvider')] + #[Test] + public function it_is_not_any_of_other_identifier_types(?Identifier $other): void + { + $id = new Uuid(RamseyUuid::fromString(self::UUID)); + + $actual = $id->any(null, Uuid::random(), $other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_not_any_when_no_identifiers_are_provided(): void + { + $id = new Uuid(RamseyUuid::fromString(self::UUID)); + + $actual = $id->any(); + + $this->assertFalse($actual); + } + + // ------------------------------------------------------------------------- + // Factory + // ------------------------------------------------------------------------- + + #[Test] + public function it_uses_a_default_factory(): void + { + Uuid::setFactory(null); + + $actual = Uuid::getFactory(); + + $this->assertInstanceOf(ConcreteUuidFactory::class, $actual); + } + + #[Test] + public function it_reuses_the_default_factory(): void + { + Uuid::setFactory(null); + $expected = Uuid::getFactory(); + + $actual = Uuid::getFactory(); + + $this->assertSame($expected, $actual); + } + + #[Test] + public function it_uses_the_provided_factory(): void + { + $factory = $this->createStub(UuidFactory::class); + Uuid::setFactory($factory); + + $actual = Uuid::getFactory(); + + $this->assertSame($factory, $actual); + } + + #[Test] + public function it_generates_a_random_uuid_using_the_factory(): void + { + $expected = UuidV4::make(); + $factory = $this->createMock(UuidFactory::class); + Uuid::setFactory($factory); + + $factory + ->expects($this->once()) + ->method('uuid4') + ->willReturn($expected); + + $actual = Uuid::random(); $this->assertSame($expected, $actual); } diff --git a/tests/Unit/Toolkit/Identifiers/UuidV4Test.php b/tests/Unit/Toolkit/Identifiers/UuidV4Test.php index bfbe66a5..30b0fe02 100644 --- a/tests/Unit/Toolkit/Identifiers/UuidV4Test.php +++ b/tests/Unit/Toolkit/Identifiers/UuidV4Test.php @@ -23,14 +23,20 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Uuid as RamseyUuid; final class UuidV4Test extends TestCase { + private const string UUID = '6dcbad65-ed92-4e60-973b-9ba58a022816'; + + private const string OTHER_UUID = '38c7be26-6887-4742-8b6b-7d07b30ca596'; + #[Test] public function it_wraps_a_ramsey_uuid(): void { $base = RamseyUuid::uuid4(); + $id = UuidV4::from($base); $this->assertSame($base, $id->value); @@ -46,55 +52,116 @@ public function it_wraps_a_ramsey_uuid(): void } #[Test] - public function it_is_equals(): void + public function it_accepts_a_lazy_uuid_v4(): void + { + $base = new LazyUuidFromString(RamseyUuid::uuid4()->toString()); + + $actual = new UuidV4($base); + + $this->assertSame($base, $actual->value); + } + + #[Test] + public function it_rejects_a_lazy_uuid_of_another_version(): void + { + $base = new LazyUuidFromString(RamseyUuid::uuid7()->toString()); + + $this->expectException(ContractException::class); + + new UuidV4($base); + } + + #[Test] + public function it_can_be_compared_for_sorting(): void + { + $uuid1 = UuidV4::make(); + $uuid2 = UuidV4::make(); + $uuid3 = UuidV4::make(); + $expected = [$uuid3->value, $uuid1->value, $uuid2->value]; + usort($expected, fn ($a, $b) => $a->compareTo($b)); + $actual = [$uuid2, $uuid1, $uuid3]; + + usort($actual, fn ($a, $b) => $a->compareTo($b)); + + $this->assertSame($expected, array_map(fn ($id) => $id->value, $actual)); + } + + // ------------------------------------------------------------------------- + // from() and tryFrom() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_the_same_instance_when_created_from_a_uuid_v4(): void + { + $id = UuidV4::make(); + + $actual = UuidV4::from($id); + + $this->assertSame($id, $actual); + } + + #[Test] + public function it_returns_the_same_instance_when_trying_from_a_uuid_v4(): void + { + $id = UuidV4::make(); + + $actual = UuidV4::tryFrom($id); + + $this->assertSame($id, $actual); + } + + #[Test] + public function it_tries_to_create_from_a_ramsey_uuid(): void { $base = RamseyUuid::uuid4(); - $id = UuidV4::from($base); - $this->assertTrue($id->is($other = UuidV4::from($base))); - $this->assertSame($id, UuidV4::from($id)); - $this->assertTrue($id->is($other)); - $this->assertTrue($id->any(null, UuidV4::make(), $other)); - $this->assertEquals($id, UuidV4::tryFrom($base)); - $this->assertSame($id, UuidV4::tryFrom($id)); - $this->assertTrue($id->is(new Uuid($base))); + $actual = UuidV4::tryFrom($base); + + $this->assertEquals(UuidV4::from($base), $actual); } #[Test] - public function it_is_not_equal(): void + public function it_can_be_created_from_a_string(): void { - $id = UuidV4::from(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')); - $this->assertFalse($id->is($other = UuidV4::from( - RamseyUuid::fromString('38c7be26-6887-4742-8b6b-7d07b30ca596'), - ))); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any(null, UuidV4::make(), $other)); + $expected = UuidV4::from(RamseyUuid::fromString(self::UUID)); + + $actual = UuidV4::from(self::UUID); + + $this->assertObjectEquals($expected, $actual); } - /** - * @return array - */ - public static function notUuidV4Provider(): array + #[Test] + public function it_can_try_to_create_from_a_string(): void { - return [ - [null], - [new IntegerId(1)], - [new StringId('foo')], - [new Guid('SomeType', new Uuid(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')))], - [new Uuid(RamseyUuid::uuid7())], - [UuidV7::make()], - ]; + $expected = UuidV4::from(RamseyUuid::fromString(self::UUID)); + + $actual = UuidV4::tryFrom(self::UUID); + + $this->assertNotNull($actual); + $this->assertObjectEquals($expected, $actual); } - #[DataProvider('notUuidV4Provider')] #[Test] - public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void + public function it_returns_null_when_trying_from_an_invalid_string(): void { - $id = UuidV4::from(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')); + $actual = UuidV4::tryFrom('invalid'); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any(null, UuidV4::make(), $other)); - $this->assertFalse($id->any()); + $this->assertNull($actual); + } + + /** + * @return array + */ + public static function notUuidV4Provider(): array + { + return [ + 'null' => [null], + 'integer id' => [new IntegerId(1)], + 'string id' => [new StringId('foo')], + 'guid' => [new Guid('SomeType', new Uuid(RamseyUuid::fromString(self::UUID)))], + 'uuid v7 wrapped in uuid' => [new Uuid(RamseyUuid::uuid7())], + 'uuid v7' => [UuidV7::make()], + ]; } #[DataProvider('notUuidV4Provider')] @@ -103,6 +170,7 @@ public function it_cannot_be_created_from_other_identifier_types(?Identifier $ot { $this->expectException(ContractException::class); $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); + UuidV4::from($other); } @@ -110,46 +178,113 @@ public function it_cannot_be_created_from_other_identifier_types(?Identifier $ot #[Test] public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { - $this->assertNull(UuidV4::tryFrom($other)); + $actual = UuidV4::tryFrom($other); + + $this->assertNull($actual); } + // ------------------------------------------------------------------------- + // is(), any() and equals() + // ------------------------------------------------------------------------- + #[Test] - public function it_can_be_created_from_a_string(): void + public function it_equals_a_uuid_with_the_same_value(): void { - $base = RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816'); + $id = UuidV4::from(self::UUID); - $this->assertTrue(UuidV4::from($base)->is(UuidV4::from($base->toString()))); + $this->assertObjectEquals(UuidV4::from(self::UUID), $id); } #[Test] - public function it_can_try_to_create_from_a_string(): void + public function it_does_not_equal_a_uuid_with_a_different_value(): void { - $base = RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816'); + $id = UuidV4::from(self::UUID); - $this->assertTrue(UuidV4::from($base)->is(UuidV4::tryFrom($base->toString()))); - $this->assertNull(UuidV4::tryFrom('invalid')); + $this->assertObjectNotEquals(UuidV4::from(self::OTHER_UUID), $id); } #[Test] - public function it_returns_null_when_trying_from_null(): void + public function it_is_a_uuid_v4_with_the_same_value(): void { - $this->assertNull(Uuid::tryFrom(null)); + $base = RamseyUuid::uuid4(); + $id = UuidV4::from($base); + + $actual = $id->is(UuidV4::from($base)); + + $this->assertTrue($actual); } #[Test] - public function it_can_be_compared_for_sorting(): void + public function it_is_a_uuid_with_the_same_value(): void { - $uuid1 = UuidV4::make(); - $uuid2 = UuidV4::make(); - $uuid3 = UuidV4::make(); + $base = RamseyUuid::uuid4(); + $id = UuidV4::from($base); - $expected = [$uuid3->value, $uuid1->value, $uuid2->value]; - usort($expected, fn ($a, $b) => $a->compareTo($b)); + $actual = $id->is(new Uuid($base)); - $actual = [$uuid2, $uuid1, $uuid3]; - usort($actual, fn ($a, $b) => $a->compareTo($b)); - $actual = array_map(fn ($id) => $id->value, $actual); + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_a_uuid_with_a_different_value(): void + { + $id = UuidV4::from(self::UUID); + + $actual = $id->is(UuidV4::from(self::OTHER_UUID)); + + $this->assertFalse($actual); + } + + #[DataProvider('notUuidV4Provider')] + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void + { + $id = UuidV4::from(self::UUID); + + $actual = $id->is($other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_any_of_the_provided_identifiers_when_one_matches(): void + { + $base = RamseyUuid::uuid4(); + $id = UuidV4::from($base); + + $actual = $id->any(null, UuidV4::make(), UuidV4::from($base)); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_any_of_the_provided_identifiers_when_none_match(): void + { + $id = UuidV4::from(self::UUID); + + $actual = $id->any(null, UuidV4::make(), UuidV4::from(self::OTHER_UUID)); + + $this->assertFalse($actual); + } + + #[DataProvider('notUuidV4Provider')] + #[Test] + public function it_is_not_any_of_other_identifier_types(?Identifier $other): void + { + $id = UuidV4::from(self::UUID); + + $actual = $id->any(null, UuidV4::make(), $other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_not_any_when_no_identifiers_are_provided(): void + { + $id = UuidV4::from(self::UUID); + + $actual = $id->any(); - $this->assertSame($expected, $actual); + $this->assertFalse($actual); } } diff --git a/tests/Unit/Toolkit/Identifiers/UuidV7Test.php b/tests/Unit/Toolkit/Identifiers/UuidV7Test.php index 9522d283..14fc69dc 100644 --- a/tests/Unit/Toolkit/Identifiers/UuidV7Test.php +++ b/tests/Unit/Toolkit/Identifiers/UuidV7Test.php @@ -20,17 +20,24 @@ use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; use CloudCreativity\Modules\Toolkit\Identifiers\UuidV4; use CloudCreativity\Modules\Toolkit\Identifiers\UuidV7; +use DateTimeImmutable; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Uuid as RamseyUuid; final class UuidV7Test extends TestCase { + private const string UUID = '019b7acc-aff8-7f70-adc9-e9c7f632e6df'; + + private const string OTHER_UUID = '019b7acd-0f6f-7828-a1cf-94c34a239594'; + #[Test] public function it_wraps_a_ramsey_uuid(): void { $base = RamseyUuid::uuid7(); + $id = UuidV7::from($base); $this->assertSame($base, $id->value); @@ -46,55 +53,129 @@ public function it_wraps_a_ramsey_uuid(): void } #[Test] - public function it_is_equals(): void + public function it_accepts_a_lazy_uuid_v7(): void + { + $base = new LazyUuidFromString(RamseyUuid::uuid7()->toString()); + + $actual = new UuidV7($base); + + $this->assertSame($base, $actual->value); + } + + #[Test] + public function it_rejects_a_lazy_uuid_of_another_version(): void + { + $base = new LazyUuidFromString(RamseyUuid::uuid4()->toString()); + + $this->expectException(ContractException::class); + + new UuidV7($base); + } + + #[Test] + public function it_makes_a_uuid_for_a_date(): void + { + $date = new DateTimeImmutable('2025-01-02 03:04:05.678'); + + $actual = UuidV7::make($date); + + $this->assertSame( + $date->format('Y-m-d H:i:s.v'), + $actual->value->getDateTime()->format('Y-m-d H:i:s.v'), + ); + } + + #[Test] + public function it_can_be_compared_for_sorting(): void + { + $uuid1 = UuidV7::make(); + $uuid2 = UuidV7::make(); + $uuid3 = UuidV7::make(); + $expected = [$uuid3->value, $uuid1->value, $uuid2->value]; + usort($expected, fn ($a, $b) => $a->compareTo($b)); + $actual = [$uuid2, $uuid1, $uuid3]; + + usort($actual, fn ($a, $b) => $a->compareTo($b)); + + $this->assertSame($expected, array_map(fn ($id) => $id->value, $actual)); + } + + // ------------------------------------------------------------------------- + // from() and tryFrom() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_the_same_instance_when_created_from_a_uuid_v7(): void + { + $id = UuidV7::make(); + + $actual = UuidV7::from($id); + + $this->assertSame($id, $actual); + } + + #[Test] + public function it_returns_the_same_instance_when_trying_from_a_uuid_v7(): void + { + $id = UuidV7::make(); + + $actual = UuidV7::tryFrom($id); + + $this->assertSame($id, $actual); + } + + #[Test] + public function it_tries_to_create_from_a_ramsey_uuid(): void { $base = RamseyUuid::uuid7(); - $id = UuidV7::from($base); - $this->assertTrue($id->is($other = UuidV7::from($base))); - $this->assertSame($id, UuidV7::from($id)); - $this->assertTrue($id->is($other)); - $this->assertTrue($id->any(null, UuidV7::make(), $other)); - $this->assertEquals($id, UuidV7::tryFrom($base)); - $this->assertSame($id, UuidV7::tryFrom($id)); - $this->assertTrue($id->is(new Uuid($base))); + $actual = UuidV7::tryFrom($base); + + $this->assertEquals(UuidV7::from($base), $actual); } #[Test] - public function it_is_not_equal(): void + public function it_can_be_created_from_a_string(): void { - $id = UuidV7::from(RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df')); - $this->assertFalse($id->is($other = UuidV7::from( - RamseyUuid::fromString('019b7acd-0f6f-7828-a1cf-94c34a239594'), - ))); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any(null, UuidV7::make(), $other)); + $expected = UuidV7::from(RamseyUuid::fromString(self::UUID)); + + $actual = UuidV7::from(self::UUID); + + $this->assertObjectEquals($expected, $actual); } - /** - * @return array - */ - public static function notUuidV7Provider(): array + #[Test] + public function it_can_try_to_create_from_a_string(): void { - return [ - [null], - [new IntegerId(1)], - [new StringId('foo')], - [new Guid('SomeType', new Uuid(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')))], - [Uuid::random()], - [UuidV4::make()], - ]; + $expected = UuidV7::from(RamseyUuid::fromString(self::UUID)); + + $actual = UuidV7::tryFrom(self::UUID); + + $this->assertNotNull($actual); + $this->assertObjectEquals($expected, $actual); } - #[DataProvider('notUuidV7Provider')] #[Test] - public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void + public function it_returns_null_when_trying_from_an_invalid_string(): void { - $id = UuidV7::from(RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df')); + $actual = UuidV7::tryFrom('invalid'); - $this->assertFalse($id->is($other)); - $this->assertFalse($id->any(null, UuidV7::make(), $other)); - $this->assertFalse($id->any()); + $this->assertNull($actual); + } + + /** + * @return array + */ + public static function notUuidV7Provider(): array + { + return [ + 'null' => [null], + 'integer id' => [new IntegerId(1)], + 'string id' => [new StringId('foo')], + 'guid' => [new Guid('SomeType', new Uuid(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')))], + 'uuid' => [Uuid::random()], + 'uuid v4' => [UuidV4::make()], + ]; } #[DataProvider('notUuidV7Provider')] @@ -103,6 +184,7 @@ public function it_cannot_be_created_from_other_identifier_types(?Identifier $ot { $this->expectException(ContractException::class); $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other)); + UuidV7::from($other); } @@ -110,46 +192,113 @@ public function it_cannot_be_created_from_other_identifier_types(?Identifier $ot #[Test] public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void { - $this->assertNull(UuidV7::tryFrom($other)); + $actual = UuidV7::tryFrom($other); + + $this->assertNull($actual); } + // ------------------------------------------------------------------------- + // is(), any() and equals() + // ------------------------------------------------------------------------- + #[Test] - public function it_can_be_created_from_a_string(): void + public function it_equals_a_uuid_with_the_same_value(): void { - $base = RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df'); + $id = UuidV7::from(self::UUID); - $this->assertTrue(UuidV7::from($base)->is(UuidV7::from($base->toString()))); + $this->assertObjectEquals(UuidV7::from(self::UUID), $id); } #[Test] - public function it_can_try_to_create_from_a_string(): void + public function it_does_not_equal_a_uuid_with_a_different_value(): void { - $base = RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df'); + $id = UuidV7::from(self::UUID); - $this->assertTrue(UuidV7::from($base)->is(UuidV7::tryFrom($base->toString()))); - $this->assertNull(UuidV7::tryFrom('invalid')); + $this->assertObjectNotEquals(UuidV7::from(self::OTHER_UUID), $id); } #[Test] - public function it_returns_null_when_trying_from_null(): void + public function it_is_a_uuid_v7_with_the_same_value(): void { - $this->assertNull(Uuid::tryFrom(null)); + $base = RamseyUuid::uuid7(); + $id = UuidV7::from($base); + + $actual = $id->is(UuidV7::from($base)); + + $this->assertTrue($actual); } #[Test] - public function it_can_be_compared_for_sorting(): void + public function it_is_a_uuid_with_the_same_value(): void { - $uuid1 = UuidV7::make(); - $uuid2 = UuidV7::make(); - $uuid3 = UuidV7::make(); + $base = RamseyUuid::uuid7(); + $id = UuidV7::from($base); - $expected = [$uuid3->value, $uuid1->value, $uuid2->value]; - usort($expected, fn ($a, $b) => $a->compareTo($b)); + $actual = $id->is(new Uuid($base)); - $actual = [$uuid2, $uuid1, $uuid3]; - usort($actual, fn ($a, $b) => $a->compareTo($b)); - $actual = array_map(fn ($id) => $id->value, $actual); + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_a_uuid_with_a_different_value(): void + { + $id = UuidV7::from(self::UUID); + + $actual = $id->is(UuidV7::from(self::OTHER_UUID)); + + $this->assertFalse($actual); + } + + #[DataProvider('notUuidV7Provider')] + #[Test] + public function it_is_not_equal_to_other_identifier_types(?Identifier $other): void + { + $id = UuidV7::from(self::UUID); + + $actual = $id->is($other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_any_of_the_provided_identifiers_when_one_matches(): void + { + $base = RamseyUuid::uuid7(); + $id = UuidV7::from($base); + + $actual = $id->any(null, UuidV7::make(), UuidV7::from($base)); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_any_of_the_provided_identifiers_when_none_match(): void + { + $id = UuidV7::from(self::UUID); + + $actual = $id->any(null, UuidV7::make(), UuidV7::from(self::OTHER_UUID)); + + $this->assertFalse($actual); + } + + #[DataProvider('notUuidV7Provider')] + #[Test] + public function it_is_not_any_of_other_identifier_types(?Identifier $other): void + { + $id = UuidV7::from(self::UUID); + + $actual = $id->any(null, UuidV7::make(), $other); + + $this->assertFalse($actual); + } + + #[Test] + public function it_is_not_any_when_no_identifiers_are_provided(): void + { + $id = UuidV7::from(self::UUID); + + $actual = $id->any(); - $this->assertSame($expected, $actual); + $this->assertFalse($actual); } } diff --git a/tests/Unit/Toolkit/Iterables/IsKeyedSetTest.php b/tests/Unit/Toolkit/Iterables/IsKeyedSetTest.php new file mode 100644 index 00000000..e6afc01b --- /dev/null +++ b/tests/Unit/Toolkit/Iterables/IsKeyedSetTest.php @@ -0,0 +1,102 @@ +makeSet(['foo' => 'one', 'bar' => 'two']); + + $actual = iterator_to_array($set); + + $this->assertSame(['foo' => 'one', 'bar' => 'two'], $actual); + } + + #[Test] + public function it_returns_all_values(): void + { + $set = $this->makeSet(['foo' => 'one', 'bar' => 'two']); + + $actual = $set->all(); + + $this->assertSame(['foo' => 'one', 'bar' => 'two'], $actual); + } + + #[Test] + public function it_counts_the_values(): void + { + $set = $this->makeSet(['foo' => 'one', 'bar' => 'two']); + + $this->assertCount(2, $set); + } + + #[Test] + public function it_is_not_empty_when_it_has_values(): void + { + $set = $this->makeSet(['foo' => 'one']); + + $this->assertFalse($set->isEmpty()); + $this->assertTrue($set->isNotEmpty()); + } + + #[Test] + public function it_can_be_empty(): void + { + $set = $this->makeSet([]); + + $this->assertTrue($set->isEmpty()); + $this->assertFalse($set->isNotEmpty()); + $this->assertCount(0, $set); + $this->assertSame([], $set->all()); + } + + #[Test] + public function it_iterates_over_nothing_when_empty(): void + { + $set = $this->makeSet([]); + + $actual = iterator_to_array($set); + + $this->assertSame([], $actual); + } + + /** + * @param array $values + * @return KeyedSet + */ + private function makeSet(array $values): KeyedSet + { + /** + * @implements KeyedSet + */ + return new class ($values) implements KeyedSet { + /** @use IsKeyedSet */ + use IsKeyedSet; + + /** + * @param array $values + */ + public function __construct(array $values) + { + $this->stack = $values; + } + }; + } +} diff --git a/tests/Unit/Toolkit/Iterables/IsLazyListTest.php b/tests/Unit/Toolkit/Iterables/IsLazyListTest.php index 500702dd..3a5a1114 100644 --- a/tests/Unit/Toolkit/Iterables/IsLazyListTest.php +++ b/tests/Unit/Toolkit/Iterables/IsLazyListTest.php @@ -39,7 +39,9 @@ public function __construct(string ...$values) } }; - $this->assertSame($expected, $list->all()); + $actual = $list->all(); + + $this->assertSame($expected, $actual); } #[Test] @@ -65,6 +67,67 @@ public function __construct(array $values) } }; - $this->assertSame(['foo', 'bar', 'baz'], $list->all()); + $actual = $list->all(); + + $this->assertSame(['foo', 'bar', 'baz'], $actual); + } + + #[Test] + public function it_is_empty_when_there_is_no_source(): void + { + /** + * @implements LazyList + */ + $list = new class () implements LazyList { + /** @use IsLazyList */ + use IsLazyList; + }; + + $actual = $list->all(); + + $this->assertSame([], $actual); + } + + #[Test] + public function it_iterates_over_nothing_when_there_is_no_source(): void + { + /** + * @implements LazyList + */ + $list = new class () implements LazyList { + /** @use IsLazyList */ + use IsLazyList; + }; + + $actual = iterator_to_array($list); + + $this->assertSame([], $actual); + } + + #[Test] + public function it_invokes_the_source_each_time_it_is_iterated(): void + { + /** + * @implements LazyList + */ + $list = new class () implements LazyList { + /** @use IsLazyList */ + use IsLazyList; + + public int $calls = 0; + + public function __construct() + { + $this->source = function () { + $this->calls++; + yield $this->calls; + }; + } + }; + + $first = $list->all(); + $second = $list->all(); + + $this->assertSame([[1], [2]], [$first, $second]); } } diff --git a/tests/Unit/Toolkit/Iterables/IsListTest.php b/tests/Unit/Toolkit/Iterables/IsListTest.php new file mode 100644 index 00000000..cb354d50 --- /dev/null +++ b/tests/Unit/Toolkit/Iterables/IsListTest.php @@ -0,0 +1,98 @@ +makeList('one', 'two', 'three'); + + $actual = iterator_to_array($list); + + $this->assertSame([0 => 'one', 1 => 'two', 2 => 'three'], $actual); + } + + #[Test] + public function it_returns_all_values(): void + { + $list = $this->makeList('one', 'two', 'three'); + + $actual = $list->all(); + + $this->assertSame(['one', 'two', 'three'], $actual); + } + + #[Test] + public function it_counts_the_values(): void + { + $list = $this->makeList('one', 'two', 'three'); + + $this->assertCount(3, $list); + } + + #[Test] + public function it_is_not_empty_when_it_has_values(): void + { + $list = $this->makeList('one'); + + $this->assertFalse($list->isEmpty()); + $this->assertTrue($list->isNotEmpty()); + } + + #[Test] + public function it_can_be_empty(): void + { + $list = $this->makeList(); + + $this->assertTrue($list->isEmpty()); + $this->assertFalse($list->isNotEmpty()); + $this->assertCount(0, $list); + $this->assertSame([], $list->all()); + } + + #[Test] + public function it_iterates_over_nothing_when_empty(): void + { + $list = $this->makeList(); + + $actual = iterator_to_array($list); + + $this->assertSame([], $actual); + } + + /** + * @return ListIterator + */ + private function makeList(string ...$values): ListIterator + { + /** + * @implements ListIterator + */ + return new class (...$values) implements ListIterator { + /** @use IsList */ + use IsList; + + public function __construct(string ...$values) + { + $this->stack = array_values($values); + } + }; + } +} diff --git a/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php b/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php index 18b759c6..4a43123b 100644 --- a/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php +++ b/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php @@ -20,14 +20,44 @@ final class IsNonEmptyListTest extends TestCase { #[Test] - public function it_iterates_counts_and_returns_all_values(): void + public function it_iterates_over_the_values(): void { - $expected = ['one', 'two', 'three']; + $list = $this->makeList('one', 'two', 'three'); + $actual = iterator_to_array($list); + + $this->assertSame(['one', 'two', 'three'], $actual); + } + + #[Test] + public function it_returns_all_values(): void + { + $list = $this->makeList('one', 'two', 'three'); + + $actual = $list->all(); + + $this->assertSame(['one', 'two', 'three'], $actual); + } + + #[Test] + public function it_counts_the_values(): void + { + $list = $this->makeList('one', 'two', 'three'); + + $actual = count($list); + + $this->assertSame(3, $actual); + } + + /** + * @return NonEmptyList + */ + private function makeList(string $value, string ...$values): NonEmptyList + { /** * @implements NonEmptyList */ - $list = new class (...$expected) implements NonEmptyList { + return new class ($value, ...$values) implements NonEmptyList { /** @use IsNonEmptyList */ use IsNonEmptyList; @@ -36,9 +66,5 @@ public function __construct(string $value, string ...$values) $this->stack = [$value, ...array_values($values)]; } }; - - $this->assertSame($expected, iterator_to_array($list)); - $this->assertSame($expected, $list->all()); - $this->assertCount(count($expected), $list); } } diff --git a/tests/Unit/Toolkit/ModuleBasenameTest.php b/tests/Unit/Toolkit/ModuleBasenameTest.php index 2049905b..0b0b62be 100644 --- a/tests/Unit/Toolkit/ModuleBasenameTest.php +++ b/tests/Unit/Toolkit/ModuleBasenameTest.php @@ -12,11 +12,12 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit; +use CloudCreativity\Modules\Tests\Unit\Toolkit\Identifiers\TestIdentifier; use CloudCreativity\Modules\Toolkit\ModuleBasename; use PHPUnit\Framework\Attributes\DataProvider; -use PHPUnit\Framework\Attributes\Depends; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use UnexpectedValueException; final class ModuleBasenameTest extends TestCase { @@ -132,10 +133,53 @@ public function it_parses_a_class_name_with_a_module(string $value, string $cont $this->assertSame($context, $name->module); $this->assertSame($message, $name->name); - $this->assertEquals($name, ModuleBasename::tryFrom($value)); - $this->assertSame("{$context}:{$message}", $name->toString()); - $this->assertSame("{$context}/{$message}", $name->toString('/')); - $this->assertSame("{$context}:{$message}", (string) $name); + } + + #[DataProvider('moduleProvider')] + #[Test] + public function it_tries_to_parse_a_class_name_with_a_module(string $value, string $context, string $message): void + { + $name = ModuleBasename::tryFrom($value); + + $this->assertNotNull($name); + $this->assertSame($context, $name->module); + $this->assertSame($message, $name->name); + } + + #[DataProvider('moduleProvider')] + #[Test] + public function it_converts_a_name_with_a_module_to_a_string(string $value, string $context, string $message): void + { + $name = ModuleBasename::from($value); + + $actual = $name->toString(); + + $this->assertSame("{$context}:{$message}", $actual); + } + + #[DataProvider('moduleProvider')] + #[Test] + public function it_converts_a_name_with_a_module_to_a_string_with_a_delimiter( + string $value, + string $context, + string $message, + ): void { + $name = ModuleBasename::from($value); + + $actual = $name->toString('/'); + + $this->assertSame("{$context}/{$message}", $actual); + } + + #[DataProvider('moduleProvider')] + #[Test] + public function it_casts_a_name_with_a_module_to_a_string(string $value, string $context, string $message): void + { + $name = ModuleBasename::from($value); + + $actual = (string) $name; + + $this->assertSame("{$context}:{$message}", $actual); } #[DataProvider('withoutModuleProvider')] @@ -146,37 +190,82 @@ public function it_parses_a_class_name_without_a_module(string $value, string $m $this->assertNull($name->module); $this->assertSame($message, $name->name); - $this->assertEquals($name, ModuleBasename::tryFrom($value)); - $this->assertSame($message, $name->toString()); - $this->assertSame($message, $name->toString('/')); - $this->assertSame($message, (string) $name); } + #[DataProvider('withoutModuleProvider')] #[Test] - public function it_converts_to_an_array(): ModuleBasename + public function it_tries_to_parse_a_class_name_without_a_module(string $value, string $message): void + { + $name = ModuleBasename::tryFrom($value); + + $this->assertNotNull($name); + $this->assertNull($name->module); + $this->assertSame($message, $name->name); + } + + #[DataProvider('withoutModuleProvider')] + #[Test] + public function it_converts_a_name_without_a_module_to_a_string(string $value, string $message): void + { + $name = ModuleBasename::from($value); + + $actual = $name->toString(); + + $this->assertSame($message, $actual); + } + + #[DataProvider('withoutModuleProvider')] + #[Test] + public function it_ignores_the_delimiter_when_converting_a_name_without_a_module_to_a_string( + string $value, + string $message, + ): void { + $name = ModuleBasename::from($value); + + $actual = $name->toString('/'); + + $this->assertSame($message, $actual); + } + + #[DataProvider('withoutModuleProvider')] + #[Test] + public function it_casts_a_name_without_a_module_to_a_string(string $value, string $message): void + { + $name = ModuleBasename::from($value); + + $actual = (string) $name; + + $this->assertSame($message, $actual); + } + + #[Test] + public function it_converts_to_an_array(): void { $value = ModuleBasename::from( 'CloudCreativity\Application\Modules\WaitList\BoundedContext\Application\Commands\ScheduleDelayedProcess\ScheduleDelayedProcessCommand', ); - $this->assertSame([ - 'module' => $value->module, - 'name' => $value->name, - ], $value->toArray()); + $actual = $value->toArray(); - return $value; + $this->assertSame([ + 'module' => 'WaitList', + 'name' => 'ScheduleDelayedProcessCommand', + ], $actual); } - #[Depends('it_converts_to_an_array')] #[Test] - public function it_serializes_to_json(ModuleBasename $value): void + public function it_serializes_to_json(): void { - $expected = json_encode([ - 'module' => $value->module, - 'name' => $value->name, - ], JSON_THROW_ON_ERROR); + $value = ModuleBasename::from( + 'CloudCreativity\Application\Modules\WaitList\BoundedContext\Application\Commands\ScheduleDelayedProcess\ScheduleDelayedProcessCommand', + ); + + $actual = json_encode($value, JSON_THROW_ON_ERROR); - $this->assertJsonStringEqualsJsonString($expected, json_encode($value, JSON_THROW_ON_ERROR)); + $this->assertJsonStringEqualsJsonString( + '{"module":"WaitList","name":"ScheduleDelayedProcessCommand"}', + $actual, + ); } #[Test] @@ -190,8 +279,19 @@ public function it_returns_null_when_trying_from_an_invalid_value(): void #[Test] public function it_throws_when_parsing_an_invalid_value(): void { - $this->expectException(\UnexpectedValueException::class); + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage('Unexpected fully-qualified message class name.'); ModuleBasename::from(ModuleBasename::class); } + + #[Test] + public function it_parses_an_object(): void + { + $object = new TestIdentifier('foo'); + + $actual = ModuleBasename::from($object); + + $this->assertSame(['module' => 'Tests', 'name' => 'TestIdentifier'], $actual->toArray()); + } } diff --git a/tests/Unit/Toolkit/Pipeline/AccumulationProcessorTest.php b/tests/Unit/Toolkit/Pipeline/AccumulationProcessorTest.php index ad3486c9..b27a4f51 100644 --- a/tests/Unit/Toolkit/Pipeline/AccumulationProcessorTest.php +++ b/tests/Unit/Toolkit/Pipeline/AccumulationProcessorTest.php @@ -28,17 +28,17 @@ public function it_accumulates_stage_results(): void ); $a = function ($actual) use ($input): int { - $this->assertSame($actual, $input); + $this->assertSame($input, $actual); return 1; }; $b = function ($actual) use ($input): int { - $this->assertSame($actual, $input); + $this->assertSame($input, $actual); return 2; }; $c = function ($actual) use ($input): int { - $this->assertSame($actual, $input); + $this->assertSame($input, $actual); return 3; }; @@ -58,17 +58,17 @@ public function it_accumulates_stage_results_with_an_initial_value(): void ); $a = function ($actual) use ($input): int { - $this->assertSame($actual, $input); + $this->assertSame($input, $actual); return 1; }; $b = function ($actual) use ($input): int { - $this->assertSame($actual, $input); + $this->assertSame($input, $actual); return 2; }; $c = function ($actual) use ($input): int { - $this->assertSame($actual, $input); + $this->assertSame($input, $actual); return 3; }; diff --git a/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php b/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php index 6fd210d2..708d07e5 100644 --- a/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php +++ b/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php @@ -15,9 +15,11 @@ use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\Pipeline; use CloudCreativity\Modules\Toolkit\Pipeline\LazyPipe; +use LogicException; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use RuntimeException; final class LazyPipeTest extends TestCase { @@ -41,11 +43,14 @@ protected function tearDown(): void #[Test] public function it_resolves_the_pipe_from_the_container_and_invokes_it(): void { + $pipe = $this->createMock(Pipeline::class); + $lazyPipe = new LazyPipe($this->container, 'SomePipe'); + $this->container ->expects($this->once()) ->method('get') ->with('SomePipe') - ->willReturn($pipe = $this->createMock(Pipeline::class)); + ->willReturn($pipe); $pipe ->expects($this->once()) @@ -53,30 +58,48 @@ public function it_resolves_the_pipe_from_the_container_and_invokes_it(): void ->with('arg1', 'arg2') ->willReturn($expected = 'Hello World!'); - $lazyPipe = new LazyPipe($this->container, 'SomePipe'); $actual = $lazyPipe('arg1', 'arg2'); $this->assertSame($expected, $actual); } #[Test] - public function it_rethrows_exception(): void + public function it_throws_when_the_pipe_cannot_be_resolved(): void { + $lazyPipe = new LazyPipe($this->container, 'PipeThatWillError'); + $this->container ->expects($this->once()) ->method('get') ->with('PipeThatWillError') - ->willThrowException($expected = new \LogicException('Boom!')); + ->willThrowException(new LogicException('Boom!')); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Failed to get pipe "PipeThatWillError" from container.'); + $this->expectExceptionCode(0); + + $lazyPipe('blah'); + } + + #[Test] + public function it_sets_the_container_exception_as_the_previous_exception(): void + { $lazyPipe = new LazyPipe($this->container, 'PipeThatWillError'); + $this->container + ->expects($this->once()) + ->method('get') + ->with('PipeThatWillError') + ->willThrowException($expected = new LogicException('Boom!')); + + $actual = null; + try { $lazyPipe('blah'); - $this->fail('No exception thrown.'); - } catch (\RuntimeException $ex) { - $this->assertSame('Failed to get pipe "PipeThatWillError" from container.', $ex->getMessage()); - $this->assertSame(0, $ex->getCode()); - $this->assertSame($expected, $ex->getPrevious()); + } catch (RuntimeException $ex) { + $actual = $ex->getPrevious(); } + + $this->assertSame($expected, $actual); } } diff --git a/tests/Unit/Toolkit/Pipeline/MiddlewareProcessorTest.php b/tests/Unit/Toolkit/Pipeline/MiddlewareProcessorTest.php index 3a7a3c14..485d499a 100644 --- a/tests/Unit/Toolkit/Pipeline/MiddlewareProcessorTest.php +++ b/tests/Unit/Toolkit/Pipeline/MiddlewareProcessorTest.php @@ -76,6 +76,37 @@ public function it_passes_the_payload_to_the_destination_when_there_are_no_stage $this->assertSame('FOO', $result); } + #[Test] + public function it_wraps_a_callable_destination(): void + { + $processor = MiddlewareProcessor::wrap('strtoupper'); + + $result = $processor->process( + 'foo', + static fn (string $value, Closure $next): mixed => $next($value . 'bar'), + ); + + $this->assertSame('FOOBAR', $result); + } + + #[Test] + public function it_calls_a_destination_without_returning_its_result(): void + { + $called = null; + $processor = MiddlewareProcessor::call(static function (string $value) use (&$called): string { + $called = $value; + return 'ignored'; + }); + + $result = $processor->process( + 'foo', + static fn (string $value, Closure $next): mixed => $next($value . 'bar'), + ); + + $this->assertNull($result); + $this->assertSame('foobar', $called); + } + private function createMiddleware(string $step): Closure { return static function (array $values, Closure $next) use ($step) { diff --git a/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php b/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php index f1214e81..14c81ed1 100644 --- a/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php +++ b/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php @@ -19,17 +19,66 @@ final class PipeContainerTest extends TestCase { #[Test] - public function it_resolves_bound_pipes(): void + public function it_resolves_a_bound_pipe(): void { $a = fn () => 1; $b = fn () => 2; - $container = new PipeContainer(); $container->bind('PipeA', fn () => $a); $container->bind('PipeB', fn () => $b); - $this->assertSame($a, $container->get('PipeA')); - $this->assertSame($b, $container->get('PipeB')); + $actual = $container->get('PipeB'); + + $this->assertSame($b, $actual); + } + + #[Test] + public function it_replaces_a_pipe_that_is_bound_again(): void + { + $a = fn () => 1; + $b = fn () => 2; + $container = new PipeContainer(); + $container->bind('PipeA', fn () => $a); + $container->bind('PipeA', fn () => $b); + + $actual = $container->get('PipeA'); + + $this->assertSame($b, $actual); + } + + #[Test] + public function it_resolves_the_pipe_from_its_factory_each_time(): void + { + $container = new PipeContainer(); + $container->bind('PipeA', fn () => new class () { + public function __invoke(): int + { + return 1; + } + }); + + $first = $container->get('PipeA'); + $second = $container->get('PipeA'); + + $this->assertNotSame($first, $second); + } + + #[Test] + public function it_throws_when_the_pipe_is_not_bound(): void + { + $container = new PipeContainer(); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Unrecognised pipe name: PipeA'); + + $container->get('PipeA'); + } + + #[Test] + public function it_throws_when_the_pipe_is_not_bound_but_others_are(): void + { + $container = new PipeContainer(); + $container->bind('PipeA', fn () => fn () => 1); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Unrecognised pipe name: PipeC'); diff --git a/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php b/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php index 9e1e4e47..bdea3c37 100644 --- a/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php +++ b/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php @@ -13,6 +13,7 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Pipeline; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipeContainer; +use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\PipelineBuilder as IPipelineBuilder; use CloudCreativity\Modules\Contracts\Toolkit\Pipeline\Processor; use CloudCreativity\Modules\Toolkit\Pipeline\LazyPipe; use CloudCreativity\Modules\Toolkit\Pipeline\Pipeline; @@ -65,10 +66,54 @@ public function it_fails_to_build_with_a_service_string_without_a_container(): v $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Cannot use a string pipe name without a pipe container.'); - $pipeline = new PipelineBuilder() + $_ = new PipelineBuilder() ->add('strtoupper') ->add('SomeService') ->add('strtolower') ->build($processor); } + + #[Test] + public function it_makes_a_builder(): void + { + $container = $this->createStub(PipeContainer::class); + + $actual = PipelineBuilder::make($container); + + $this->assertInstanceOf(IPipelineBuilder::class, $actual); + $this->assertEquals(new PipelineBuilder($container), $actual); + } + + #[Test] + public function it_makes_a_builder_without_a_container(): void + { + $actual = PipelineBuilder::make(); + + $this->assertEquals(new PipelineBuilder(), $actual); + } + + #[Test] + public function it_builds_a_pipeline_with_the_default_processor(): void + { + $pipeline = new PipelineBuilder() + ->through([ + static fn (int $value): int => $value * 5, + static fn (int $value): int => $value + 2, + ]) + ->build(); + + $actual = $pipeline->process(3); + + $this->assertSame(17, $actual); + } + + #[Test] + public function it_builds_an_empty_pipeline(): void + { + $processor = $this->createStub(Processor::class); + + $actual = new PipelineBuilder()->build($processor); + + $this->assertEquals(new Pipeline($processor, []), $actual); + } } diff --git a/tests/Unit/Toolkit/Pipeline/PipelineTest.php b/tests/Unit/Toolkit/Pipeline/PipelineTest.php index b43c182a..c246ed75 100644 --- a/tests/Unit/Toolkit/Pipeline/PipelineTest.php +++ b/tests/Unit/Toolkit/Pipeline/PipelineTest.php @@ -78,17 +78,39 @@ public function it_uses_a_default_processor(): void #[Test] public function it_returns_a_new_pipeline_when_piping(): void { - $pipeline1 = new Pipeline(null, [ + $pipeline = new Pipeline(null, [ + static fn (int $value): int => $value * 5, + ]); + + $actual = $pipeline->pipe(static fn (int $value): int => $value + 2); + + $this->assertNotSame($pipeline, $actual); + } + + #[Test] + public function it_does_not_change_the_original_pipeline_when_piping(): void + { + $pipeline = new Pipeline(null, [ static fn (int $value): int => $value * 5, static fn (int $value): int => $value + 2, ]); + $pipeline->pipe(static fn (int $value): int => $value - 3); - $pipeline2 = $pipeline1->pipe( - static fn (int $value): int => $value - 3, - ); + $actual = $pipeline->process(3); + + $this->assertSame(17, $actual); + } + + #[Test] + public function it_processes_the_piped_stage_after_the_existing_stages(): void + { + $pipeline = new Pipeline(null, [ + static fn (int $value): int => $value * 5, + static fn (int $value): int => $value + 2, + ])->pipe(static fn (int $value): int => $value - 3); + + $actual = $pipeline->process(3); - $this->assertNotSame($pipeline1, $pipeline2); - $this->assertSame(17, $pipeline1->process(3)); - $this->assertSame(14, $pipeline2->process(3)); + $this->assertSame(14, $actual); } } diff --git a/tests/Unit/Toolkit/Pipeline/ThroughTest.php b/tests/Unit/Toolkit/Pipeline/ThroughTest.php new file mode 100644 index 00000000..18f3ca70 --- /dev/null +++ b/tests/Unit/Toolkit/Pipeline/ThroughTest.php @@ -0,0 +1,70 @@ +assertSame(['PipeA', 'PipeB', 'PipeC'], $through->pipes); + } + + #[Test] + public function it_can_have_no_pipes(): void + { + $through = new Through(); + + $this->assertSame([], $through->pipes); + } + + #[Test] + public function it_lists_pipes_passed_with_keys(): void + { + $pipes = ['a' => 'PipeA', 'b' => 'PipeB']; + + $through = new Through(...$pipes); + + $this->assertSame(['PipeA', 'PipeB'], $through->pipes); + } + + #[Test] + public function it_is_read_from_a_class(): void + { + $object = new #[Through('PipeA', 'PipeB')] class () { + }; + $reflection = new ReflectionClass($object); + + $through = $reflection->getAttributes(Through::class)[0]->newInstance(); + + $this->assertSame(['PipeA', 'PipeB'], $through->pipes); + } + + #[Test] + public function it_only_targets_classes(): void + { + $reflection = new ReflectionClass(Through::class); + + $attribute = $reflection->getAttributes(Attribute::class)[0]->newInstance(); + + $this->assertSame(Attribute::TARGET_CLASS, $attribute->flags); + } +} diff --git a/tests/Unit/Toolkit/Result/ContextualResultTest.php b/tests/Unit/Toolkit/Result/ContextualResultTest.php new file mode 100644 index 00000000..5b29caf7 --- /dev/null +++ b/tests/Unit/Toolkit/Result/ContextualResultTest.php @@ -0,0 +1,264 @@ +assertInstanceOf(Contextual::class, $contextual); + } + + // ------------------------------------------------------------------------- + // success() + // ------------------------------------------------------------------------- + + #[Test] + public function it_is_successful_when_the_result_succeeded(): void + { + $contextual = new ContextualResult(Result::ok()); + + $this->assertTrue($contextual->success()); + } + + #[Test] + public function it_is_not_successful_when_the_result_failed(): void + { + $contextual = new ContextualResult(Result::failed('Something went wrong.')); + + $this->assertFalse($contextual->success()); + } + + // ------------------------------------------------------------------------- + // value() + // ------------------------------------------------------------------------- + + /** + * @return array + */ + public static function scalarProvider(): array + { + return [ + 'true' => [true], + 'false' => [false], + 'integer' => [99], + 'zero' => [0], + 'float' => [1.5], + ]; + } + + #[DataProvider('scalarProvider')] + #[Test] + public function it_returns_bool_int_and_float_values(bool|float|int $value): void + { + $contextual = new ContextualResult(Result::ok($value)); + + $actual = $contextual->value(); + + $this->assertSame($value, $actual); + } + + #[Test] + public function it_returns_the_context_of_a_contextual_value(): void + { + $value = Guid::fromInteger('SomeType', 123); + $contextual = new ContextualResult(Result::ok($value)); + + $actual = $contextual->value(); + + $this->assertSame(['type' => 'SomeType', 'id' => 123], $actual); + } + + /** + * @return array + */ + public static function omittedValueProvider(): array + { + return [ + 'null' => [null], + 'string' => ['secret'], + 'array' => [['foo' => 'bar']], + 'object' => [new stdClass()], + 'enum' => [TestBackedEnum::Foo], + ]; + } + + #[DataProvider('omittedValueProvider')] + #[Test] + public function it_does_not_return_other_values(mixed $value): void + { + $contextual = new ContextualResult(Result::ok($value)); + + $actual = $contextual->value(); + + $this->assertNull($actual); + } + + #[Test] + public function it_does_not_return_a_value_for_a_failed_result(): void + { + $contextual = new ContextualResult(Result::failed('Something went wrong.')); + + $actual = $contextual->value(); + + $this->assertNull($actual); + } + + // ------------------------------------------------------------------------- + // meta() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_the_meta(): void + { + $contextual = new ContextualResult(Result::ok()->withMeta(['foo' => 'bar', 'baz' => null])); + + $actual = $contextual->meta(); + + $this->assertSame(['foo' => 'bar', 'baz' => null], $actual); + } + + #[Test] + public function it_returns_null_when_the_meta_is_empty(): void + { + $contextual = new ContextualResult(Result::ok()); + + $actual = $contextual->meta(); + + $this->assertNull($actual); + } + + // ------------------------------------------------------------------------- + // errors() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_the_errors(): void + { + $contextual = new ContextualResult(Result::failed([ + new Error(code: TestUnitEnum::Baz, message: 'Message A', key: 'foo'), + new Error(message: 'Message B'), + new Error(code: TestBackedEnum::Foo), + ])); + + $actual = $contextual->errors(); + + $this->assertSame([ + ['code' => TestUnitEnum::Baz, 'key' => 'foo', 'message' => 'Message A'], + ['message' => 'Message B'], + ['code' => TestBackedEnum::Foo], + ], $actual); + } + + #[Test] + public function it_returns_no_errors_for_a_successful_result(): void + { + $contextual = new ContextualResult(Result::ok()); + + $actual = $contextual->errors(); + + $this->assertSame([], $actual); + } + + // ------------------------------------------------------------------------- + // context() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_context_for_a_successful_result_without_a_value(): void + { + $contextual = new ContextualResult(Result::ok()); + + $actual = $contextual->context(); + + $this->assertSame(['success' => true], $actual); + } + + #[Test] + public function it_returns_context_for_a_successful_result_with_a_value_and_meta(): void + { + $contextual = new ContextualResult( + Result::ok(new IntegerId(99))->withMeta(['foo' => 'bar']), + ); + + $actual = $contextual->context(); + + $this->assertSame([ + 'success' => true, + 'value' => 99, + 'meta' => ['foo' => 'bar'], + ], $actual); + } + + #[Test] + public function it_keeps_a_false_value_in_the_context(): void + { + $contextual = new ContextualResult(Result::ok(false)); + + $actual = $contextual->context(); + + $this->assertSame(['success' => true, 'value' => false], $actual); + } + + #[Test] + public function it_returns_context_for_a_failed_result_with_one_error(): void + { + $contextual = new ContextualResult( + Result::failed(new Error(message: 'Something went wrong.', key: 'foo')) + ->withMeta(['foo' => 'bar']), + ); + + $actual = $contextual->context(); + + $this->assertSame([ + 'success' => false, + 'error' => ['key' => 'foo', 'message' => 'Something went wrong.'], + 'meta' => ['foo' => 'bar'], + ], $actual); + } + + #[Test] + public function it_returns_context_for_a_failed_result_with_many_errors(): void + { + $contextual = new ContextualResult(Result::failed([ + new Error(message: 'Message A'), + new Error(code: TestUnitEnum::Bat), + ])); + + $actual = $contextual->context(); + + $this->assertSame([ + 'success' => false, + 'errors' => [ + ['message' => 'Message A'], + ['code' => TestUnitEnum::Bat], + ], + ], $actual); + } +} diff --git a/tests/Unit/Toolkit/Result/ErrorTest.php b/tests/Unit/Toolkit/Result/ErrorTest.php index 2c3e7bf4..f371961c 100644 --- a/tests/Unit/Toolkit/Result/ErrorTest.php +++ b/tests/Unit/Toolkit/Result/ErrorTest.php @@ -31,8 +31,26 @@ public function it_has_a_key_message_and_code(): void $this->assertSame('foo', $error->key()); $this->assertSame('Bar', $error->message()); $this->assertSame(TestUnitEnum::Baz, $error->code()); - $this->assertTrue($error->is(TestUnitEnum::Baz)); - $this->assertFalse($error->is(TestUnitEnum::Bat)); + } + + #[Test] + public function it_is_its_code(): void + { + $error = new Error(code: TestUnitEnum::Baz); + + $actual = $error->is(TestUnitEnum::Baz); + + $this->assertTrue($actual); + } + + #[Test] + public function it_is_not_another_code(): void + { + $error = new Error(code: TestUnitEnum::Baz); + + $actual = $error->is(TestUnitEnum::Bat); + + $this->assertFalse($actual); } #[Test] @@ -63,4 +81,30 @@ public function it_requires_a_message_or_a_code(): void new Error(key: 'foo'); } + + #[Test] + public function it_can_have_an_enum_key(): void + { + $error = new Error(message: 'Hello World', key: TestUnitEnum::Bat); + + $this->assertSame(TestUnitEnum::Bat, $error->key()); + } + + #[Test] + public function it_converts_an_empty_key_to_null(): void + { + $error = new Error(message: 'Hello World', key: ''); + + $this->assertNull($error->key()); + } + + #[Test] + public function it_is_not_a_code_when_it_has_no_code(): void + { + $error = new Error(message: 'Hello World'); + + $actual = $error->is(TestUnitEnum::Baz); + + $this->assertFalse($actual); + } } diff --git a/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php b/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php index 349874c9..6f0f1956 100644 --- a/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php +++ b/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php @@ -12,9 +12,12 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Result; +use CloudCreativity\Modules\Contracts\Toolkit\Result\Result as IResult; use CloudCreativity\Modules\Tests\TestUnitEnum; use CloudCreativity\Modules\Toolkit\Result\FailedResultException; +use CloudCreativity\Modules\Toolkit\Result\ListOfErrors; use CloudCreativity\Modules\Toolkit\Result\Result; +use LogicException; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -39,17 +42,15 @@ public function it_fails_with_error_code(): void $exception = new FailedResultException($result); - $expected = 'Failed with error code: Bat'; - $this->assertSame($result, $exception->getResult()); - $this->assertSame($expected, $exception->getMessage()); + $this->assertSame('Failed with error code: Bat', $exception->getMessage()); } #[Test] public function it_has_code_and_previous_exception(): void { $result = Result::failed('Something went wrong.'); - $previous = new \LogicException('Boom!'); + $previous = new LogicException('Boom!'); $exception = new FailedResultException($result, 99, $previous); @@ -58,4 +59,54 @@ public function it_has_code_and_previous_exception(): void $this->assertSame(99, $exception->getCode()); $this->assertSame($previous, $exception->getPrevious()); } + + #[Test] + public function it_has_an_empty_message_when_the_result_has_no_message_or_code(): void + { + $result = $this->createFailedResult(); + + $exception = new FailedResultException($result); + + $this->assertSame('', $exception->getMessage()); + } + + #[Test] + public function it_returns_the_result_context(): void + { + $exception = new FailedResultException( + Result::failed('Something went wrong.')->withMeta(['foo' => 'bar']), + ); + + $actual = $exception->context(); + + $this->assertSame([ + 'success' => false, + 'error' => ['message' => 'Something went wrong.'], + 'meta' => ['foo' => 'bar'], + ], $actual); + } + + #[Test] + public function it_wraps_a_result_context_that_is_not_an_array(): void + { + $exception = new FailedResultException($this->createFailedResult('Some context')); + + $actual = $exception->context(); + + $this->assertSame(['Some context'], $actual); + } + + /** + * @return IResult + */ + private function createFailedResult(mixed $context = null): IResult + { + $result = $this->createStub(IResult::class); + $result->method('didFail')->willReturn(true); + $result->method('error')->willReturn(null); + $result->method('errors')->willReturn(new ListOfErrors()); + $result->method('context')->willReturn($context); + + return $result; + } } diff --git a/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php b/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php index ec21f2c7..cb20302c 100644 --- a/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php +++ b/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php @@ -12,12 +12,15 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Result; +use CloudCreativity\Modules\Contracts\Toolkit\Iterables\KeyedSet; use CloudCreativity\Modules\Tests\TestUnitEnum; use CloudCreativity\Modules\Toolkit\Result\Error; use CloudCreativity\Modules\Toolkit\Result\KeyedSetOfErrors; use CloudCreativity\Modules\Toolkit\Result\ListOfErrors; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use UnitEnum; final class KeyedSetOfErrorsTest extends TestCase { @@ -50,8 +53,38 @@ public function it_groups_errors_by_key(): void $this->assertCount(8, $errors); $this->assertTrue($errors->isNotEmpty()); $this->assertFalse($errors->isEmpty()); - $this->assertEquals($expected['bar'], $errors->get('bar')); - $this->assertEquals($expected[TestUnitEnum::Baz->name], $errors->get(TestUnitEnum::Baz)); + } + + /** + * @return array + */ + public static function getProvider(): array + { + return [ + 'string key' => ['bar', new ListOfErrors(new Error(message: 'Message B', key: 'bar'))], + 'enum key' => [TestUnitEnum::Baz, new ListOfErrors( + new Error(message: 'Message C', key: TestUnitEnum::Baz), + new Error(message: 'Message E', key: TestUnitEnum::Baz), + )], + ]; + } + + #[DataProvider('getProvider')] + #[Test] + public function it_gets_errors_by_key(string|UnitEnum $key, ListOfErrors $expected): void + { + $errors = new KeyedSetOfErrors( + new Error(message: 'Message A', key: 'foo'), + new Error(message: 'Message B', key: 'bar'), + new Error(message: 'Message C', key: TestUnitEnum::Baz), + new Error(message: 'Message D', key: TestUnitEnum::Bat), + new Error(message: 'Message E', key: TestUnitEnum::Baz), + new Error(message: 'Message F'), + ); + + $actual = $errors->get($key); + + $this->assertEquals($expected, $actual); } #[Test] @@ -199,4 +232,107 @@ public function it_merges_another_set(): void $this->assertSame(['_base', 'bar', 'baz', 'foo'], $actual->keys()); $this->assertCount($set1->count() + $set2->count(), $actual); } + + #[Test] + public function it_is_a_keyed_set(): void + { + $errors = new KeyedSetOfErrors(); + + $this->assertInstanceOf(KeyedSet::class, $errors); + } + + #[Test] + public function it_sorts_keys_case_insensitively(): void + { + $errors = new KeyedSetOfErrors( + new Error(message: 'Message A', key: 'foo'), + new Error(message: 'Message B', key: 'Bar'), + new Error(message: 'Message C', key: 'baz'), + new Error(message: 'Message D'), + ); + + $actual = $errors->keys(); + + $this->assertSame(['_base', 'Bar', 'baz', 'foo'], $actual); + } + + #[Test] + public function it_returns_an_empty_list_for_a_key_that_does_not_exist(): void + { + $errors = new KeyedSetOfErrors(new Error(message: 'Message A', key: 'foo')); + + $actual = $errors->get('bar'); + + $this->assertEquals(new ListOfErrors(), $actual); + } + + #[Test] + public function it_returns_no_keys_or_errors_when_empty(): void + { + $errors = new KeyedSetOfErrors(); + + $this->assertSame([], $errors->keys()); + $this->assertSame([], $errors->all()); + $this->assertEquals(new ListOfErrors(), $errors->toList()); + } + + #[Test] + public function it_returns_the_same_instance_when_created_from_a_keyed_set(): void + { + $errors = new KeyedSetOfErrors(new Error(message: 'Message A', key: 'foo')); + + $actual = KeyedSetOfErrors::from($errors); + + $this->assertSame($errors, $actual); + } + + #[Test] + public function it_is_created_from_a_list_of_errors(): void + { + $errors = new ListOfErrors( + $a = new Error(message: 'Message A', key: 'foo'), + $b = new Error(message: 'Message B'), + $c = new Error(message: 'Message C', key: 'foo'), + ); + + $actual = KeyedSetOfErrors::from($errors); + + $this->assertEquals(new KeyedSetOfErrors($a, $b, $c), $actual); + } + + #[Test] + public function it_is_created_from_an_error(): void + { + $error = new Error(message: 'Message A', key: 'foo'); + + $actual = KeyedSetOfErrors::from($error); + + $this->assertEquals(new KeyedSetOfErrors($error), $actual); + } + + #[Test] + public function it_merges_a_list_of_errors(): void + { + $set = new KeyedSetOfErrors( + $a = new Error(message: 'Message A', key: 'foo'), + $b = new Error(message: 'Message B', key: 'bar'), + ); + + $actual = $set->merge(new ListOfErrors( + $c = new Error(message: 'Message C', key: 'foo'), + $d = new Error(message: 'Message D'), + )); + + $this->assertNotSame($set, $actual); + $this->assertEquals([ + 'bar' => new ListOfErrors($b), + 'foo' => new ListOfErrors($a), + ], $set->all()); + $this->assertEquals([ + '_base' => new ListOfErrors($d), + 'bar' => new ListOfErrors($b), + 'foo' => new ListOfErrors($a, $c), + ], $actual->all()); + $this->assertSame(['_base', 'bar', 'foo'], $actual->keys()); + } } diff --git a/tests/Unit/Toolkit/Result/ListOfErrorsTest.php b/tests/Unit/Toolkit/Result/ListOfErrorsTest.php index e0dc791e..63367db9 100644 --- a/tests/Unit/Toolkit/Result/ListOfErrorsTest.php +++ b/tests/Unit/Toolkit/Result/ListOfErrorsTest.php @@ -12,6 +12,7 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Result; +use ArrayIterator; use CloudCreativity\Modules\Contracts\Toolkit\Result\Error as IError; use CloudCreativity\Modules\Contracts\Toolkit\Result\ListOfErrors as IListOfErrors; use CloudCreativity\Modules\Tests\TestBackedEnum; @@ -19,8 +20,12 @@ use CloudCreativity\Modules\Toolkit\Result\Error; use CloudCreativity\Modules\Toolkit\Result\KeyedSetOfErrors; use CloudCreativity\Modules\Toolkit\Result\ListOfErrors; +use Closure; +use LogicException; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use UnitEnum; final class ListOfErrorsTest extends TestCase { @@ -48,9 +53,9 @@ public function it_can_be_empty(): void $this->assertTrue($errors->isEmpty()); $this->assertFalse($errors->isNotEmpty()); - $this->assertSame(0, $errors->count()); + $this->assertCount(0, $errors); $this->assertNull($errors->first()); - $this->assertEmpty($errors->codes()); + $this->assertSame([], $errors->codes()); } #[Test] @@ -99,28 +104,58 @@ public function it_returns_the_first_error(): void new Error(null, 'Message C'), ); - $this->assertSame($a, $errors->first()); + $actual = $errors->first(); + + $this->assertSame($a, $actual); } + /** + * @return array + */ + public static function findProvider(): array + { + return [ + 'callback matches' => [static fn (IError $error): bool => 'Message C' === $error->message(), 2], + 'code matches' => [TestUnitEnum::Bat, 4], + 'callback does not match' => [static fn (IError $error): bool => 'Message E' === $error->message(), null], + 'code does not match' => [TestUnitEnum::Baz, null], + ]; + } + + #[DataProvider('findProvider')] #[Test] - public function it_finds_an_error(): void + public function it_finds_an_error(Closure|UnitEnum $matcher, ?int $expected): void { - $errors = new ListOfErrors( + $all = [ new Error(null, 'Message A'), new Error(null, 'Message B'), - $c = new Error(null, 'Message C'), + new Error(null, 'Message C'), new Error(null, 'Message D'), - $e = new Error(code: TestUnitEnum::Bat), - ); + new Error(code: TestUnitEnum::Bat), + ]; + $errors = new ListOfErrors(...$all); - $this->assertSame($c, $errors->find(fn (IError $error) => 'Message C' === $error->message())); - $this->assertSame($e, $errors->find(TestUnitEnum::Bat)); - $this->assertNull($errors->find(fn (IError $error) => 'Message E' === $error->message())); - $this->assertNull($errors->find(TestUnitEnum::Baz)); + $actual = $errors->find($matcher); + + $this->assertSame($expected === null ? null : $all[$expected], $actual); } + /** + * @return array + */ + public static function anyProvider(): array + { + return [ + 'callback matches' => [static fn (IError $error): bool => 'Message C' === $error->message(), true], + 'code matches' => [TestUnitEnum::Baz, true], + 'callback does not match' => [static fn (IError $error): bool => 'Message E' === $error->message(), false], + 'code does not match' => [TestUnitEnum::Bat, false], + ]; + } + + #[DataProvider('anyProvider')] #[Test] - public function it_checks_if_any_error_matches(): void + public function it_checks_if_any_error_matches(Closure|UnitEnum $matcher, bool $expected): void { $errors = new ListOfErrors( new Error(message: 'Message A'), @@ -129,202 +164,293 @@ public function it_checks_if_any_error_matches(): void new Error(code: TestUnitEnum::Baz, message: 'Message D'), ); - $this->assertTrue($errors->any(fn (IError $error) => 'Message C' === $error->message())); - $this->assertTrue($errors->any(TestUnitEnum::Baz)); - $this->assertFalse($errors->any(fn (IError $error) => 'Message E' === $error->message())); - $this->assertFalse($errors->any(TestUnitEnum::Bat)); + $actual = $errors->any($matcher); + + $this->assertSame($expected, $actual); } - #[Test] - public function it_checks_if_every_error_matches(): void + /** + * @return array + */ + public static function everyProvider(): array { - $errors1 = new ListOfErrors( + $mixed = new ListOfErrors( new Error(message: 'Message A'), new Error(message: 'Message B'), new Error(message: 'Message C'), new Error(message: 'Message D', code: TestUnitEnum::Baz), ); - $errors2 = new ListOfErrors( + $codes = new ListOfErrors( new Error(code: TestUnitEnum::Baz, message: 'Message D'), new Error(code: TestUnitEnum::Baz, message: 'Message D'), new Error(code: TestUnitEnum::Baz, message: 'Message D'), ); - $this->assertTrue($errors1->every(fn (IError $error) => str_starts_with($error->message(), 'Message'))); - $this->assertFalse($errors1->every(fn (IError $error) => null !== $error->code())); - $this->assertFalse($errors1->every(fn (IError $error) => 'Message A' === $error->message())); - - $this->assertTrue($errors2->every(TestUnitEnum::Baz)); - $this->assertFalse($errors1->every(TestUnitEnum::Baz)); - $this->assertFalse($errors2->every(TestUnitEnum::Bat)); + return [ + 'callback matches all' => [ + $mixed, + static fn (IError $error): bool => str_starts_with($error->message(), 'Message'), + true, + ], + 'callback matches some' => [ + $mixed, + static fn (IError $error): bool => null !== $error->code(), + false, + ], + 'callback matches one' => [ + $mixed, + static fn (IError $error): bool => 'Message A' === $error->message(), + false, + ], + 'code matches all' => [$codes, TestUnitEnum::Baz, true], + 'code matches some' => [$mixed, TestUnitEnum::Baz, false], + 'code matches none' => [$codes, TestUnitEnum::Bat, false], + ]; } + #[DataProvider('everyProvider')] #[Test] - public function it_returns_the_sole_error(): void - { - $errors1 = new ListOfErrors( - $expected = new Error(message: 'Message A', code: $code = TestUnitEnum::Baz), - ); + public function it_checks_if_every_error_matches( + ListOfErrors $errors, + Closure|UnitEnum $matcher, + bool $expected, + ): void { + $actual = $errors->every($matcher); + + $this->assertSame($expected, $actual); + } - $errors2 = new ListOfErrors( + /** + * @return array + */ + public static function soleProvider(): array + { + $expected = new Error(message: 'Message A', code: TestUnitEnum::Baz); + $one = new ListOfErrors($expected); + $many = new ListOfErrors( new Error(message: 'Message B'), new Error(message: 'Message C'), $expected, ); + $fn = static fn (IError $error): bool => 'Message A' === $error->message(); + + return [ + 'one error' => [$one, null, $expected], + 'one error matching code' => [$one, TestUnitEnum::Baz, $expected], + 'one error matching callback' => [$one, $fn, $expected], + 'many errors matching code' => [$many, TestUnitEnum::Baz, $expected], + 'many errors matching callback' => [$many, $fn, $expected], + ]; + } - $fn = fn (IError $error) => 'Message A' === $error->message(); - - $this->assertSame($expected, $errors1->sole()); - $this->assertSame($expected, $errors1->sole($code)); - $this->assertSame($expected, $errors1->sole($fn)); + #[DataProvider('soleProvider')] + #[Test] + public function it_returns_the_sole_error(ListOfErrors $errors, Closure|UnitEnum|null $matcher, Error $expected): void + { + $actual = $errors->sole($matcher); - $this->assertSame($expected, $errors2->sole($code)); - $this->assertSame($expected, $errors2->sole($fn)); + $this->assertSame($expected, $actual); } #[Test] public function it_throws_when_there_is_no_sole_error(): void { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Expected exactly one error but there are 0.'); - $errors = new ListOfErrors(); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected exactly one error but there are 0.'); + $errors->sole(); } #[Test] public function it_throws_when_there_are_many_errors_for_sole(): void { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Expected exactly one error but there are 3.'); - $errors = new ListOfErrors( new Error(message: 'Message A'), new Error(message: 'Message B'), new Error(message: 'Message C'), ); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected exactly one error but there are 3.'); + $errors->sole(); } #[Test] public function it_throws_when_no_error_matches_the_sole_callback(): void { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Expected exactly one error matching the criteria but there are 0.'); - $errors = new ListOfErrors( new Error(message: 'Message A'), new Error(message: 'Message B'), new Error(message: 'Message C'), ); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected exactly one error matching the criteria but there are 0.'); + $errors->sole(fn (IError $error) => 'Message D' === $error->message()); } #[Test] public function it_throws_when_many_errors_match_the_sole_callback(): void { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Expected exactly one error matching the criteria but there are 2.'); - $errors = new ListOfErrors( new Error(message: 'Message A'), new Error(message: 'Message B'), new Error(message: 'Message A'), ); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected exactly one error matching the criteria but there are 2.'); + $errors->sole(fn (IError $error) => 'Message A' === $error->message()); } #[Test] public function it_throws_when_no_error_matches_the_sole_code(): void { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Expected exactly one error with code "Baz" but there are 0.'); - $errors = new ListOfErrors( new Error(code: TestUnitEnum::Bat, message: 'Message A'), new Error(code: TestUnitEnum::Bat, message: 'Message B'), new Error(code: TestUnitEnum::Bat, message: 'Message C'), ); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected exactly one error with code "Baz" but there are 0.'); + $errors->sole(TestUnitEnum::Baz); } #[Test] public function it_throws_when_many_errors_match_the_sole_code(): void { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('Expected exactly one error with code "Bat" but there are 2.'); - $errors = new ListOfErrors( new Error(code: TestUnitEnum::Bat, message: 'Message A'), new Error(code: TestUnitEnum::Bat, message: 'Message B'), new Error(code: TestUnitEnum::Baz, message: 'Message C'), ); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expected exactly one error with code "Bat" but there are 2.'); + $errors->sole(TestUnitEnum::Bat); } #[Test] - public function it_filters_the_list(): void + public function it_filters_the_list_using_a_callback(): void { $errors = new ListOfErrors( new Error(message: 'Message A'), $b = new Error(code: TestUnitEnum::Bat, message: 'Message B'), - $c = new Error(code: TestUnitEnum::Bat, message: 'Message C'), + new Error(code: TestUnitEnum::Bat, message: 'Message C'), $d = new Error(code: TestUnitEnum::Baz, message: 'Message D'), ); - $filtered1 = $errors->filter(fn (IError $error) => in_array($error, [$b, $d], true)); - $filtered2 = $errors->filter(TestUnitEnum::Bat); + $actual = $errors->filter(fn (IError $error) => in_array($error, [$b, $d], true)); + $this->assertNotSame($errors, $actual); $this->assertCount(4, $errors); - $this->assertSame([$b, $d], $filtered1->all()); - $this->assertSame([$b, $c], $filtered2->filter(TestUnitEnum::Bat)->all()); - $this->assertEmpty($errors->filter(fn (IError $error) => $error->message() === 'Message E')); - $this->assertEmpty($errors->filter(TestBackedEnum::Bar)); + $this->assertSame([$b, $d], $actual->all()); + } + + #[Test] + public function it_filters_the_list_by_code(): void + { + $errors = new ListOfErrors( + new Error(message: 'Message A'), + $b = new Error(code: TestUnitEnum::Bat, message: 'Message B'), + $c = new Error(code: TestUnitEnum::Bat, message: 'Message C'), + new Error(code: TestUnitEnum::Baz, message: 'Message D'), + ); + + $actual = $errors->filter(TestUnitEnum::Bat); + + $this->assertCount(4, $errors); + $this->assertSame([$b, $c], $actual->all()); + } + + /** + * @return array + */ + public static function noMatchProvider(): array + { + return [ + 'callback' => [static fn (IError $error): bool => $error->message() === 'Message E'], + 'code' => [TestBackedEnum::Bar], + ]; + } + + #[DataProvider('noMatchProvider')] + #[Test] + public function it_filters_to_an_empty_list_when_no_errors_match(Closure|UnitEnum $matcher): void + { + $errors = new ListOfErrors( + new Error(message: 'Message A'), + new Error(code: TestUnitEnum::Bat, message: 'Message B'), + ); + + $actual = $errors->filter($matcher); + + $this->assertTrue($actual->isEmpty()); } #[Test] public function it_returns_unique_codes(): void { - $errors1 = new ListOfErrors( + $errors = new ListOfErrors( new Error(message: 'Message A'), new Error(code: TestBackedEnum::Foo, message: 'Message B'), new Error(code: TestUnitEnum::Baz, message: 'Message C'), new Error(code: TestBackedEnum::Foo, message: 'Message D'), ); - $errors2 = new ListOfErrors( + $actual = $errors->codes(); + + $this->assertSame([TestBackedEnum::Foo, TestUnitEnum::Baz], $actual); + } + + #[Test] + public function it_returns_no_codes_when_errors_do_not_have_codes(): void + { + $errors = new ListOfErrors( new Error(message: 'Message E'), new Error(message: 'Message F'), ); - $this->assertSame([TestBackedEnum::Foo, TestUnitEnum::Baz], $errors1->codes()); - $this->assertEmpty($errors2->codes()); + $actual = $errors->codes(); + + $this->assertSame([], $actual); } #[Test] public function it_returns_the_first_code(): void { - $errors1 = new ListOfErrors( + $errors = new ListOfErrors( new Error(message: 'Message A'), new Error(code: TestBackedEnum::Foo, message: 'Message B'), new Error(code: TestUnitEnum::Baz, message: 'Message C'), new Error(code: TestBackedEnum::Foo, message: 'Message D'), ); - $errors2 = new ListOfErrors( + $actual = $errors->code(); + + $this->assertSame(TestBackedEnum::Foo, $actual); + } + + #[Test] + public function it_returns_no_code_when_errors_do_not_have_codes(): void + { + $errors = new ListOfErrors( new Error(message: 'Message E'), new Error(message: 'Message F'), ); - $this->assertSame(TestBackedEnum::Foo, $errors1->code()); - $this->assertNull($errors2->code()); + $actual = $errors->code(); + + $this->assertNull($actual); } #[Test] @@ -338,26 +464,122 @@ public function it_returns_unique_messages(): void new Error(message: 'Message C'), ); - $this->assertSame(['Message A', 'Message B', 'Message C'], $errors->messages()); + $actual = $errors->messages(); + + $this->assertSame(['Message A', 'Message B', 'Message C'], $actual); } #[Test] public function it_returns_the_first_message(): void { - $errors1 = new ListOfErrors( - new Error(message: 'Message A'), - new Error(message: 'Message B'), + $errors = new ListOfErrors( new Error(code: TestUnitEnum::Baz), new Error(message: 'Message A'), - new Error(message: 'Message C'), + new Error(message: 'Message B'), ); - $errors2 = new ListOfErrors( + $actual = $errors->message(); + + $this->assertSame('Message A', $actual); + } + + #[Test] + public function it_returns_no_message_when_errors_do_not_have_messages(): void + { + $errors = new ListOfErrors( new Error(code: TestUnitEnum::Baz), new Error(code: TestBackedEnum::Foo), ); - $this->assertSame('Message A', $errors1->message()); - $this->assertNull($errors2->message()); + $actual = $errors->message(); + + $this->assertNull($actual); + } + + // ------------------------------------------------------------------------- + // from() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_the_same_instance_when_created_from_a_list_of_errors(): void + { + $errors = new ListOfErrors(new Error(null, 'Message A')); + + $actual = ListOfErrors::from($errors); + + $this->assertSame($errors, $actual); + } + + #[Test] + public function it_is_created_from_another_list_of_errors_implementation(): void + { + $a = new Error(null, 'Message A'); + $b = new Error(null, 'Message B'); + $other = $this->createStub(IListOfErrors::class); + $other->method('getIterator')->willReturn(new ArrayIterator([$a, $b])); + + $actual = ListOfErrors::from($other); + + $this->assertEquals(new ListOfErrors($a, $b), $actual); + } + + #[Test] + public function it_is_created_from_an_array_of_errors(): void + { + $a = new Error(null, 'Message A'); + $b = new Error(null, 'Message B'); + + $actual = ListOfErrors::from(['foo' => $a, 'bar' => $b]); + + $this->assertSame([$a, $b], $actual->all()); + } + + #[Test] + public function it_is_created_from_an_error(): void + { + $error = new Error(null, 'Message A'); + + $actual = ListOfErrors::from($error); + + $this->assertSame([$error], $actual->all()); + } + + #[Test] + public function it_is_created_from_a_string(): void + { + $actual = ListOfErrors::from('Message A'); + + $this->assertEquals(new ListOfErrors(new Error(message: 'Message A')), $actual); + } + + /** + * @return array + */ + public static function codeProvider(): array + { + return [ + 'unit enum' => [TestUnitEnum::Baz], + 'backed enum' => [TestBackedEnum::Foo], + ]; + } + + #[DataProvider('codeProvider')] + #[Test] + public function it_is_created_from_an_error_code(UnitEnum $code): void + { + $actual = ListOfErrors::from($code); + + $this->assertEquals(new ListOfErrors(new Error(code: $code)), $actual); + } + + #[Test] + public function it_reindexes_errors_passed_to_the_constructor(): void + { + $a = new Error(null, 'Message A'); + $b = new Error(null, 'Message B'); + + $actual = new ListOfErrors(...['foo' => $a, 'bar' => $b]); + + $this->assertSame([$a, $b], $actual->all()); } } diff --git a/tests/Unit/Toolkit/Result/MetaTest.php b/tests/Unit/Toolkit/Result/MetaTest.php index c5d7912a..35973a14 100644 --- a/tests/Unit/Toolkit/Result/MetaTest.php +++ b/tests/Unit/Toolkit/Result/MetaTest.php @@ -12,7 +12,10 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Result; +use CloudCreativity\Modules\Contracts\Toolkit\Iterables\KeyedSet; use CloudCreativity\Modules\Toolkit\Result\Meta; +use LogicException; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -29,16 +32,57 @@ public function it_holds_values(): void $this->assertCount(3, $meta); $this->assertSame($values, $meta->all()); - $this->assertSame($values['baz'], $meta->get('baz')); - $this->assertNull($meta->get('foobar', 'default')); - $this->assertTrue($meta->exists('foobar')); - $this->assertNull($meta->get('blah')); - $this->assertFalse($meta->exists('blah')); - $this->assertSame('default', $meta->get('blah', 'default')); $this->assertTrue($meta->isNotEmpty()); $this->assertFalse($meta->isEmpty()); } + /** + * @return array + */ + public static function getProvider(): array + { + return [ + 'value' => ['baz', null, 'bat'], + 'null value with default' => ['foobar', 'default', null], + 'missing key' => ['blah', null, null], + 'missing key with default' => ['blah', 'default', 'default'], + ]; + } + + #[DataProvider('getProvider')] + #[Test] + public function it_gets_a_value(string $key, mixed $default, mixed $expected): void + { + $meta = new Meta(['foo' => 'bar', 'baz' => 'bat', 'foobar' => null]); + + $actual = $meta->get($key, $default); + + $this->assertSame($expected, $actual); + } + + /** + * @return array + */ + public static function existsProvider(): array + { + return [ + 'value' => ['foo', true], + 'null value' => ['foobar', true], + 'missing key' => ['blah', false], + ]; + } + + #[DataProvider('existsProvider')] + #[Test] + public function it_checks_if_a_value_exists(string $key, bool $expected): void + { + $meta = new Meta(['foo' => 'bar', 'foobar' => null]); + + $actual = $meta->exists($key); + + $this->assertSame($expected, $actual); + } + #[Test] public function it_is_iterable(): void { @@ -61,15 +105,38 @@ public function it_can_be_empty(): void $this->assertFalse($meta->isNotEmpty()); } + /** + * @return array + */ + public static function offsetGetProvider(): array + { + return [ + 'value' => ['baz', 'bat'], + 'null value' => ['foobar', null], + 'missing key' => ['blah', null], + ]; + } + + #[DataProvider('offsetGetProvider')] #[Test] - public function it_supports_array_access(): void + public function it_gets_values_via_array_access(string $key, mixed $expected): void { $meta = new Meta(['foo' => 'bar', 'baz' => 'bat', 'foobar' => null]); - $this->assertSame('bat', $meta['baz']); - $this->assertNull($meta['foobar']); - $this->assertTrue(isset($meta['foobar'])); - $this->assertFalse(isset($meta['blah'])); + $actual = $meta[$key]; + + $this->assertSame($expected, $actual); + } + + #[DataProvider('existsProvider')] + #[Test] + public function it_checks_if_a_value_is_set_via_array_access(string $key, bool $expected): void + { + $meta = new Meta(['foo' => 'bar', 'foobar' => null]); + + $actual = isset($meta[$key]); + + $this->assertSame($expected, $actual); } #[Test] @@ -77,7 +144,9 @@ public function it_cannot_unset_values(): void { $meta = new Meta(['foo' => 'bar']); - $this->expectException(\LogicException::class); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Result meta is immutable.'); + unset($meta['foo']); } @@ -86,7 +155,9 @@ public function it_cannot_set_values_via_array_access(): void { $meta = new Meta(['foo' => 'bar']); - $this->expectException(\LogicException::class); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Result meta is immutable.'); + $meta['foo'] = 'foobar'; } @@ -94,6 +165,7 @@ public function it_cannot_set_values_via_array_access(): void public function it_puts_a_value_immutably(): void { $original = new Meta(['foo' => 'bar', 'baz' => 'bat']); + $actual = $original->put('foo', 'foobar'); $this->assertNotSame($original, $actual); @@ -105,6 +177,7 @@ public function it_puts_a_value_immutably(): void public function it_merges_an_array(): void { $original = new Meta(['foo' => 'bar', 'baz' => 'bat']); + $actual = $original->merge(['foo' => null, 'foobar' => 'bazbat']); $this->assertNotSame($original, $actual); @@ -116,10 +189,81 @@ public function it_merges_an_array(): void public function it_merges_another_meta(): void { $original = new Meta(['foo' => 'bar', 'baz' => 'bat']); + $actual = $original->merge(new Meta(['foo' => null, 'foobar' => 'bazbat'])); $this->assertNotSame($original, $actual); $this->assertSame(['foo' => 'bar', 'baz' => 'bat'], $original->all()); $this->assertSame(['foo' => null, 'baz' => 'bat', 'foobar' => 'bazbat'], $actual->all()); } + + #[Test] + public function it_is_a_keyed_set(): void + { + $meta = new Meta(); + + $this->assertInstanceOf(KeyedSet::class, $meta); + } + + #[Test] + public function it_casts_an_array(): void + { + $values = ['foo' => 'bar', 'baz' => 'bat']; + + $actual = Meta::cast($values); + + $this->assertEquals(new Meta($values), $actual); + } + + #[Test] + public function it_casts_an_empty_array(): void + { + $actual = Meta::cast([]); + + $this->assertEquals(new Meta(), $actual); + } + + #[Test] + public function it_returns_the_same_instance_when_casting_meta(): void + { + $meta = new Meta(['foo' => 'bar']); + + $actual = Meta::cast($meta); + + $this->assertSame($meta, $actual); + } + + #[Test] + public function it_puts_a_new_value_immutably(): void + { + $original = new Meta(['foo' => 'bar']); + + $actual = $original->put('baz', 'bat'); + + $this->assertNotSame($original, $actual); + $this->assertSame(['foo' => 'bar'], $original->all()); + $this->assertSame(['foo' => 'bar', 'baz' => 'bat'], $actual->all()); + } + + #[Test] + public function it_puts_a_value_into_empty_meta(): void + { + $original = new Meta(); + + $actual = $original->put('foo', 'bar'); + + $this->assertTrue($original->isEmpty()); + $this->assertSame(['foo' => 'bar'], $actual->all()); + } + + #[Test] + public function it_merges_an_empty_array(): void + { + $original = new Meta(['foo' => 'bar']); + + $actual = $original->merge([]); + + $this->assertNotSame($original, $actual); + $this->assertSame(['foo' => 'bar'], $actual->all()); + } } diff --git a/tests/Unit/Toolkit/Result/ResultTest.php b/tests/Unit/Toolkit/Result/ResultTest.php index 7d0e7856..91605f29 100644 --- a/tests/Unit/Toolkit/Result/ResultTest.php +++ b/tests/Unit/Toolkit/Result/ResultTest.php @@ -12,6 +12,8 @@ namespace CloudCreativity\Modules\Tests\Unit\Toolkit\Result; +use Closure; +use CloudCreativity\Modules\Contracts\Toolkit\Result\Error as IError; use CloudCreativity\Modules\Contracts\Toolkit\Result\ListOfErrors as IListOfErrors; use CloudCreativity\Modules\Contracts\Toolkit\Result\Result as IResult; use CloudCreativity\Modules\Tests\TestBackedEnum; @@ -21,7 +23,8 @@ use CloudCreativity\Modules\Toolkit\Result\ListOfErrors; use CloudCreativity\Modules\Toolkit\Result\Meta; use CloudCreativity\Modules\Toolkit\Result\Result; -use PHPUnit\Framework\Attributes\Depends; +use LogicException; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use UnitEnum; @@ -30,11 +33,26 @@ final class ResultTest extends TestCase { + /** + * @return array + */ + public static function defaultMessageProvider(): array + { + return [ + 'no default' => [null], + 'string default' => ['Default message.'], + 'closure default' => [static fn (): never => throw new LogicException('Should not be called.')], + ]; + } + + // ------------------------------------------------------------------------- + // ok() + // ------------------------------------------------------------------------- + #[Test] public function it_creates_a_successful_result_without_a_value(): void { $result = Result::ok(); - $result->abort(); $this->assertInstanceOf(IResult::class, $result); $this->assertNull($result->value()); @@ -43,9 +61,6 @@ public function it_creates_a_successful_result_without_a_value(): void $this->assertFalse($result->didFail()); $this->assertTrue($result->errors()->isEmpty()); $this->assertTrue($result->meta()->isEmpty()); - $this->assertNull($result->error()); - $this->assertNull($result->error('There is no error!')); - $this->assertNull($result->error(fn (): never => $this->fail('Should not be called.'))); $this->assertNull($result->code()); } @@ -60,17 +75,42 @@ public function it_creates_a_successful_result_with_a_value(): void $this->assertFalse($result->didFail()); $this->assertTrue($result->errors()->isEmpty()); $this->assertTrue($result->meta()->isEmpty()); - $this->assertNull($result->error()); $this->assertNull($result->code()); } /** - * @return Result + * @param (Closure(UnitEnum): non-empty-string)|non-empty-string|null $default */ + #[DataProvider('defaultMessageProvider')] + #[Test] + public function it_does_not_have_an_error_message_when_successful(Closure|string|null $default): void + { + $result = Result::ok(); + + $actual = $result->error($default); + + $this->assertNull($actual); + } + + #[Test] + public function it_does_not_throw_when_aborting_a_successful_result(): void + { + $result = Result::ok(); + + $this->expectNotToPerformAssertions(); + + $result->abort(); + } + + // ------------------------------------------------------------------------- + // failed() and fail() + // ------------------------------------------------------------------------- + #[Test] - public function it_creates_a_failed_result(): Result + public function it_creates_a_failed_result(): void { $errors = new ListOfErrors(new Error(null, 'Something went wrong.')); + $result = Result::failed($errors); $this->assertFalse($result->didSucceed()); @@ -78,85 +118,50 @@ public function it_creates_a_failed_result(): Result $this->assertNull($result->safe()); $this->assertSame($errors, $result->errors()); $this->assertTrue($result->meta()->isEmpty()); - $this->assertSame('Something went wrong.', $result->error()); - $this->assertSame('Something went wrong.', $result->error('Blah!')); - $this->assertSame('Something went wrong.', $result->error( - fn (): never => $this->fail('Should not be called.'), - )); $this->assertNull($result->code()); - $this->assertEquals($result, Result::fail($errors)); - - return $result; } /** - * @param Result $result + * @param (Closure(UnitEnum): non-empty-string)|non-empty-string|null $default */ - #[Depends('it_creates_a_failed_result')] - #[Test] - public function it_throws_when_aborting_a_failed_result(Result $result): void - { - try { - $result->abort(); - $this->fail('No exception thrown.'); - } catch (FailedResultException $ex) { - $this->assertSame($result, $ex->getResult()); - } - } - + #[DataProvider('defaultMessageProvider')] #[Test] - public function it_returns_the_first_message_and_code_from_multiple_errors(): void + public function it_returns_the_error_message_when_failed(Closure|string|null $default): void { - $errors = new ListOfErrors( - new Error(code: TestBackedEnum::Foo), - new Error(code: TestUnitEnum::Baz), - new Error(message: 'Message A'), - new Error(message: 'Message B'), - ); + $result = Result::failed(new Error(null, 'Something went wrong.')); - $result = Result::failed($errors); + $actual = $result->error($default); - $this->assertSame('Message A', $result->error()); - $this->assertSame('Message A', $result->error(fn (): never => $this->fail('Should not be called.'))); - $this->assertSame(TestBackedEnum::Foo, $result->code()); + $this->assertSame('Something went wrong.', $actual); } - #[Test] - public function it_resolves_the_message_when_errors_only_have_codes(): void + /** + * @return array|IError|IListOfErrors|string|UnitEnum}> + */ + public static function failureProvider(): array { - $errors = new ListOfErrors( - new Error(code: TestBackedEnum::Foo), - new Error(code: TestUnitEnum::Baz), - ); - - $result = Result::failed($errors); + $error = new Error(null, 'Something went wrong.'); - $this->assertSame(TestBackedEnum::Foo, $result->code()); - $this->assertNull($result->error()); - $this->assertSame('Unknown error!', $result->error('Unknown error!')); - $this->assertSame( - enum_string(TestBackedEnum::Foo), - $result->error(function (UnitEnum $code): string { - $this->assertSame(TestBackedEnum::Foo, $code); - return enum_string($code); - }), - ); - $this->assertSame(TestBackedEnum::Foo, $result->code()); + return [ + 'list of errors' => [new ListOfErrors($error)], + 'error' => [$error], + 'string' => ['Something went wrong.'], + 'array of errors' => [[$error]], + 'enum' => [TestBackedEnum::Foo], + ]; } /** - * @param Result $result + * @param array|IError|IListOfErrors|string|UnitEnum $errors */ - #[Depends('it_creates_a_failed_result')] + #[DataProvider('failureProvider')] #[Test] - public function it_throws_when_getting_value_on_failed_result(Result $result): void - { - try { - $result->value(); - $this->fail('No exception thrown.'); - } catch (FailedResultException $ex) { - $this->assertSame($result, $ex->getResult()); - } + public function it_creates_a_failed_result_using_the_fail_alias( + array|IError|IListOfErrors|string|UnitEnum $errors, + ): void { + $actual = Result::fail($errors); + + $this->assertEquals(Result::failed($errors), $actual); } #[Test] @@ -164,72 +169,221 @@ public function it_fails_with_a_list_of_errors_implementation(): void { $errors = $this->createStub(IListOfErrors::class); $errors->method('isNotEmpty')->willReturn(true); + $result = Result::failed($errors); $this->assertFalse($result->didSucceed()); $this->assertTrue($result->didFail()); $this->assertSame($errors, $result->errors()); - $this->assertEquals($result, Result::fail($errors)); } #[Test] public function it_fails_with_an_error(): void { $error = new Error(null, 'Something went wrong.'); + $result = Result::failed($error); $this->assertEquals(new ListOfErrors($error), $result->errors()); - $this->assertEquals($result, Result::fail($error)); } #[Test] public function it_fails_with_a_string_error(): void { - $error = new Error(null, 'Something went wrong.'); - $result = Result::failed($error->message()); + $result = Result::failed('Something went wrong.'); - $this->assertEquals(new ListOfErrors($error), $result->errors()); - $this->assertEquals($result, Result::fail($error->message())); + $this->assertEquals(new ListOfErrors(new Error(null, 'Something went wrong.')), $result->errors()); } #[Test] public function it_fails_with_an_array_of_errors(): void { $error = new Error(null, 'Something went wrong.'); + $result = Result::failed([$error]); $this->assertEquals(new ListOfErrors($error), $result->errors()); - $this->assertEquals($result, Result::fail([$error])); } #[Test] public function it_fails_with_an_enum_error_code(): void { - $error = new Error(code: $code = TestBackedEnum::Foo); - $result = Result::failed($code); + $result = Result::failed(TestBackedEnum::Foo); - $this->assertEquals(new ListOfErrors($error), $result->errors()); - $this->assertEquals($result, Result::fail($code)); + $this->assertEquals(new ListOfErrors(new Error(code: TestBackedEnum::Foo)), $result->errors()); } + // ------------------------------------------------------------------------- + // abort() and value() + // ------------------------------------------------------------------------- + #[Test] - public function it_requires_errors_when_calling_failed(): void + public function it_throws_when_aborting_a_failed_result(): void { - $this->expectException(\AssertionError::class); - Result::failed(new ListOfErrors()); + $result = Result::failed('Something went wrong.'); + + $this->expectException(FailedResultException::class); + $this->expectExceptionMessage('Something went wrong.'); + + $result->abort(); } #[Test] - public function it_requires_errors_when_calling_fail(): void + public function it_throws_with_the_result_when_aborting_a_failed_result(): void { - $this->expectException(\AssertionError::class); - Result::fail(new ListOfErrors()); + $result = Result::failed('Something went wrong.'); + $actual = null; + + try { + $result->abort(); + } catch (FailedResultException $ex) { + $actual = $ex->getResult(); + } + + $this->assertSame($result, $actual); } + #[Test] + public function it_throws_when_getting_the_value_of_a_failed_result(): void + { + $result = Result::failed('Something went wrong.'); + + $this->expectException(FailedResultException::class); + $this->expectExceptionMessage('Something went wrong.'); + + $result->value(); + } + + #[Test] + public function it_throws_with_the_result_when_getting_the_value_of_a_failed_result(): void + { + $result = Result::failed('Something went wrong.'); + $actual = null; + + try { + $result->value(); + } catch (FailedResultException $ex) { + $actual = $ex->getResult(); + } + + $this->assertSame($result, $actual); + } + + // ------------------------------------------------------------------------- + // error() and code() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_the_first_message_from_multiple_errors(): void + { + $result = Result::failed([ + new Error(code: TestBackedEnum::Foo), + new Error(code: TestUnitEnum::Baz), + new Error(message: 'Message A'), + new Error(message: 'Message B'), + ]); + + $actual = $result->error(static fn (): never => throw new LogicException('Should not be called.')); + + $this->assertSame('Message A', $actual); + } + + #[Test] + public function it_returns_the_first_code_from_multiple_errors(): void + { + $result = Result::failed([ + new Error(message: 'Message A'), + new Error(code: TestBackedEnum::Foo), + new Error(code: TestUnitEnum::Baz), + ]); + + $actual = $result->code(); + + $this->assertSame(TestBackedEnum::Foo, $actual); + } + + #[Test] + public function it_returns_null_when_errors_only_have_codes_and_there_is_no_default(): void + { + $result = Result::failed([ + new Error(code: TestBackedEnum::Foo), + new Error(code: TestUnitEnum::Baz), + ]); + + $actual = $result->error(); + + $this->assertNull($actual); + } + + #[Test] + public function it_returns_the_default_message_when_errors_only_have_codes(): void + { + $result = Result::failed([ + new Error(code: TestBackedEnum::Foo), + new Error(code: TestUnitEnum::Baz), + ]); + + $actual = $result->error('Unknown error!'); + + $this->assertSame('Unknown error!', $actual); + } + + #[Test] + public function it_resolves_the_message_from_the_first_code_when_errors_only_have_codes(): void + { + $result = Result::failed([ + new Error(code: TestBackedEnum::Foo), + new Error(code: TestUnitEnum::Baz), + ]); + $received = null; + + $actual = $result->error(function (UnitEnum $code) use (&$received): string { + $received = $code; + return enum_string($code); + }); + + $this->assertSame(enum_string(TestBackedEnum::Foo), $actual); + $this->assertSame(TestBackedEnum::Foo, $received); + } + + #[Test] + public function it_throws_when_resolving_a_default_message_without_a_code(): void + { + $errors = $this->createStub(IListOfErrors::class); + $errors->method('isNotEmpty')->willReturn(true); + $errors->method('message')->willReturn(null); + $errors->method('code')->willReturn(null); + $result = Result::failed($errors); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Expecting errors to have a code if there is no message.'); + + $result->error(fn (UnitEnum $code): string => enum_string($code)); + } + + #[Test] + public function it_returns_the_default_message_when_errors_have_no_message_or_code(): void + { + $errors = $this->createStub(IListOfErrors::class); + $errors->method('isNotEmpty')->willReturn(true); + $errors->method('message')->willReturn(null); + $errors->method('code')->willReturn(null); + $result = Result::failed($errors); + + $actual = $result->error('Unknown error!'); + + $this->assertSame('Unknown error!', $actual); + } + + // ------------------------------------------------------------------------- + // withMeta() + // ------------------------------------------------------------------------- + #[Test] public function it_sets_meta(): void { $meta = new Meta(['foo' => 'bar']); + $result = Result::ok()->withMeta($meta); $this->assertEquals($meta, $result->meta()); @@ -238,30 +392,92 @@ public function it_sets_meta(): void #[Test] public function it_sets_meta_from_an_array(): void { - $meta = new Meta(['foo' => 'bar']); - $result = Result::ok()->withMeta($meta->all()); + $result = Result::ok()->withMeta(['foo' => 'bar']); - $this->assertEquals($meta, $result->meta()); + $this->assertEquals(new Meta(['foo' => 'bar']), $result->meta()); } #[Test] public function it_merges_meta_values(): void { - $result1 = Result::ok() - ->withMeta($values = ['foo' => 'bar', 'baz' => 'bat', 'foobar' => null]); + $result = Result::ok()->withMeta(['foo' => 'bar', 'baz' => 'bat', 'foobar' => null]); - $result2 = $result1->withMeta([ + $actual = $result->withMeta([ 'baz' => 'blah', 'foobar' => 'bazbat', 'bazbat' => 'blah!', ]); - $this->assertSame($values, $result1->meta()->all()); + $this->assertNotSame($result, $actual); + $this->assertSame(['foo' => 'bar', 'baz' => 'bat', 'foobar' => null], $result->meta()->all()); $this->assertSame([ 'foo' => 'bar', 'baz' => 'blah', 'foobar' => 'bazbat', 'bazbat' => 'blah!', - ], $result2->meta()->all()); + ], $actual->meta()->all()); + } + + #[Test] + public function it_merges_meta_with_a_meta_instance(): void + { + $result = Result::ok()->withMeta(['foo' => 'bar', 'baz' => 'bat']); + + $actual = $result->withMeta(new Meta(['baz' => 'blah'])); + + $this->assertSame(['foo' => 'bar', 'baz' => 'blah'], $actual->meta()->all()); + } + + #[Test] + public function it_keeps_the_value_when_setting_meta(): void + { + $result = Result::ok(99); + + $actual = $result->withMeta(['foo' => 'bar']); + + $this->assertNotSame($result, $actual); + $this->assertTrue($actual->didSucceed()); + $this->assertSame(99, $actual->value()); + $this->assertTrue($result->meta()->isEmpty()); + } + + #[Test] + public function it_keeps_the_errors_when_setting_meta(): void + { + $result = Result::failed('Something went wrong.'); + + $actual = $result->withMeta(['foo' => 'bar']); + + $this->assertNotSame($result, $actual); + $this->assertTrue($actual->didFail()); + $this->assertSame($result->errors(), $actual->errors()); + $this->assertTrue($result->meta()->isEmpty()); + } + + // ------------------------------------------------------------------------- + // context() + // ------------------------------------------------------------------------- + + #[Test] + public function it_returns_context_for_a_successful_result(): void + { + $result = Result::ok(99)->withMeta(['foo' => 'bar']); + + $actual = $result->context(); + + $this->assertSame(['success' => true, 'value' => 99, 'meta' => ['foo' => 'bar']], $actual); + } + + #[Test] + public function it_returns_context_for_a_failed_result(): void + { + $result = Result::failed(new Error(code: TestUnitEnum::Baz, message: 'Something went wrong.')); + + $actual = $result->context(); + + $this->assertSame([ + 'success' => false, + 'error' => ['code' => TestUnitEnum::Baz, 'message' => 'Something went wrong.'], + ], $actual); } } diff --git a/tests/Unit/Toolkit/SensitiveTest.php b/tests/Unit/Toolkit/SensitiveTest.php new file mode 100644 index 00000000..6e19fd65 --- /dev/null +++ b/tests/Unit/Toolkit/SensitiveTest.php @@ -0,0 +1,48 @@ +getAttributes(Sensitive::class); + + $this->assertCount(1, $attributes); + $this->assertInstanceOf(Sensitive::class, $attributes[0]->newInstance()); + } + + #[Test] + public function it_only_targets_properties(): void + { + $reflection = new ReflectionClass(Sensitive::class); + + $attribute = $reflection->getAttributes(Attribute::class)[0]->newInstance(); + + $this->assertSame(Attribute::TARGET_PROPERTY, $attribute->flags); + } +}