diff --git a/.claude/skills/unit-testing/SKILL.md b/.claude/skills/unit-testing/SKILL.md
new file mode 100644
index 00000000..7e031ed9
--- /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 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/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/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..845707a7 100644
--- a/tests/Integration/Bus/MathCommandBusTest.php
+++ b/tests/Integration/Bus/MathCommandBusTest.php
@@ -16,13 +16,20 @@
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
+ 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));
@@ -30,14 +37,36 @@ public function test(): 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 b22873ee..db1914c1 100644
--- a/tests/Integration/Bus/MathEventBusTest.php
+++ b/tests/Integration/Bus/MathEventBusTest.php
@@ -16,17 +16,30 @@
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
+ 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);
@@ -35,16 +48,60 @@ public function test(): 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 6c8589d2..a20e72a6 100644
--- a/tests/Integration/Bus/MathQueryBusTest.php
+++ b/tests/Integration/Bus/MathQueryBusTest.php
@@ -15,13 +15,20 @@
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
+ 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));
@@ -30,13 +37,34 @@ public function test(): 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 62c30dd7..8f906535 100644
--- a/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php
+++ b/tests/Integration/Infrastructure/OutboundEventBus/MathEventPublisherTest.php
@@ -17,30 +17,86 @@
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
+ 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/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..514f4003 100644
--- a/tests/Integration/Infrastructure/Queue/MathQueueTest.php
+++ b/tests/Integration/Infrastructure/Queue/MathQueueTest.php
@@ -17,30 +17,86 @@
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
+ 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/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/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 42942aa9..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\MockObject\MockObject;
+use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class CommandDispatcherTest extends TestCase
{
- private CommandHandlerContainer&MockObject $handlers;
-
- private MockObject&PipeContainer $middleware;
-
- private CommandDispatcher $dispatcher;
-
/**
- * @var array
+ * @var list
*/
private array $sequence = [];
- protected function setUp(): void
+ #[Test]
+ public function it_dispatches_a_command(): void
{
- parent::setUp();
-
- $this->dispatcher = new class (
- handlers: $this->handlers = $this->createMock(CommandHandlerContainer::class),
- middleware: $this->middleware = $this->createMock(PipeContainer::class),
- ) extends CommandDispatcher {};
- }
-
- protected function tearDown(): void
- {
- unset($this->handlers, $this->middleware, $this->dispatcher, $this->sequence);
- parent::tearDown();
- }
-
- public function test(): void
- {
- $command = $this->createMock(Command::class);
+ $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,20 +50,22 @@ public function test(): void
->with($this->identicalTo($command))
->willReturn($expected = Result::ok());
- $actual = $this->dispatcher->dispatch($command);
+ $actual = $dispatcher->dispatch($command);
$this->assertSame($expected, $actual);
}
- public function testWithMiddleware(): void
+ #[Test]
+ public function it_dispatches_a_command_through_middleware(): void
{
$command1 = new TestCommand();
$command2 = new TestCommand();
$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);
@@ -87,7 +73,7 @@ public function testWithMiddleware(): 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);
@@ -95,7 +81,7 @@ public function testWithMiddleware(): 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);
@@ -103,7 +89,15 @@ public function testWithMiddleware(): 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)
->willReturnCallback(function () use ($handler) {
@@ -111,15 +105,6 @@ public function testWithMiddleware(): void
return $handler;
});
- $this->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 +116,7 @@ public function testWithMiddleware(): 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([
@@ -144,4 +128,68 @@ public function testWithMiddleware(): 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 eaf35e6f..a17cd65b 100644
--- a/tests/Unit/Application/Bus/CommandHandlerContainerTest.php
+++ b/tests/Unit/Application/Bus/CommandHandlerContainerTest.php
@@ -16,19 +16,20 @@
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
{
- public function testItResolvesUsingClosureBindings(): void
+ #[Test]
+ public function it_resolves_using_closure_bindings(): void
{
$a = new class () extends TestCommandHandler {};
$b = $this->createStub(TestCommandHandler::class);
$command1 = new class () implements Command {};
$command2 = new class () implements Command {};
- $command3 = new class () implements Command {};
$container = new CommandHandlerContainer();
$container->bind($command1::class, fn () => $a);
@@ -36,31 +37,35 @@ public function testItResolvesUsingClosureBindings(): 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);
}
- public function testItResolvesViaPsrContainer(): void
+ #[Test]
+ public function it_resolves_via_psr_container(): void
{
$a = new class () extends TestCommandHandler {};
$b = $this->createStub(TestCommandHandler::class);
$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);
@@ -68,10 +73,34 @@ public function testItResolvesViaPsrContainer(): 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 ee8fc2c4..f63cbf56 100644
--- a/tests/Unit/Application/Bus/CommandHandlerTest.php
+++ b/tests/Unit/Application/Bus/CommandHandlerTest.php
@@ -14,43 +14,58 @@
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(): 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);
}
- public function testItDoesNotHaveExecuteMethod(): void
+ #[Test]
+ 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 61afe652..18eb7bc2 100644
--- a/tests/Unit/Application/Bus/CommandQueuerTest.php
+++ b/tests/Unit/Application/Bus/CommandQueuerTest.php
@@ -13,13 +13,13 @@
namespace CloudCreativity\Modules\Tests\Unit\Application\Bus;
use CloudCreativity\Modules\Application\Bus\CommandQueuer;
-use CloudCreativity\Modules\Contracts\Application\Ports\Queue;
-use PHPUnit\Framework\MockObject\MockObject;
+use CloudCreativity\Modules\Testing\FakeQueue;
+use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class CommandQueuerTest extends TestCase
{
- private MockObject&Queue $queue;
+ private FakeQueue $queue;
private CommandQueuer $queuer;
@@ -28,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 {};
}
@@ -38,13 +38,13 @@ protected function tearDown(): void
parent::tearDown();
}
- public function test(): 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/ExecuteInUnitOfWorkTest.php b/tests/Unit/Application/Bus/Middleware/ExecuteInUnitOfWorkTest.php
index e090764f..9862aa27 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,9 +27,10 @@ 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);
+ $command = $this->createStub(Command::class);
$expected = Result::ok();
$middleware = new ExecuteInUnitOfWork(
@@ -57,9 +59,10 @@ 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);
+ $command = $this->createStub(Command::class);
$expected = Result::failed('Something went wrong.');
$middleware = new ExecuteInUnitOfWork(
@@ -88,9 +91,10 @@ 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);
+ $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 1512ad54..b9bd8b64 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,9 +40,16 @@ protected function setUp(): void
);
}
- public function testItFlushesDeferredEvents(): void
+ protected function tearDown(): void
{
- $command = $this->createMock(Command::class);
+ unset($this->middleware, $this->dispatcher);
+ parent::tearDown();
+ }
+
+ #[Test]
+ public function it_flushes_deferred_events(): void
+ {
+ $command = $this->createStub(Command::class);
$expected = Result::ok();
$this->dispatcher
@@ -65,9 +73,10 @@ 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);
+ $command = $this->createStub(Command::class);
$expected = Result::failed('Something went wrong.');
$this->dispatcher
@@ -87,13 +96,14 @@ public function testItForgetsDeferredEventsOnFailedResult(): void
return $expected;
});
+ $this->assertSame($expected, $actual);
$this->assertSame(['next', 'forget'], $this->sequence);
}
-
- public function testItForgetsDeferredEventsOnException(): 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
@@ -107,17 +117,19 @@ public function testItForgetsDeferredEventsOnException(): 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 89d4ffab..047a1f71 100644
--- a/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php
+++ b/tests/Unit/Application/Bus/Middleware/LogMessageDispatchTest.php
@@ -15,53 +15,44 @@
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\MockObject\Stub;
+use PHPUnit\Framework\Attributes\Test;
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);
parent::tearDown();
- unset($this->logger, $this->message, $this->logs);
}
- public function testWithDefaultLevels(): void
+ #[Test]
+ 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;
@@ -69,17 +60,26 @@ public function testWithDefaultLevels(): 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);
}
- public function testWithCustomLevels(): void
+ #[Test]
+ 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;
@@ -87,28 +87,106 @@ public function testWithCustomLevels(): 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);
}
- public function testItLogsAfterTheNextClosureIsInvoked(): void
+ #[Test]
+ 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);
+ $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/SetupBeforeDispatchTest.php b/tests/Unit/Application/Bus/Middleware/SetupBeforeDispatchTest.php
index 50c3feaf..562db740 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,9 +28,10 @@ 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);
+ $message = $this->createStub(Command::class);
$result = Result::ok();
$middleware = new SetupBeforeDispatch(function () {
@@ -47,9 +49,10 @@ 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);
+ $message = $this->createStub(Query::class);
$result = Result::ok();
$middleware = new SetupBeforeDispatch(function (): Closure {
@@ -69,9 +72,10 @@ 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);
+ $message = $this->createStub(Command::class);
$result = Result::failed('Something went wrong.');
$middleware = new SetupBeforeDispatch(function () {
@@ -89,9 +93,10 @@ 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);
+ $message = $this->createStub(Command::class);
$result = Result::failed('Something went wrong.');
$middleware = new SetupBeforeDispatch(function (): Closure {
@@ -111,9 +116,10 @@ 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);
+ $message = $this->createStub(Command::class);
$exception = new RuntimeException('Something went wrong.');
$actual = null;
@@ -137,9 +143,10 @@ 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);
+ $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 00dbab7f..33f2f687 100644
--- a/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php
+++ b/tests/Unit/Application/Bus/Middleware/TearDownAfterDispatchTest.php
@@ -16,14 +16,16 @@
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);
+ $message = $this->createStub(Command::class);
$result = Result::ok();
$sequence = [];
@@ -41,9 +43,10 @@ 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);
+ $message = $this->createStub(Query::class);
$result = Result::failed('Something went wrong.');
$sequence = [];
@@ -61,9 +64,10 @@ 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);
+ $message = $this->createStub(Command::class);
$exception = new RuntimeException('Something went wrong.');
$actual = null;
$sequence = [];
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 @@
+validator, $this->middleware);
+ parent::tearDown();
+ }
+
+ #[Test]
+ public function it_succeeds(): void
{
$rules = [];
$command = $this->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')
@@ -80,18 +90,21 @@ public function testItSucceeds(): 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);
}
- public function testItFails(): 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')
@@ -106,22 +119,20 @@ public function testItFails(): void
$this->validator
->expects($this->once())
->method('validate')
- ->with($command = $this->createStub(Query::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 = ($this->middleware)($command, $next);
- $this->assertTrue($result?->didFail());
- $this->assertSame($errors, $result->errors());
+ $this->assertEquals(Result::failed($errors), $actual);
}
- 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 {
+ $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
*/
@@ -131,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')
@@ -145,24 +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.')));
+ ->with($this->identicalTo($command))
+ ->willReturn($errors);
- $next = function () {
- throw new \LogicException('Not expecting next closure to be called.');
- };
-
- $result = ($this->middleware)($command, $next);
+ $actual = $middleware($command, $next);
- $this->assertTrue($result?->didFail());
- $this->assertSame($errors, $result->errors());
+ $this->assertEquals(Result::failed($errors), $actual);
}
- public function testItStopsOnFirstFailure(): void
+ #[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);
@@ -182,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')
@@ -196,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);
+ }
+
+ #[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->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();
- $result = ($this->middleware)($command, $next);
+ $this->validator
+ ->expects($this->once())
+ ->method('validate')
+ ->with($this->identicalTo($command))
+ ->willReturn(new ListOfErrors());
- $this->assertTrue($result?->didFail());
- $this->assertSame($errors, $result->errors());
+ $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 1801b7ac..7a3571ad 100644
--- a/tests/Unit/Application/Bus/QueryDispatcherTest.php
+++ b/tests/Unit/Application/Bus/QueryDispatcherTest.php
@@ -12,59 +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\MockObject\MockObject;
+use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class QueryDispatcherTest extends TestCase
{
/**
- * @var MockObject&QueryHandlerContainer
- */
- private QueryHandlerContainer $handlers;
-
- /**
- * @var MockObject&PipeContainer
- */
- private PipeContainer $middleware;
-
- private QueryDispatcher $dispatcher;
-
- /**
- * @var array
+ * @var list
*/
private array $sequence = [];
- protected function setUp(): void
+ #[Test]
+ public function it_dispatches_a_query(): void
{
- parent::setUp();
-
- $this->dispatcher = new class (
- handlers: $this->handlers = $this->createMock(QueryHandlerContainer::class),
- middleware: $this->middleware = $this->createMock(PipeContainer::class),
- ) extends QueryDispatcher {};
- }
-
- protected function tearDown(): void
- {
- unset($this->handlers, $this->middleware, $this->dispatcher, $this->sequence);
- parent::tearDown();
- }
-
- public function test(): void
- {
- $query = $this->createMock(Query::class);
+ $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())
@@ -72,61 +50,61 @@ public function test(): void
->with($this->identicalTo($query))
->willReturn($expected = Result::ok());
- $actual = $this->dispatcher->dispatch($query);
+ $actual = $dispatcher->dispatch($query);
$this->assertSame($expected, $actual);
}
- public function testWithMiddleware(): void
+ #[Test]
+ public function it_dispatches_a_query_through_middleware(): void
{
$query1 = new TestQuery();
$query2 = new TestQuery();
$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;
});
- $this->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')
@@ -138,8 +116,7 @@ public function testWithMiddleware(): 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([
@@ -151,4 +128,68 @@ public function testWithMiddleware(): 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 9f7388da..0e2b5506 100644
--- a/tests/Unit/Application/Bus/QueryHandlerContainerTest.php
+++ b/tests/Unit/Application/Bus/QueryHandlerContainerTest.php
@@ -16,19 +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
{
- public function testItResolvesClosureBindings(): void
+ #[Test]
+ 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);
@@ -36,31 +37,35 @@ public function testItResolvesClosureBindings(): 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);
}
- public function testItResolvesViaPsrContainer(): void
+ #[Test]
+ public function it_resolves_via_psr_container(): 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 {};
-
- $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);
@@ -68,10 +73,34 @@ public function testItResolvesViaPsrContainer(): 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 01b5c749..b196a435 100644
--- a/tests/Unit/Application/Bus/QueryHandlerTest.php
+++ b/tests/Unit/Application/Bus/QueryHandlerTest.php
@@ -14,43 +14,58 @@
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(): 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);
}
- public function testItDoesNotHaveExecuteMethod(): void
+ #[Test]
+ 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 f6beba20..7f2a71a4 100644
--- a/tests/Unit/Application/Bus/ValidatorTest.php
+++ b/tests/Unit/Application/Bus/ValidatorTest.php
@@ -12,21 +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
{
@@ -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');
@@ -63,30 +65,23 @@ public function testItValidatesMessage(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);
}
/**
* @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');
@@ -108,30 +103,23 @@ public function testItValidatesMessageUsingPsrContainer(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);
}
/**
* @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');
@@ -150,21 +138,23 @@ public function testItStopsOnFirstFailure(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);
}
- public function testItHasNoRules(): void
+ #[Test]
+ 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 6a107c7e..b7796263 100644
--- a/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php
+++ b/tests/Unit/Application/DomainEventDispatching/DeferredDispatcherTest.php
@@ -14,35 +14,28 @@
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 PHPUnit\Framework\MockObject\MockObject;
+use LogicException;
+use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class DeferredDispatcherTest extends TestCase
{
- private ListenerContainer&MockObject $listeners;
-
- /**
- * @var MockObject&MockObject&PipeContainer
- */
- private MockObject&PipeContainer $middleware;
-
- 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->middleware = $this->createMock(PipeContainer::class),
- ) extends DeferredDispatcher {};
+ $this->assertInstanceOf(IDeferredDispatcher::class, $dispatcher);
}
- public function testItDispatchesImmediately(): void
+ #[Test]
+ public function it_dispatches_immediately(): void
{
$sequence = [];
$event = new TestImmediateDomainEvent();
@@ -51,18 +44,15 @@ public function testItDispatchesImmediately(): 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())
@@ -92,41 +82,48 @@ public function testItDispatchesImmediately(): void
->expects($this->never())
->method('handle');
- $this->dispatcher->listen($event::class, [
- 'Listener1',
- $listener2Closure,
- 'Listener3',
- ]);
- $this->dispatcher->listen(TestDomainEvent::class, 'Listener4');
+ $dispatcher->dispatch($event);
+
+ $this->assertSame(['Listener1', 'Listener2', 'Listener3'], $sequence);
+ }
- $this->dispatcher->dispatch($event);
+ #[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');
- $this->assertInstanceOf(IDeferredDispatcher::class, $this->dispatcher);
- $this->assertSame($sequence, ['Listener1', 'Listener2', 'Listener3']);
+ $dispatcher->dispatch($event);
}
- public function testItFlushesDeferredEvents(): void
+ #[Test]
+ 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);
$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())
@@ -160,41 +157,30 @@ public function testItFlushesDeferredEvents(): 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);
}
- public function testItFlushesDeferredEventsIncludingEventsDispatchedByListeners(): void
+ #[Test]
+ public function it_flushes_deferred_events_including_events_dispatched_by_listeners(): 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);
$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())
@@ -208,9 +194,9 @@ public function testItFlushesDeferredEventsIncludingEventsDispatchedByListeners(
->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
@@ -221,116 +207,76 @@ public function testItFlushesDeferredEventsIncludingEventsDispatchedByListeners(
$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);
}
- public function testItForgetsDeferredEvents(): void
+ #[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
- ->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();
}
- public function testItForgetsDeferredEventsAfterException(): void
+ #[Test]
+ public function it_forgets_deferred_events_after_exception(): void
{
- $sequence = [];
$event1 = new class () extends TestDomainEvent {};
- $event2 = $this->createMock(DomainEvent::class);
- $expected = new \LogicException('Boom!');
+ $event2 = $this->createStub(DomainEvent::class);
$listener1 = $this->createMock(TestListener::class);
$listener2 = $this->createMock(TestListener::class);
$listener3 = $this->createMock(TestListener::class);
$listener4 = $this->createMock(TestListener::class);
- $this->listeners
- ->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())
@@ -340,29 +286,32 @@ public function testItForgetsDeferredEventsAfterException(): 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();
}
- 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);
+ $event = $this->createStub(DomainEvent::class);
+ $listeners = $this->createMock(IListenerContainer::class);
+ $dispatcher = new class ($listeners) extends DeferredDispatcher {};
+ $dispatcher->dispatch($event);
+
+ $listeners
+ ->expects($this->never())
+ ->method($this->anything());
+
+ $dispatcher->flush();
}
- public function testItDispatchesThroughMiddleware(): void
+ #[Test]
+ public function it_dispatches_through_middleware(): void
{
$event1 = new TestImmediateDomainEvent();
$event2 = new TestImmediateDomainEvent();
@@ -380,44 +329,33 @@ public function testItDispatchesThroughMiddleware(): void
return $next($event3);
};
- $this->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);
}
- public function testListenerDoesNotHaveHandleMethod(): 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 968473fb..e4a3789d 100644
--- a/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php
+++ b/tests/Unit/Application/DomainEventDispatching/DispatcherTest.php
@@ -14,54 +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 PHPUnit\Framework\MockObject\MockObject;
+use CloudCreativity\Modules\Testing\FakeContainer;
+use InvalidArgumentException;
+use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class DispatcherTest extends TestCase
{
- private ListenerContainer&MockObject $listeners;
-
- private MockObject&PipeContainer $middleware;
-
- 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->middleware = $this->createMock(PipeContainer::class),
- ) extends Dispatcher {};
+ $this->assertInstanceOf(DomainEventDispatcher::class, $dispatcher);
}
- public function testItDispatchesImmediately(): void
+ #[Test]
+ 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())
@@ -80,41 +71,62 @@ public function testItDispatchesImmediately(): 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->createMock(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);
}
- 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);
+ $event = $this->createStub(DomainEvent::class);
+ $listeners = $this->createMock(IListenerContainer::class);
+ $dispatcher = new class ($listeners) extends Dispatcher {};
+
+ $listeners
+ ->expects($this->never())
+ ->method($this->anything());
+
+ $dispatcher->dispatch($event);
}
- public function testItDispatchesThroughMiddleware(): void
+ #[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 {
@@ -129,44 +141,90 @@ public function testItDispatchesThroughMiddleware(): void
return $next($event3);
};
- $this->middleware
- ->expects($this->once())
- ->method('get')
- ->with('Middleware2')
- ->willReturn($b);
-
$listener = $this->createMock(TestListener::class);
+ $listeners = new ListenerContainer();
+ $listeners->bind('MyListener', fn () => $listener);
+
+ $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->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('Expecting listener to be a Closure or non-empty string.');
- $this->dispatcher->through([$a, 'Middleware2']);
- $this->dispatcher->listen($event3::class, 'MyListener');
- $this->dispatcher->dispatch($event1);
+ $dispatcher->listen(TestImmediateDomainEvent::class, ['Listener1', '']);
}
- public function testListenerDoesNotHaveHandleMethod(): void
+ #[Test]
+ 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 fc1cfa3f..2ce6b1ae 100644
--- a/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php
+++ b/tests/Unit/Application/DomainEventDispatching/ListenerContainerTest.php
@@ -13,34 +13,86 @@
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;
final class ListenerContainerTest extends TestCase
{
- public function testItCreatesListener(): void
+ #[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);
}
- public function testItDoesNotRecogniseListenerName(): void
+ #[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');
}
- public function testItHandlesBindingNotReturningAnObject(): void
+ #[Test]
+ 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 c0ffa34f..fc66cda3 100644
--- a/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php
+++ b/tests/Unit/Application/DomainEventDispatching/Middleware/LogDomainEventDispatchTest.php
@@ -14,19 +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\MockObject\MockObject;
+use PHPUnit\Framework\Attributes\Test;
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;
@@ -34,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.
@@ -54,73 +51,63 @@ public function getOccurredAt(): DateTimeImmutable
};
}
- public function testWithDefaultLevels(): void
+ protected function tearDown(): 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;
- });
+ unset($this->logger, $this->event);
+ parent::tearDown();
+ }
+ #[Test]
+ public function it_logs_with_the_default_levels(): void
+ {
+ $eventName = $this->event::class;
$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);
}
- public function testWithCustomLevels(): void
+ #[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);
}
- public function testItLogsAfterTheNextClosureIsInvoked(): void
+ #[Test]
+ 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->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->assertInstanceOf(DomainEventDispatcher::class, $dispatcher);
}
- public function testItDispatchesImmediately(): void
+ #[Test]
+ public function it_dispatches_immediately(): void
{
$sequence = [];
$event = new TestImmediateDomainEvent();
+ $unitOfWorkManager = $this->createMock(UnitOfWorkManager::class);
$listener1 = $this->createMock(TestListener::class);
$listener2 = $this->createMock(TestListener::class);
@@ -61,21 +52,25 @@ public function testItDispatchesImmediately(): 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())
@@ -117,40 +112,32 @@ public function testItDispatchesImmediately(): void
->expects($this->never())
->method('handle');
- $this->unitOfWorkManager
+ $unitOfWorkManager
->expects($this->once())
->method('beforeCommit');
- $this->unitOfWorkManager
+ $unitOfWorkManager
->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);
}
- public function testItDoesNotDispatchImmediately(): void
+ #[Test]
+ public function it_does_not_dispatch_immediately(): void
{
- $event = $this->createMock(DomainEvent::class);
-
+ $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())
@@ -160,38 +147,30 @@ public function testItDoesNotDispatchImmediately(): void
->expects($this->never())
->method('handle');
- $this->unitOfWorkManager
+ $unitOfWorkManager
->expects($this->once())
- ->method('beforeCommit'); // we'll prove this works in the subsequent test
+ ->method('beforeCommit');
- $this->unitOfWorkManager
+ $unitOfWorkManager
->expects($this->never())
->method('afterCommit');
- $this->dispatcher->listen($event::class, [
- 'Listener1',
- 'Listener2',
- ]);
-
- $this->dispatcher->dispatch($event);
+ $dispatcher->dispatch($event);
}
- #[Depends('testItDoesNotDispatchImmediately')]
- public function testItDispatchesEventInBeforeCommitCallback(): void
+ #[Test]
+ public function it_dispatches_event_in_before_commit_callback(): void
{
$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())
@@ -203,92 +182,93 @@ public function testItDispatchesEventInBeforeCommitCallback(): void
->method('handle')
->with($this->identicalTo($event));
- $this->unitOfWorkManager
+ $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);
}
- public function testBeforeCommitListener(): void
+ #[Test]
+ public function it_dispatches_to_a_before_commit_listener_before_commit(): void
{
$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')
->with($this->identicalTo($event));
- $this->unitOfWorkManager
+ $unitOfWorkManager
->expects($this->once())
->method('beforeCommit')
- ->willReturnCallback(function (Closure $callback) {
+ ->willReturnCallback(function (Closure $callback): void {
$callback();
});
- $this->unitOfWorkManager
+ $unitOfWorkManager
->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);
}
- public function testAfterCommitListener(): void
+ #[Test]
+ public function it_dispatches_to_an_after_commit_listener_after_commit(): void
{
$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')
->with($this->identicalTo($event));
- $this->unitOfWorkManager
+ $unitOfWorkManager
->expects($this->once())
->method('afterCommit')
- ->willReturnCallback(function (Closure $callback) {
+ ->willReturnCallback(function (Closure $callback): void {
$callback();
});
- $this->unitOfWorkManager
+ $unitOfWorkManager
->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);
}
- 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);
+ $event = $this->createStub(DomainEvent::class);
+ $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);
}
- public function testItDispatchesThroughMiddleware(): void
+ #[Test]
+ public function it_dispatches_through_middleware(): void
{
$event1 = new TestImmediateDomainEvent();
$event2 = new TestImmediateDomainEvent();
@@ -306,67 +286,102 @@ public function testItDispatchesThroughMiddleware(): void
return $next($event3);
};
- $this->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);
}
- public function testListenerDoesNotHaveHandleMethod(): void
+ #[Test]
+ 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);
}
- public function testListenerCannotImplementBothBeforeAndAfterCommit(): void
+ #[Test]
+ 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
- ->method('get')
- ->with('InvalidListener')
- ->willReturn($listener);
+ $listener
+ ->expects($this->once())
+ ->method('handle')
+ ->with($this->identicalTo($event));
- $event = new TestImmediateDomainEvent();
- $this->dispatcher->listen($event::class, 'InvalidListener');
+ $unitOfWorkManager->execute(static function () use ($dispatcher, $event): void {
+ $dispatcher->dispatch($event);
+ });
- $this->expectException(\AssertionError::class);
- $this->expectExceptionMessage('cannot be dispatched both before and after a unit of work is committed.');
+ $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);
+ }
- $this->dispatcher->dispatch($event);
+ /**
+ * @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: $container,
+ middleware: $middleware,
+ logger: $logger,
+ ) extends UnitOfWorkAwareDispatcher {};
}
}
diff --git a/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php b/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php
index 9b321d52..f76ecd4e 100644
--- a/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php
+++ b/tests/Unit/Application/InboundEventBus/EventHandlerContainerTest.php
@@ -15,90 +15,127 @@
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
{
- public function testItHasHandlerBindings(): void
+ #[Test]
+ public function it_has_handler_bindings(): void
{
$a = new class () extends TestEventHandler {};
$b = $this->createStub(TestEventHandler::class);
$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));
}
- public function testItUsesPsrContainer(): void
+ #[Test]
+ 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));
}
- public function testItHasBoundDefaultHandler(): void
+ #[Test]
+ 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);
}
- public function testItHasDefaultHandlerInPsrContainer(): void
+ #[Test]
+ 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);
+ }
- 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 {});
$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 0aa87502..f3173689 100644
--- a/tests/Unit/Application/InboundEventBus/EventHandlerTest.php
+++ b/tests/Unit/Application/InboundEventBus/EventHandlerTest.php
@@ -13,42 +13,55 @@
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(): 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);
}
- public function testItDoesNotHaveExecuteMethod(): void
+ #[Test]
+ 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 537eb34e..fd6dd3e1 100644
--- a/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php
+++ b/tests/Unit/Application/InboundEventBus/InboundEventDispatcherTest.php
@@ -12,91 +12,87 @@
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 PHPUnit\Framework\MockObject\MockObject;
+use CloudCreativity\Modules\Testing\FakeContainer;
+use CloudCreativity\Modules\Testing\FakeLogger;
+use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class InboundEventDispatcherTest extends TestCase
{
- private EventHandlerContainer&MockObject $handlers;
-
- private MockObject&PipeContainer $middleware;
-
- private InboundEventDispatcher $dispatcher;
-
/**
- * @var array
+ * @var list
*/
private array $sequence = [];
- protected function setUp(): void
+ #[Test]
+ public function it_dispatches_an_event(): void
{
- parent::setUp();
-
- $this->dispatcher = new class (
- handlers: $this->handlers = $this->createMock(EventHandlerContainer::class),
- middleware: $this->middleware = $this->createMock(PipeContainer::class),
- ) extends InboundEventDispatcher {};
- }
-
- protected function tearDown(): void
- {
- unset($this->handlers, $this->middleware, $this->dispatcher, $this->sequence);
- parent::tearDown();
- }
-
- public function test(): void
- {
- $event = $this->createMock(IntegrationEvent::class);
+ $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);
}
- public function testWithMiddleware(): void
+ #[Test]
+ public function it_dispatches_an_event_through_middleware(): void
{
$event1 = new TestInboundEvent();
$event2 = new TestInboundEvent();
$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)
->willReturnCallback(function () use ($handler) {
@@ -104,15 +100,6 @@ public function testWithMiddleware(): void
return $handler;
});
- $this->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')
@@ -123,8 +110,7 @@ public function testWithMiddleware(): void
->method('__invoke')
->with($this->identicalTo($event4));
- $this->dispatcher->through(['MyFirstMiddleware']);
- $this->dispatcher->dispatch($event1);
+ $dispatcher->dispatch($event1);
$this->assertSame([
'before1',
@@ -135,4 +121,83 @@ public function testWithMiddleware(): 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/Middleware/SetupBeforeEventTest.php b/tests/Unit/Application/InboundEventBus/Middleware/SetupBeforeEventTest.php
index 149d8bd7..28ee2270 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,9 +27,10 @@ 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);
+ $event = $this->createStub(IntegrationEvent::class);
$middleware = new SetupBeforeEvent(function () {
$this->sequence[] = 'setup';
@@ -43,9 +45,10 @@ 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);
+ $event = $this->createStub(IntegrationEvent::class);
$middleware = new SetupBeforeEvent(function (): Closure {
$this->sequence[] = 'setup';
@@ -62,9 +65,10 @@ 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);
+ $event = $this->createStub(IntegrationEvent::class);
$exception = new RuntimeException('Something went wrong.');
$actual = null;
@@ -88,9 +92,10 @@ 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);
+ $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 9cbf0724..641ab707 100644
--- a/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php
+++ b/tests/Unit/Application/InboundEventBus/Middleware/TearDownAfterEventTest.php
@@ -14,14 +14,16 @@
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);
+ $event = $this->createStub(IntegrationEvent::class);
$sequence = [];
$middleware = new TearDownAfterEvent(function () use (&$sequence): void {
@@ -36,9 +38,10 @@ 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);
+ $event = $this->createStub(IntegrationEvent::class);
$exception = new RuntimeException('Something went wrong.');
$actual = null;
$sequence = [];
diff --git a/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php b/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php
index 9a49822e..e9f32ef5 100644
--- a/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php
+++ b/tests/Unit/Application/InboundEventBus/SwallowInboundEventTest.php
@@ -13,54 +13,51 @@
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
{
- public function testItDoesNothing(): void
+ #[Test]
+ public function it_does_nothing(): void
{
$handler = new SwallowInboundEvent();
+
+ $this->expectNotToPerformAssertions();
+
$handler->handle(new TestInboundEvent());
- /** @phpstan-ignore-next-line */
- $this->assertTrue(true);
}
- public function testItLogsThatItDoesNothing(): void
+ #[Test]
+ 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);
}
- 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);
- $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->reporter = $this->createMock(ExceptionReporter::class),
+ $this->reporter = new FakeExceptionReporter(),
);
}
- public function testItExecutesCallbacks(): void
+ protected function tearDown(): void
{
- $sequence = [];
+ unset($this->manager, $this->unitOfWork, $this->reporter);
+ parent::tearDown();
+ }
- $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;
- });
+ #[Test]
+ public function it_executes_callbacks(): void
+ {
+ $sequence = [];
$before1 = function () use (&$sequence): void {
$this->assertSame(['start'], $sequence);
@@ -76,6 +74,17 @@ public function testItExecutesCallbacks(): 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);
@@ -88,20 +97,12 @@ 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');
+ $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);
@@ -117,38 +118,38 @@ public function testItExecutesCallbackWhenTransactionFailsToCommit(): 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);
}
/**
* 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 = [];
- $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);
@@ -184,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]);
@@ -211,35 +223,31 @@ function () use (&$sequence): void {
$this->assertSame($expected, $actual);
}
- public function testItFlushesCallbacksOnSuccessfulTransaction(): void
+ #[Test]
+ public function it_flushes_callbacks_on_successful_transaction(): void
{
$this->unitOfWork
+ ->expects($this->exactly(2))
->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);
}
- public function testItFlushesCallbacksOnUnsuccessfulTransaction(): void
+ #[Test]
+ public function it_flushes_callbacks_on_unsuccessful_transaction(): void
{
$ex = new LogicException('Boom');
$count = 0;
- $this->reporter
- ->expects($this->exactly(2)) // only "swallowed" exceptions are reported
- ->method('report')
- ->with($this->identicalTo($ex));
-
$this->unitOfWork
->expects($this->exactly(4))
->method('execute')
@@ -257,15 +265,15 @@ public function testItFlushesCallbacksOnUnsuccessfulTransaction(): 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
}
/**
@@ -279,17 +287,13 @@ 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 = [];
$count = 0;
- $this->reporter
- ->expects($this->exactly(2))
- ->method('report')
- ->with($this->identicalTo($ex));
-
$before = [
function () use (&$sequence): void {
$sequence[] = 'before1';
@@ -353,6 +357,7 @@ function () use (&$sequence): void {
'after1',
'after2',
], $sequence);
+ $this->assertSame([$ex, $ex], $this->reporter->reported);
}
/**
@@ -368,17 +373,13 @@ 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 = [];
$count = 0;
- $this->reporter
- ->expects($this->exactly(2))
- ->method('report')
- ->with($this->identicalTo($ex));
-
$before = [
function () use (&$sequence): void {
$sequence[] = 'before1';
@@ -398,6 +399,7 @@ function () use (&$sequence): void {
];
$this->unitOfWork
+ ->expects($this->exactly(3))
->method('execute')
->willReturnCallback(function (Closure $closure) use ($ex, &$sequence, &$count): mixed {
$count++;
@@ -437,36 +439,44 @@ function () use (&$sequence): void {
'after1',
'after2',
], $sequence);
+ $this->assertSame([$ex, $ex], $this->reporter->reported);
}
- public function testItFailsIfBeforeCallbacksAreQueuedBeforeTransaction(): void
+ #[Test]
+ public function it_fails_if_before_callbacks_are_queued_before_transaction(): void
{
$this->unitOfWork
->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);
}
- public function testItFailsIfAfterCallbacksAreQueuedBeforeTransaction(): void
+ #[Test]
+ public function it_fails_if_after_callbacks_are_queued_before_transaction(): void
{
- $this->expectException(RuntimeException::class);
+ $this->unitOfWork
+ ->expects($this->never())
+ ->method('execute');
+
+ $this->expectException(ApplicationException::class);
$this->expectExceptionMessage('Cannot queue an after commit callback when not executing a unit of work.');
$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())
->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.',
);
@@ -476,13 +486,15 @@ public function testItCannotStartTransactionWithinAnExistingOne(): void
});
}
- public function testItFailsIfAfterCommitCallbackRegistersBeforeCommitCallback(): void
+ #[Test]
+ 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());
- $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 () {
@@ -492,11 +504,9 @@ 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.');
-
/**
* Simulates an infinite loop if the zero attempts is not rejected.
*/
@@ -505,7 +515,10 @@ public function testAttemptsMustBeGreaterThanZero(): 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 a7508e89..3c39ab92 100644
--- a/tests/Unit/Bus/PsrPipeContainerTest.php
+++ b/tests/Unit/Bus/PsrPipeContainerTest.php
@@ -12,13 +12,16 @@
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
{
- public function testItResolvesBoundPipes(): void
+ #[Test]
+ public function it_resolves_bound_pipes(): void
{
$a = fn () => 1;
$b = fn () => 2;
@@ -29,33 +32,33 @@ public function testItResolvesBoundPipes(): void
$this->assertSame($a, $container->get('PipeA'));
$this->assertSame($b, $container->get('PipeB'));
+ }
- $this->expectException(\RuntimeException::class);
+ #[Test]
+ public function it_fails_to_resolve_an_unbound_pipe(): void
+ {
+ $container = new PsrPipeContainer();
+ $container->bind('PipeA', fn () => fn () => 1);
+
+ $this->expectException(BusException::class);
$this->expectExceptionMessage('Unrecognised pipe name: PipeC');
$container->get('PipeC');
}
- public function testItFallsBackToPsrContainer(): 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 68ee901c..fb6d6d6b 100644
--- a/tests/Unit/Domain/EntityTest.php
+++ b/tests/Unit/Domain/EntityTest.php
@@ -13,15 +13,15 @@
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;
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,89 +31,53 @@ 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),
- );
-
- $b = new TestEntity(
- $id2 = $this->createMock(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));
}
- public function testItIsNotTheSame(): void
+ #[Test]
+ public function it_is_not_the_same(): void
{
- $a = new TestEntity(
- $id1 = $this->createMock(Identifier::class),
- );
-
- $b = new TestEntity(
- $id2 = $this->createMock(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));
}
- public function testItIsDifferentClass(): void
+ #[Test]
+ public function it_is_different_class(): void
{
- $a = new TestEntity(
- $id1 = $this->createMock(Identifier::class),
- );
-
- $b = $this->createMock(Entity::class);
- $b->method('getId')->willReturn($this->createMock(Identifier::class));
-
- $id1
- ->expects($this->never())
- ->method('is');
+ $a = new TestEntity(new IntegerId(1));
+ $b = $this->createStub(Entity::class);
+ $b->method('getId')->willReturn(new IntegerId(1));
$this->assertFalse($a->is($b));
$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);
-
- $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 63af7236..14ce36bb 100644
--- a/tests/Unit/Domain/EntityWithNullableGuidTest.php
+++ b/tests/Unit/Domain/EntityWithNullableGuidTest.php
@@ -13,15 +13,16 @@
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;
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 +35,8 @@ public function test(): void
$this->assertTrue($entity->hasId());
}
- public function testWithNullId(): TestEntityWithNullableId
+ #[Test]
+ public function it_has_a_null_id(): void
{
$entity = new TestEntityWithNullableId();
@@ -42,122 +44,87 @@ public function testWithNullId(): TestEntityWithNullableId
$this->assertFalse($entity->is(null));
$this->assertTrue($entity->isNot(null));
$this->assertFalse($entity->hasId());
-
- return $entity;
}
- #[Depends('testWithNullId')]
- public function testGetIdOrFailWithoutId(TestEntityWithNullableId $entity): void
- {
- $this->expectException(\AssertionError::class);
- $this->expectExceptionMessage('Entity does not have an identifier.');
-
- $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));
+ $guid = Guid::fromInteger('SomeType', 99);
+
+ $actual = $entity->setId($guid);
$this->assertSame($entity, $actual);
$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));
$this->expectException(ContractException::class);
+ $this->expectExceptionMessage('Cannot set identity as entity already has an identifier.');
+
$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),
- );
-
- $b = new TestEntityWithNullableId(
- $id2 = $this->createMock(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));
}
- public function testItIsNotTheSameWithNullId(): void
+ #[Test]
+ public function it_is_not_the_same_with_null_id(): void
{
$a = new TestEntityWithNullableId();
-
- $b = new TestEntityWithNullableId(
- $id1 = $this->createMock(Identifier::class),
- );
-
- $id1
- ->expects($this->never())
- ->method('is');
+ $b = new TestEntityWithNullableId(new IntegerId(1));
$this->assertFalse($a->is($b));
$this->assertTrue($a->isNot($b));
}
- public function testItIsTheSameWhenOtherHasNullId(): void
+ #[Test]
+ public function it_is_not_the_same_when_other_has_null_id(): void
{
- $a = new TestEntityWithNullableId(
- $id1 = $this->createMock(Identifier::class),
- );
-
+ $a = new TestEntityWithNullableId(new IntegerId(1));
$b = new TestEntityWithNullableId();
- $id1
- ->expects($this->exactly(2))
- ->method('is')
- ->with(null)
- ->willReturn(false);
-
$this->assertFalse($a->is($b));
$this->assertTrue($a->isNot($b));
}
- public function testItIsNotTheSame(): void
+ #[Test]
+ public function it_is_not_the_same_when_both_have_null_ids(): void
{
- $a = new TestEntityWithNullableId(
- $id1 = $this->createMock(Identifier::class),
- );
-
- $b = new TestEntityWithNullableId(
- $id2 = $this->createMock(Identifier::class),
- );
-
- $id1
- ->expects($this->exactly(2))
- ->method('is')
- ->with($this->identicalTo($id2))
- ->willReturn(false);
+ $a = new TestEntityWithNullableId();
+ $b = new TestEntityWithNullableId();
$this->assertFalse($a->is($b));
$this->assertTrue($a->isNot($b));
}
- public function testItIsDifferentClass(): void
+ #[Test]
+ public function it_is_not_the_same(): void
{
- $a = new TestEntityWithNullableId(
- $id1 = $this->createMock(Identifier::class),
- );
+ $a = new TestEntityWithNullableId(new IntegerId(1));
+ $b = new TestEntityWithNullableId(new IntegerId(2));
- $b = $this->createMock(Entity::class);
- $b->method('getId')->willReturn($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_different_class(): void
+ {
+ $a = new TestEntityWithNullableId(new IntegerId(1));
+ $b = $this->createStub(Entity::class);
+ $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 799b409a..c37e1c88 100644
--- a/tests/Unit/Domain/EntityWithTypedIdTest.php
+++ b/tests/Unit/Domain/EntityWithTypedIdTest.php
@@ -13,14 +13,15 @@
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;
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 +32,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 +47,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,36 +57,33 @@ 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);
+ $b = $this->createStub(Entity::class);
$b->method('getId')->willReturn(UuidV7::from($a->id->toString()));
$this->assertFalse($a->is($b));
$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);
-
- $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 1ca11594..3ffe0907 100644
--- a/tests/Unit/Domain/IdentifierOrEntityTest.php
+++ b/tests/Unit/Domain/IdentifierOrEntityTest.php
@@ -13,13 +13,16 @@
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;
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,9 +31,10 @@ 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 = $this->createStub(Entity::class);
$entity->method('getId')->willReturn($guid = Guid::fromInteger('SomeType', 1));
$guidOrEntity = IdentifierOrEntity::make($entity);
@@ -40,17 +44,26 @@ 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 = $this->createStub(Entity::class);
$entity->method('getId')->willReturn(null);
$guidOrEntity = IdentifierOrEntity::make($entity);
$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 9a038cb4..6a68e688 100644
--- a/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php
+++ b/tests/Unit/Infrastructure/ExceptionReporter/PsrLogExceptionReporterTest.php
@@ -14,63 +14,67 @@
use CloudCreativity\Modules\Contracts\Application\Ports\ExceptionReporter;
use CloudCreativity\Modules\Infrastructure\ExceptionReporter\PsrLogExceptionReporter;
+use CloudCreativity\Modules\Testing\FakeLogger;
use LogicException;
-use PHPUnit\Framework\MockObject\MockObject;
+use PHPUnit\Framework\Attributes\Test;
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);
}
protected function tearDown(): void
{
- parent::tearDown();
unset($this->logger, $this->reporter);
+ parent::tearDown();
}
- public function testItReportsException(): void
+ #[Test]
+ public function it_is_an_exception_reporter(): void
{
- $exception = new LogicException('Test exception');
+ $this->assertInstanceOf(ExceptionReporter::class, $this->reporter);
+ }
- $this->logger
- ->expects($this->once())
- ->method('error')
- ->with(
- $exception->getMessage(),
- ['exception' => $exception],
- );
+ #[Test]
+ public function it_reports_exception(): void
+ {
+ $exception = new LogicException('Test 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);
}
- public function testItReportsDefaultMessageIfExceptionHasEmptyMessage(): void
+ #[Test]
+ public function it_reports_default_message_if_exception_has_empty_message(): void
{
$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);
}
- public function testItLogsContextForExceptionThatImplementsContextProvider(): void
+ #[Test]
+ public function it_logs_context_for_exception_that_has_context_method(): void
{
$exception = new class ('Boom!') extends LogicException {
/**
@@ -82,47 +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);
}
- public function testItLogsContextForExceptionThatHasContextMethod(): void
+ #[Test]
+ 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/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/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 c61d0a27..f0f6cf96 100644
--- a/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php
+++ b/tests/Unit/Infrastructure/OutboundEventBus/ClosurePublisherTest.php
@@ -15,6 +15,10 @@
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;
@@ -27,11 +31,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 +46,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);
@@ -63,12 +69,8 @@ public function testWithMiddleware(): 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([
@@ -82,7 +84,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);
@@ -98,12 +101,8 @@ public function testWithMiddlewareViaPsrContainer(): void
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([
@@ -116,8 +115,8 @@ public function testWithMiddlewareViaPsrContainer(): void
$this->assertSame([$event3], $this->actual);
}
-
- 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);
@@ -142,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 bd1082bf..dd31c0e5 100644
--- a/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php
+++ b/tests/Unit/Infrastructure/OutboundEventBus/ComponentPublisherTest.php
@@ -14,107 +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 PHPUnit\Framework\MockObject\MockObject;
+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\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();
}
- public function testPublish(): void
+ #[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));
+ $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 {};
- $handler
- ->expects($this->once())
- ->method('__invoke')
- ->with($this->identicalTo($event));
+ $publisher->publish($event);
- $this->publisher->publish($event);
+ $this->assertSame([$event], $handler->published);
}
- public function testPublishWithMiddleware(): void
+ #[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 67de852b..583c1f1e 100644
--- a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php
+++ b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerContainerTest.php
@@ -12,109 +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
{
- public function testItPublishesViaBindingsWithoutDefaultHandler(): void
+ #[Test]
+ 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($publisher), $actual);
+ }
- $this->assertEquals(new PublisherHandler($a), $container->get($event1::class));
- $this->assertEquals(new PublisherHandler($b), $container->get($event2::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);
- $this->expectException(RuntimeException::class);
- $this->expectExceptionMessage('No handler bound for integration event: ' . $event3::class);
+ $actual = $container->get(TestNamedOutboundEvent::class);
- $container->get($event3::class);
+ $this->assertEquals(new PublisherHandler($default), $actual);
}
- public function testItPublishesViaBindingsWithDefaultHandler(): void
+ #[Test]
+ 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);
}
- public function testItPublishesViaPsrContainerWithoutDefaultHandler(): void
+ #[Test]
+ 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);
+ }
- $this->assertEquals(new PublisherHandler($a), $container->get($event1::class));
- $this->assertEquals(new PublisherHandler($b), $container->get($event2::class));
+ #[Test]
+ public function it_uses_a_closure_default_handler_set_after_construction(): void
+ {
+ $default = new class () extends TestPublisher {};
+ $container = new PublisherHandlerContainer();
- $this->expectException(RuntimeException::class);
- $this->expectExceptionMessage('No handler bound for integration event: ' . $event3::class);
+ $container->withDefault(fn () => $default);
+ $actual = $container->get(TestNamedOutboundEvent::class);
- $container->get($event3::class);
+ $this->assertEquals(new PublisherHandler($default), $actual);
}
- public function testItPublishesViaPsrContainerWithDefaultHandler(): void
+ #[Test]
+ public function it_uses_a_psr_container_default_handler_set_after_construction(): void
{
- $a = new class () extends TestPublisher {};
- $b = $this->createStub(TestPublisher::class);
+ $default = new class () extends TestPublisher {};
+ $psrContainer = new FakeContainer();
+ $psrContainer->instance(TestPublisher::class, $default);
+ $container = new PublisherHandlerContainer(container: $psrContainer);
- $event1 = new class () extends TestOutboundEvent {};
- $event2 = new class () extends TestOutboundEvent {};
- $event3 = new class () extends TestOutboundEvent {};
+ $container->withDefault(TestPublisher::class);
+ $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($default), $actual);
+ }
+
+ #[Test]
+ public function it_prefers_a_binding_over_a_default_handler_set_after_construction(): void
+ {
+ $bound = new class () extends TestPublisher {};
+ $default = new class () extends TestPublisher {};
+ $container = new PublisherHandlerContainer();
+ $container->bind(TestNamedOutboundEvent::class, fn () => $bound);
+
+ $container->withDefault(fn () => $default);
+ $actual = $container->get(TestNamedOutboundEvent::class);
+
+ $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 2d205878..fed11041 100644
--- a/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php
+++ b/tests/Unit/Infrastructure/OutboundEventBus/PublisherHandlerTest.php
@@ -14,23 +14,38 @@
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_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 @@
+
*/
private array $actual = [];
- private ClosureQueue $queue;
-
- 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 {};
- }
-
protected function tearDown(): void
{
+ unset($this->actual);
parent::tearDown();
- unset($this->queue, $this->middleware, $this->actual);
}
- public function test(): void
+ #[Test]
+ public function it_queues_a_command(): void
{
- $command = $this->createMock(Command::class);
+ $command = $this->createStub(Command::class);
+ $queue = $this->createQueue();
- $this->queue->push($command);
+ $queue->push($command);
$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);
- $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);
@@ -79,44 +68,77 @@ public function testWithMiddleware(): void
return $next($command4);
};
- $this->middleware
- ->expects($this->once())
- ->method('get')
- ->with('MySecondMiddleware')
- ->willReturn($middleware2);
+ $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);
}
-
- 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);
+ $stub = $this->createStub(Command::class);
$actual = null;
+ $queue = $this->createQueue();
- $this->queue->bind($mock::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);
}
+
+ #[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 {
+ $this->actual[] = $command;
+ },
+ $middleware,
+ ) extends ClosureQueue {};
+ }
}
diff --git a/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php b/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php
index 88be9225..98d41d77 100644
--- a/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php
+++ b/tests/Unit/Infrastructure/Queue/ComponentQueueTest.php
@@ -13,104 +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 PHPUnit\Framework\MockObject\MockObject;
+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\TestCase;
final class ComponentQueueTest extends TestCase
{
- private EnqueuerContainer&MockObject $enqueuers;
-
- private MockObject&PipeContainer $middleware;
-
- 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->middleware = $this->createMock(PipeContainer::class),
- ) extends ComponentQueue {};
- }
-
protected function tearDown(): void
{
- unset($this->queue, $this->enqueuers, $this->middleware, $this->sequence);
+ unset($this->sequence);
parent::tearDown();
}
- public function test(): void
+ #[Test]
+ public function it_queues_a_command(): void
{
- $command = $this->createMock(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);
}
- public function testItQueuesThroughMiddleware(): void
+ #[Test]
+ public function it_queues_through_middleware(): void
{
- $command1 = $this->createMock(Command::class);
- $command2 = $this->createMock(Command::class);
- $command3 = $this->createMock(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));
- $this->middleware
- ->expects($this->once())
- ->method('get')
- ->with('MySecondMiddleware')
- ->willReturn($middleware2);
+ $queue->push($command);
+ }
+
+ 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 05333953..8eaaca10 100644
--- a/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php
+++ b/tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php
@@ -13,58 +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
{
- public function testItUsesBindings(): void
+ /**
+ * @return array}>
+ */
+ public static function multipleCommandsProvider(): array
{
- $command1 = new class () implements Command {};
- $command2 = new class () implements Command {};
+ return [
+ 'first command' => [TestCommand::class],
+ 'second command' => [TestQueueableCommand::class],
+ ];
+ }
+
+ #[Test]
+ public function it_gets_an_enqueuer_bound_with_a_closure(): void
+ {
+ $enqueuer = new class () extends TestEnqueuer {};
+ $container = new EnqueuerContainer();
+ $container->bind(TestQueueableCommand::class, fn () => $enqueuer);
+
+ $actual = $container->get(TestQueueableCommand::class);
- $a = new class () extends TestEnqueuer {};
- $b = $this->createStub(TestEnqueuer::class);
- $default = $this->createStub(TestEnqueuer::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);
}
- public function testItUsesPsrContainer(): void
+ #[Test]
+ public function it_throws_when_the_default_enqueuer_is_a_string_without_a_psr_container(): void
{
- $command1 = new class () implements Command {};
- $command2 = new class () implements Command {};
+ $this->expectException(InfrastructureException::class);
+ $this->expectExceptionMessage('Cannot bind default enqueuer as a string without a PSR container.');
- $a = new class () extends TestEnqueuer {};
- $b = $this->createStub(TestEnqueuer::class);
- $default = $this->createStub(TestEnqueuer::class);
+ new EnqueuerContainer(default: TestEnqueuer::class);
+ }
+
+ #[Test]
+ 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);
+ }
- $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),
- });
+ #[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();
- $container = new EnqueuerContainer(default: $default::class, container: $psrContainer);
- $container->bind($command1::class, $a::class);
- $container->bind($command2::class, $b::class);
+ $this->expectException(InfrastructureException::class);
+ $this->expectExceptionMessage('Cannot bind default enqueuer as a string without a PSR container.');
- $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));
+ $container->withDefault(TestEnqueuer::class);
}
}
diff --git a/tests/Unit/Infrastructure/Queue/EnqueuerTest.php b/tests/Unit/Infrastructure/Queue/EnqueuerTest.php
index c7f24221..7dee31d4 100644
--- a/tests/Unit/Infrastructure/Queue/EnqueuerTest.php
+++ b/tests/Unit/Infrastructure/Queue/EnqueuerTest.php
@@ -14,21 +14,30 @@
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);
-
- $innerEnqueuer
- ->expects($this->once())
- ->method('push')
- ->with($this->identicalTo($command));
+ $command = $this->createStub(Command::class);
+ $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 46752b62..d345ebde 100644
--- a/tests/Unit/Testing/FakeDomainEventDispatcherTest.php
+++ b/tests/Unit/Testing/FakeDomainEventDispatcherTest.php
@@ -16,62 +16,167 @@
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
+ 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_dispatches_events(): void
+ {
+ $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
{
- $dispatcher = new class () extends FakeDomainEventDispatcher {};
-
- $event1 = $this->createMock(DomainEvent::class);
- $event2 = $this->createMock(DomainEvent::class);
-
- $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]);
+ $event1 = $this->createStub(DomainEvent::class);
+ $event2 = $this->createStub(DomainEvent::class);
+ $this->dispatcher->events = [$event1, $event2];
+
+ $actual = iterator_to_array($this->dispatcher);
+
+ $this->assertSame([$event1, $event2], $actual);
}
- public function testItReturnsSoleEvent(): void
+ // -------------------------------------------------------------------------
+ // ArrayAccess
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_gets_an_event_by_offset(): void
{
- $dispatcher = new class () extends FakeDomainEventDispatcher {};
- $event = $this->createMock(DomainEvent::class);
+ $event1 = $this->createStub(DomainEvent::class);
+ $event2 = $this->createStub(DomainEvent::class);
+ $this->dispatcher->events = [$event1, $event2];
- $dispatcher->dispatch($event);
+ $actual = [$this->dispatcher[0], $this->dispatcher[1]];
- $this->assertSame($event, $dispatcher->sole());
+ $this->assertSame([$event1, $event2], $actual);
}
- public function testItThrowsExceptionIfNoEvents(): void
+ #[Test]
+ public function it_checks_whether_an_offset_exists(): void
{
- $dispatcher = new class () extends FakeDomainEventDispatcher {};
+ $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('Expected one event to be dispatched but there are 0 events.');
+ $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)];
- $dispatcher->sole();
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Cannot unset domain events.');
+
+ unset($this->dispatcher[0]);
}
- public function testItThrowsExceptionIfMultipleEvents(): void
+ // -------------------------------------------------------------------------
+ // sole()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_returns_sole_event(): void
{
- $dispatcher = new class () extends FakeDomainEventDispatcher {};
- $event1 = $this->createMock(DomainEvent::class);
- $event2 = $this->createMock(DomainEvent::class);
+ $event = $this->createStub(DomainEvent::class);
+ $this->dispatcher->events = [$event];
+
+ $actual = $this->dispatcher->sole();
- $dispatcher->dispatch($event1);
- $dispatcher->dispatch($event2);
+ $this->assertSame($event, $actual);
+ }
+
+ #[Test]
+ public function it_throws_exception_if_no_events(): void
+ {
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Expected one event to be dispatched but there are 0 events.');
+
+ $this->dispatcher->sole();
+ }
+
+ #[Test]
+ public function it_throws_exception_if_multiple_events(): void
+ {
+ $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 5f872f01..5d3f2cd6 100644
--- a/tests/Unit/Testing/FakeExceptionReporterTest.php
+++ b/tests/Unit/Testing/FakeExceptionReporterTest.php
@@ -15,78 +15,212 @@
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
+ private FakeExceptionReporter $reporter;
+
+ protected function setUp(): void
{
- $reporter = new FakeExceptionReporter();
- $reporter->report($ex1 = new RuntimeException('Whoops!'));
- $reporter->report($ex2 = new RuntimeException('Whoops again!'));
+ parent::setUp();
+ $this->reporter = new FakeExceptionReporter();
+ }
- $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]);
+ protected function tearDown(): void
+ {
+ unset($this->reporter);
+ parent::tearDown();
}
- public function testItDoesNotExpectExceptions(): void
+ #[Test]
+ public function it_is_an_exception_reporter(): void
{
- $expected = new RuntimeException('Boom! That was a surprise.');
+ $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
+ {
+ $ex1 = new RuntimeException('Whoops!');
+ $ex2 = new RuntimeException('Whoops again!');
+
+ $this->reporter->report($ex1);
+ $this->reporter->report($ex2);
+
+ $this->assertSame([$ex1, $ex2], $this->reporter->reported);
+ }
+
+ // -------------------------------------------------------------------------
+ // none() and expect()
+ // -------------------------------------------------------------------------
- $reporter = new FakeExceptionReporter();
- $reporter->none();
+ #[Test]
+ public function it_does_not_expect_exceptions(): void
+ {
+ $expected = new RuntimeException('Boom! That was a surprise.');
+ $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);
}
- public function testItExpectsExceptions(): void
+ #[Test]
+ 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!'),
+ ];
- for ($i = 0; $i < 3; $i++) {
- $reporter->report(new LogicException("Whoops {$i}!"));
- }
+ $actual = count($this->reporter);
- $this->assertCount(3, $reporter);
- $reporter->report($expected);
+ $this->assertSame(2, $actual);
}
- public function testItHasSoleException(): void
+ #[Test]
+ public function it_iterates_over_the_reported_exceptions(): void
{
- $reporter = new FakeExceptionReporter();
- $reporter->report($ex = new RuntimeException('Whoops!'));
+ $ex1 = new RuntimeException('Whoops!');
+ $ex2 = new RuntimeException('Whoops again!');
+ $this->reporter->reported = [$ex1, $ex2];
- $this->assertSame($ex, $reporter->sole());
+ $actual = iterator_to_array($this->reporter);
+
+ $this->assertSame([$ex1, $ex2], $actual);
}
- public function testItFailsWhenThereIsNoSoleException(): void
+ // -------------------------------------------------------------------------
+ // ArrayAccess
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_gets_an_exception_by_offset(): void
{
- $this->expectExceptionMessage('Expected one exception to be reported but there are 0 exceptions.');
+ $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);
+ }
+
+ #[Test]
+ public function it_cannot_set_an_offset(): void
+ {
+ $ex = new RuntimeException('Whoops!');
+
$this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Cannot set reported exceptions.');
- $reporter = new FakeExceptionReporter();
- $reporter->sole();
+ $this->reporter[0] = $ex;
}
- public function testItFailsWhenThereIsMoreThanOneSoleException(): void
+ #[Test]
+ public function it_cannot_unset_an_offset(): void
{
- $this->expectExceptionMessage('Expected one exception to be reported but there are 2 exceptions.');
+ $this->reporter->reported = [new RuntimeException('Whoops!')];
+
$this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Cannot unset reported exceptions.');
+
+ unset($this->reporter[0]);
+ }
+
+ // -------------------------------------------------------------------------
+ // sole()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_has_sole_exception(): void
+ {
+ $ex = new RuntimeException('Whoops!');
+ $this->reporter->reported = [$ex];
+
+ $actual = $this->reporter->sole();
+
+ $this->assertSame($ex, $actual);
+ }
+
+ #[Test]
+ public function it_fails_when_there_is_no_sole_exception(): void
+ {
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Expected one exception to be reported but there are 0 exceptions.');
+
+ $this->reporter->sole();
+ }
+
+ #[Test]
+ public function it_fails_when_there_is_more_than_one_sole_exception(): void
+ {
+ $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 6c2def8a..03a9c021 100644
--- a/tests/Unit/Testing/FakeOutboundEventPublisherTest.php
+++ b/tests/Unit/Testing/FakeOutboundEventPublisherTest.php
@@ -16,60 +16,167 @@
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
+ private FakeOutboundEventPublisher $publisher;
+
+ protected function setUp(): void
{
- $publisher = new class () extends FakeOutboundEventPublisher {};
+ parent::setUp();
+ $this->publisher = new class () extends FakeOutboundEventPublisher {};
+ }
- $event1 = $this->createMock(IntegrationEvent::class);
- $event2 = $this->createMock(IntegrationEvent::class);
+ protected function tearDown(): void
+ {
+ unset($this->publisher);
+ parent::tearDown();
+ }
- $publisher->publish($event1);
- $publisher->publish($event2);
+ #[Test]
+ public function it_is_an_outbound_event_publisher(): void
+ {
+ $this->assertInstanceOf(OutboundEventPublisher::class, $this->publisher);
+ }
- $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]);
+ #[Test]
+ public function it_is_empty_by_default(): void
+ {
+ $actual = [count($this->publisher), iterator_to_array($this->publisher)];
+
+ $this->assertSame([0, []], $actual);
}
- public function testItReturnsSoleEvent(): void
+ // -------------------------------------------------------------------------
+ // publish()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_publishes_events(): void
{
- $publisher = new class () extends FakeOutboundEventPublisher {};
- $event = $this->createMock(IntegrationEvent::class);
+ $event1 = $this->createStub(IntegrationEvent::class);
+ $event2 = $this->createStub(IntegrationEvent::class);
- $publisher->publish($event);
+ $this->publisher->publish($event1);
+ $this->publisher->publish($event2);
- $this->assertSame($event, $publisher->sole());
+ $this->assertSame([$event1, $event2], $this->publisher->events);
}
- public function testItThrowsExceptionIfNoEvents(): void
+ // -------------------------------------------------------------------------
+ // count() and getIterator()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_counts_the_published_events(): void
{
- $publisher = new class () extends FakeOutboundEventPublisher {};
+ $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];
+
+ $actual = [$this->publisher[0], $this->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('Expected one event to be published but there are 0 events.');
+ $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
+ {
+ $event = $this->createStub(IntegrationEvent::class);
+ $this->publisher->events = [$event];
- $publisher->sole();
+ $actual = $this->publisher->sole();
+
+ $this->assertSame($event, $actual);
}
- public function testItThrowsExceptionIfMultipleEvents(): void
+ #[Test]
+ public function it_throws_exception_if_no_events(): void
{
- $publisher = new class () extends FakeOutboundEventPublisher {};
- $event1 = $this->createMock(IntegrationEvent::class);
- $event2 = $this->createMock(IntegrationEvent::class);
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Expected one event to be published but there are 0 events.');
- $publisher->publish($event1);
- $publisher->publish($event2);
+ $this->publisher->sole();
+ }
+
+ #[Test]
+ public function it_throws_exception_if_multiple_events(): void
+ {
+ $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 65ebd497..6de20421 100644
--- a/tests/Unit/Testing/FakeQueueTest.php
+++ b/tests/Unit/Testing/FakeQueueTest.php
@@ -16,49 +16,167 @@
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
+ private FakeQueue $queue;
+
+ protected function setUp(): void
{
- $queue = new class () extends FakeQueue {};
- $queue->push($command1 = $this->createMock(Command::class));
- $queue->push($command2 = $this->createMock(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]);
+ parent::setUp();
+ $this->queue = new class () extends FakeQueue {};
}
- public function testItHasSoleCommand(): void
+ protected function tearDown(): void
{
- $queue = new class () extends FakeQueue {};
- $queue->push($command = $this->createMock(Command::class));
+ unset($this->queue);
+ parent::tearDown();
+ }
- $this->assertSame($command, $queue->sole());
+ #[Test]
+ public function it_is_a_queue(): void
+ {
+ $this->assertInstanceOf(Queue::class, $this->queue);
}
- public function testItFailsWhenThereIsNoSoleCommand(): void
+ #[Test]
+ public function it_is_empty_by_default(): void
{
- $this->expectExceptionMessage('Expected one command in the queue but there are 0 commands.');
+ $actual = [count($this->queue), iterator_to_array($this->queue)];
+
+ $this->assertSame([0, []], $actual);
+ }
+
+ // -------------------------------------------------------------------------
+ // push()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_queues_commands(): void
+ {
+ $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.');
- $queue = new class () extends FakeQueue {};
- $queue->sole();
+ $this->queue[0] = $command;
}
- public function testItFailsWhenThereIsMoreThanOneSoleCommand(): void
+ #[Test]
+ public function it_cannot_unset_an_offset(): void
{
- $this->expectExceptionMessage('Expected one command in the queue but there are 2 commands.');
+ $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
+ {
+ $command = $this->createStub(Command::class);
+ $this->queue->commands = [$command];
+
+ $actual = $this->queue->sole();
+
+ $this->assertSame($command, $actual);
+ }
+
+ #[Test]
+ public function it_fails_when_there_is_no_sole_command(): void
+ {
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Expected one command in the queue but there are 0 commands.');
+
+ $this->queue->sole();
+ }
+
+ #[Test]
+ public function it_fails_when_there_is_more_than_one_sole_command(): void
+ {
+ $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->createMock(Command::class));
- $queue->push($this->createMock(Command::class));
- $queue->sole();
+ $this->queue->sole();
}
}
diff --git a/tests/Unit/Testing/FakeUnitOfWorkTest.php b/tests/Unit/Testing/FakeUnitOfWorkTest.php
index fbd11fe8..f6f1636e 100644
--- a/tests/Unit/Testing/FakeUnitOfWorkTest.php
+++ b/tests/Unit/Testing/FakeUnitOfWorkTest.php
@@ -12,43 +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
{
- public function testItIsSuccessfulOnFirstAttempt(): void
+ #[Test]
+ public function it_is_a_unit_of_work(): void
{
$unitOfWork = new FakeUnitOfWork();
- $result = $unitOfWork->execute(fn () => 'result');
$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->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);
}
- public function testItIsSuccessfulBeforeMaxAttempts(): void
+ /**
+ * @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_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',
@@ -58,68 +95,124 @@ public function testItIsSuccessfulBeforeMaxAttempts(): 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);
}
- public function testItIsSuccessfulOnMaxAttempts(): void
+ #[Test]
+ 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);
}
- public function testItIsNotSuccessful(): void
+ #[Test]
+ 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 2849b656..c2a08d12 100644
--- a/tests/Unit/Toolkit/ContractsTest.php
+++ b/tests/Unit/Toolkit/ContractsTest.php
@@ -14,29 +14,32 @@
use CloudCreativity\Modules\Toolkit\ContractException;
use CloudCreativity\Modules\Toolkit\Contracts;
+use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
+use ReflectionClass;
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.');
+ $this->expectNotToPerformAssertions();
/** @phpstan-ignore-next-line */
- $this->assertTrue(true);
+ Contracts::assert(true, 'Not expected error.');
}
- 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.'));
+ $this->expectNotToPerformAssertions();
/** @phpstan-ignore-next-line */
- $this->assertTrue(true);
+ Contracts::assert(true, fn () => $this->fail('Not expected error.'));
}
- 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 +48,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.');
@@ -53,4 +57,22 @@ public function testItThrowsWhenPreconditionIsFalseWithLazyMessage(): 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/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..a622d12a 100644
--- a/tests/Unit/Toolkit/Identifiers/GuidTest.php
+++ b/tests/Unit/Toolkit/Identifiers/GuidTest.php
@@ -23,15 +23,21 @@
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;
+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
{
@@ -52,87 +58,121 @@ public static function typeProvider(): array
];
}
- /**
- * @param string|TestUnitEnum $type
- * @param string|TestUnitEnum $other
- */
+ // -------------------------------------------------------------------------
+ // Creation
+ // -------------------------------------------------------------------------
+
#[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,
+ string $otherValue,
+ ): 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')]
- 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,
+ string $otherValue,
+ ): void {
$guid = Guid::fromInteger($type, 123);
$this->assertSame($type, $guid->type);
$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')]
- public function testUuid(string|UnitEnum $type, string $value, string|UnitEnum $other): void
- {
- $uuid = Uuid::random();
+ #[Test]
+ public function it_can_be_created_from_a_base_uuid(
+ string|UnitEnum $type,
+ string $value,
+ string|UnitEnum $other,
+ string $otherValue,
+ ): void {
+ $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
*/
@@ -150,78 +190,327 @@ 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->assertSame('SomeType', $guid->type);
$this->assertTrue($expected->is($guid->id));
- $this->assertSame($guid, Guid::from($guid));
- $this->assertSame($guid, Guid::tryFrom($guid));
}
- public function testFromWithNull(): void
+ // -------------------------------------------------------------------------
+ // from() and tryFrom()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ 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);
}
- public function testEmptyType(): void
+ #[Test]
+ 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);
}
- public function testEmptyStringId(): void
+ /**
+ * @return array
+ */
+ public static function notGuidProvider(): array
{
- $this->expectException(ContractException::class);
- Guid::fromString('SomeType', '');
+ return [
+ 'null' => [null],
+ 'integer id' => [new IntegerId(1)],
+ 'string id' => [new StringId('SomeType:1')],
+ 'uuid' => [new Uuid(BaseUuid::fromString(self::UUID))],
+ ];
}
- public function testNegativeIntegerId(): void
+ #[DataProvider('notGuidProvider')]
+ #[Test]
+ public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void
{
$this->expectException(ContractException::class);
- Guid::fromInteger('SomeType', -1);
+ $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other));
+
+ Guid::from($other);
+ }
+
+ #[DataProvider('notGuidProvider')]
+ #[Test]
+ public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void
+ {
+ $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_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);
}
- public function testFromInteger(): void
+ #[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);
}
- public function testFromString(): void
+ #[DataProvider('notGuidProvider')]
+ #[Test]
+ 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')]
- public function testIsTypeWithMultipleTypes(string|UnitEnum $type, string $value, string|UnitEnum $other): void
- {
+ #[Test]
+ 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,
+ string $otherValue,
+ ): 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')]
- public function testAssertTypeDoesNotThrowForExpectedType(string|UnitEnum $type): void
- {
+ #[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')]
+ #[Test]
+ 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);
+
$this->assertSame($guid, $actual);
}
#[DataProvider('typeProvider')]
- public function testAssertTypeDoesThrowForUnexpectedType(
+ #[Test]
+ public function it_throws_when_asserting_an_unexpected_type(
string|UnitEnum $type,
string $value,
string|UnitEnum $other,
string $otherValue,
): void {
+ $guid = Guid::fromInteger($type, 1);
+
$this->expectException(ContractException::class);
$this->expectExceptionMessage(sprintf(
'Expecting type "%s", received "%s".',
@@ -229,6 +518,51 @@ public function testAssertTypeDoesThrowForUnexpectedType(
$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 f4177698..254049af 100644
--- a/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php
+++ b/tests/Unit/Toolkit/Identifiers/GuidTypeMapTest.php
@@ -12,93 +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
{
- public function testItReturnsExpectedType(): GuidTypeMap
+ 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(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('testItReturnsExpectedType')]
- public function testItReturnsExpectedGuid(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('testItReturnsExpectedType')]
- public function testItThrowsIfTypeIsNotValidString(GuidTypeMap $map): void
+ #[DataProvider('stringGuidProvider')]
+ #[Test]
+ 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',
+ ]);
+
+ $actual = $map->guidFor($alias, $id);
+
+ $this->assertObjectEquals($expected, $actual);
+ }
- $map->typeFor('NotString');
+ /**
+ * @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],
+ ];
}
- #[Depends('testItReturnsExpectedType')]
- public function testItThrowsIfTypeIsEmptyString(GuidTypeMap $map): void
+ #[DataProvider('enumTypeProvider')]
+ #[Test]
+ 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('testItReturnsExpectedType')]
- public function testItThrowsIfTypeIsNotDefined(GuidTypeMap $map): void
+ #[DataProvider('enumTypeProvider')]
+ #[Test]
+ 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'],
+ ];
}
- public function testItReturnsExpectedTypeWithEnums(): void
+ #[DataProvider('defineProvider')]
+ #[Test]
+ 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 45f9581a..cd98f47e 100644
--- a/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php
+++ b/tests/Unit/Toolkit/Identifiers/IntegerIdTest.php
@@ -18,13 +18,15 @@
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
{
- public function test(): void
+ #[Test]
+ public function it_wraps_an_integer(): void
{
$id = new IntegerId(99);
@@ -39,72 +41,177 @@ 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
+ // -------------------------------------------------------------------------
+ // from() and tryFrom()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_is_created_from_an_integer(): void
+ {
+ $actual = IntegerId::from(99);
+
+ $this->assertObjectEquals(new IntegerId(99), $actual);
+ }
+
+ #[Test]
+ public function it_returns_the_same_instance_when_created_from_an_integer_id(): void
+ {
+ $id = new IntegerId(99);
+
+ $actual = IntegerId::from($id);
+
+ $this->assertSame($id, $actual);
+ }
+
+ #[Test]
+ public function it_tries_to_create_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::tryFrom(99);
+
+ $this->assertNotNull($actual);
+ $this->assertObjectEquals(new IntegerId(99), $actual);
}
- public function testItIsNotEqual(): void
+ #[Test]
+ public function it_returns_the_same_instance_when_trying_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::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')]
- public function testIsWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ 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')]
- 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));
+ $actual = IntegerId::tryFrom($other);
+
+ $this->assertNull($actual);
}
- public function testIsWithNull(): void
+ // -------------------------------------------------------------------------
+ // 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_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')]
- public function testFromWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ 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 4e96faa6..965ac52a 100644
--- a/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php
+++ b/tests/Unit/Toolkit/Identifiers/PossiblyNumericIdTest.php
@@ -16,39 +16,65 @@
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
{
/**
- * @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 '],
];
}
#[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);
$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 8e4f453f..0b9ca147 100644
--- a/tests/Unit/Toolkit/Identifiers/StringIdTest.php
+++ b/tests/Unit/Toolkit/Identifiers/StringIdTest.php
@@ -19,11 +19,14 @@
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;
final class StringIdTest extends TestCase
{
- public function test(): void
+ #[Test]
+ public function it_wraps_a_string(): void
{
$id = new StringId('99');
@@ -38,71 +41,185 @@ 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
+ // -------------------------------------------------------------------------
+ // from() and tryFrom()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ 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);
}
- public function testItIsNotEqual(): void
+ #[Test]
+ 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')]
- public function testIsWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ 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')]
- public function testTryFromWithInvalid(?Identifier $other): void
+ #[Test]
+ public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void
+ {
+ $actual = StringId::tryFrom($other);
+
+ $this->assertNull($actual);
+ }
+
+ // -------------------------------------------------------------------------
+ // is(), any() and equals()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_equals_a_string_id_with_the_same_value(): void
{
- $this->assertNull(StringId::tryFrom($other));
+ $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')]
- public function testFromWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ 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 @@
+factory, $this->baseFactory);
+ parent::tearDown();
+ }
+
+ #[Test]
+ public function it_wraps_a_base_uuid(): void
+ {
+ $base = BaseUuid::uuid4();
+
$this->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);
}
- public function testFromWithUuid(): 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);
}
- public function testFromWithIdentifierInterface(): 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->createMock(Identifier::class),
- );
+ $this->factory->from($id);
}
- public function testFromBytes(): void
+ #[Test]
+ public function it_creates_from_bytes(): void
{
$this->baseFactory
->expects($this->once())
@@ -89,10 +105,11 @@ public function testFromBytes(): void
$uuid = $this->factory->fromBytes($bytes);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testFromDateTime(): void
+ #[Test]
+ public function it_creates_from_a_date_time(): void
{
$this->baseFactory
->expects($this->once())
@@ -107,10 +124,11 @@ public function testFromDateTime(): void
$uuid = $this->factory->fromDateTime($dateTime, $hex, $int);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testFromInteger(): void
+ #[Test]
+ public function it_creates_from_an_integer(): void
{
$this->baseFactory
->expects($this->once())
@@ -121,10 +139,11 @@ public function testFromInteger(): void
$uuid = $this->factory->fromInteger($integer);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testFromString(): void
+ #[Test]
+ public function it_creates_from_a_string(): void
{
$this->baseFactory
->expects($this->once())
@@ -135,10 +154,11 @@ public function testFromString(): void
$uuid = $this->factory->fromString($string);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testUuid1(): void
+ #[Test]
+ public function it_creates_a_uuid_v1(): void
{
$this->baseFactory
->expects($this->once())
@@ -152,10 +172,11 @@ public function testUuid1(): void
$uuid = $this->factory->uuid1($hex, $int);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testUuid2(): void
+ #[Test]
+ public function it_creates_a_uuid_v2(): void
{
$this->baseFactory
->expects($this->once())
@@ -171,10 +192,11 @@ public function testUuid2(): void
$uuid = $this->factory->uuid2($int, $integer, $hex, $seq);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testUuid3(): void
+ #[Test]
+ public function it_creates_a_uuid_v3(): void
{
$this->baseFactory
->expects($this->once())
@@ -188,10 +210,11 @@ public function testUuid3(): void
$uuid = $this->factory->uuid3($ns, $name);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testUuid4(): void
+ #[Test]
+ public function it_creates_a_uuid_v4(): void
{
$this->baseFactory
->expects($this->once())
@@ -201,10 +224,11 @@ public function testUuid4(): void
$uuid = $this->factory->uuid4();
$this->assertInstanceOf(UuidV4::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testUuid5(): void
+ #[Test]
+ public function it_creates_a_uuid_v5(): void
{
$this->baseFactory
->expects($this->once())
@@ -218,10 +242,11 @@ public function testUuid5(): void
$uuid = $this->factory->uuid5($ns, $name);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testUuid6(): void
+ #[Test]
+ public function it_creates_a_uuid_v6(): void
{
$this->baseFactory
->expects($this->once())
@@ -235,12 +260,13 @@ public function testUuid6(): void
$uuid = $this->factory->uuid6($hex, $int);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testUuid7(): void
+ #[Test]
+ public function it_creates_a_uuid_v7(): void
{
- $date = new \DateTimeImmutable();
+ $date = new DateTimeImmutable();
$this->baseFactory
->expects($this->once())
@@ -251,22 +277,28 @@ public function testUuid7(): void
$uuid = $this->factory->uuid7($date);
$this->assertInstanceOf(UuidV7::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testUuid7NotSupported(): void
+ #[Test]
+ public function it_throws_if_uuid_v7_is_not_supported(): void
{
$factory = new UuidFactory(
- $this->createMock(BaseUuidFactoryInterface::class),
+ $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.');
$factory->uuid7();
}
- public function testUuid8(): void
+ #[Test]
+ public function it_creates_a_uuid_v8(): void
{
$bytes = 'blah!';
@@ -279,15 +311,20 @@ public function testUuid8(): void
$uuid = $this->factory->uuid8($bytes);
$this->assertInstanceOf(Uuid::class, $uuid);
- $this->assertSame($uuid->value, $base);
+ $this->assertSame($base, $uuid->value);
}
- public function testUuid8NotSupported(): void
+ #[Test]
+ public function it_throws_if_uuid_v8_is_not_supported(): void
{
$factory = new UuidFactory(
- $this->createMock(BaseUuidFactoryInterface::class),
+ $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 935bc396..2e998d6b 100644
--- a/tests/Unit/Toolkit/Identifiers/UuidTest.php
+++ b/tests/Unit/Toolkit/Identifiers/UuidTest.php
@@ -19,21 +19,30 @@
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;
use Ramsey\Uuid\Uuid as RamseyUuid;
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
{
- 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);
$this->assertSame($base, $id->value);
@@ -48,138 +57,365 @@ public function test(): void
);
}
- public function testItIsEquals(): void
+ #[Test]
+ 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));
}
- public function testItIsNotEqual(): void
+ #[Test]
+ 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')]
- public function testIsWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ 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());
+
+ $actual = Uuid::tryFrom($id);
- $this->assertFalse($id->is($other));
- $this->assertFalse($id->any(null, Uuid::random(), $other));
- $this->assertFalse($id->any());
+ $this->assertSame($id, $actual);
}
- #[DataProvider('notUuidProvider')]
- public function testFromWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ 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')]
- public function testTryFromWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ 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);
}
- public function testFromWithString(): void
+ #[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);
+
+ $actual = Uuid::from('blah!');
- $this->assertSame($expected, Uuid::from($str));
+ $this->assertSame($expected, $actual);
}
- public function testTryFromWithString(): void
+ #[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);
+ }
+
+ #[Test]
+ public function it_returns_null_when_trying_from_an_invalid_string(): void
+ {
+ $factory = $this->createMock(UuidFactory::class);
+ Uuid::setFactory($factory);
- $this->assertSame($expected, Uuid::tryFrom($valid));
- $this->assertNull(Uuid::tryFrom('invalid'));
+ $factory
+ ->expects($this->never())
+ ->method($this->anything());
+
+ $actual = Uuid::tryFrom('invalid');
+
+ $this->assertNull($actual);
}
- public function testFromAndTryFromWithBaseUuid(): void
+ #[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);
}
- public function testTryFromWithNull(): void
+ #[Test]
+ public function it_can_try_to_create_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->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
+ {
+ $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);
}
- public function testNil(): void
+ /**
+ * @return array
+ */
+ public static function notUuidProvider(): array
{
- $base = RamseyUuid::fromString(RamseyUuid::NIL);
- $actual = Uuid::nil();
+ return [
+ 'null' => [null],
+ 'integer id' => [new IntegerId(1)],
+ 'string id' => [new StringId('foo')],
+ 'guid' => [new Guid('SomeType', new Uuid(RamseyUuid::fromString(self::UUID)))],
+ ];
+ }
- $this->assertTrue($actual->toBase()->equals($base));
+ #[DataProvider('notUuidProvider')]
+ #[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));
+
+ Uuid::from($other);
}
- public function testCompareTo(): void
+ #[DataProvider('notUuidProvider')]
+ #[Test]
+ 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 bf6d60c5..30b0fe02 100644
--- a/tests/Unit/Toolkit/Identifiers/UuidV4Test.php
+++ b/tests/Unit/Toolkit/Identifiers/UuidV4Test.php
@@ -21,14 +21,22 @@
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\Lazy\LazyUuidFromString;
use Ramsey\Uuid\Uuid as RamseyUuid;
final class UuidV4Test extends TestCase
{
- public function test(): void
+ 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);
@@ -43,102 +51,240 @@ public function test(): void
);
}
- public function testItIsEquals(): void
+ #[Test]
+ 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);
}
- public function testItIsNotEqual(): void
+ #[Test]
+ 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);
+ }
+
+ #[Test]
+ public function it_can_try_to_create_from_a_string(): void
+ {
+ $expected = UuidV4::from(RamseyUuid::fromString(self::UUID));
+
+ $actual = UuidV4::tryFrom(self::UUID);
+
+ $this->assertNotNull($actual);
+ $this->assertObjectEquals($expected, $actual);
+ }
+
+ #[Test]
+ public function it_returns_null_when_trying_from_an_invalid_string(): void
+ {
+ $actual = UuidV4::tryFrom('invalid');
+
+ $this->assertNull($actual);
}
/**
- * @return array
+ * @return array
*/
public static function notUuidV4Provider(): array
{
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()],
+ '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')]
- public function testIsWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void
{
- $id = UuidV4::from(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816'));
+ $this->expectException(ContractException::class);
+ $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other));
- $this->assertFalse($id->is($other));
- $this->assertFalse($id->any(null, UuidV4::make(), $other));
- $this->assertFalse($id->any());
+ UuidV4::from($other);
}
#[DataProvider('notUuidV4Provider')]
- public function testFromWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void
{
- $this->expectException(ContractException::class);
- $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other));
- UuidV4::from($other);
+ $actual = UuidV4::tryFrom($other);
+
+ $this->assertNull($actual);
}
- #[DataProvider('notUuidV4Provider')]
- public function testTryFromWithOtherIdentifiers(?Identifier $other): void
+ // -------------------------------------------------------------------------
+ // is(), any() and equals()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_equals_a_uuid_with_the_same_value(): void
{
- $this->assertNull(UuidV4::tryFrom($other));
+ $id = UuidV4::from(self::UUID);
+
+ $this->assertObjectEquals(UuidV4::from(self::UUID), $id);
}
- public function testFromWithString(): void
+ #[Test]
+ 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::from($base->toString())));
+ $this->assertObjectNotEquals(UuidV4::from(self::OTHER_UUID), $id);
}
- public function testTryFromWithString(): void
+ #[Test]
+ public function it_is_a_uuid_v4_with_the_same_value(): void
{
- $base = RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816');
+ $base = RamseyUuid::uuid4();
+ $id = UuidV4::from($base);
+
+ $actual = $id->is(UuidV4::from($base));
- $this->assertTrue(UuidV4::from($base)->is(UuidV4::tryFrom($base->toString())));
- $this->assertNull(UuidV4::tryFrom('invalid'));
+ $this->assertTrue($actual);
}
- public function testTryFromWithNull(): void
+ #[Test]
+ public function it_is_a_uuid_with_the_same_value(): void
{
- $this->assertNull(Uuid::tryFrom(null));
+ $base = RamseyUuid::uuid4();
+ $id = UuidV4::from($base);
+
+ $actual = $id->is(new Uuid($base));
+
+ $this->assertTrue($actual);
}
- public function testCompareTo(): void
+ #[Test]
+ public function it_is_not_a_uuid_with_a_different_value(): void
{
- $uuid1 = UuidV4::make();
- $uuid2 = UuidV4::make();
- $uuid3 = UuidV4::make();
+ $id = UuidV4::from(self::UUID);
- $expected = [$uuid3->value, $uuid1->value, $uuid2->value];
- usort($expected, fn ($a, $b) => $a->compareTo($b));
+ $actual = $id->is(UuidV4::from(self::OTHER_UUID));
- $actual = [$uuid2, $uuid1, $uuid3];
- usort($actual, fn ($a, $b) => $a->compareTo($b));
- $actual = array_map(fn ($id) => $id->value, $actual);
+ $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 d0d6a522..14fc69dc 100644
--- a/tests/Unit/Toolkit/Identifiers/UuidV7Test.php
+++ b/tests/Unit/Toolkit/Identifiers/UuidV7Test.php
@@ -20,15 +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
{
- public function test(): void
+ 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);
@@ -43,102 +52,253 @@ public function test(): void
);
}
- public function testItIsEquals(): void
+ #[Test]
+ 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_can_be_created_from_a_string(): void
+ {
+ $expected = UuidV7::from(RamseyUuid::fromString(self::UUID));
+
+ $actual = UuidV7::from(self::UUID);
+
+ $this->assertObjectEquals($expected, $actual);
+ }
+
+ #[Test]
+ public function it_can_try_to_create_from_a_string(): void
+ {
+ $expected = UuidV7::from(RamseyUuid::fromString(self::UUID));
+
+ $actual = UuidV7::tryFrom(self::UUID);
+
+ $this->assertNotNull($actual);
+ $this->assertObjectEquals($expected, $actual);
}
- public function testItIsNotEqual(): void
+ #[Test]
+ public function it_returns_null_when_trying_from_an_invalid_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));
+ $actual = UuidV7::tryFrom('invalid');
+
+ $this->assertNull($actual);
}
/**
- * @return array
+ * @return array
*/
public static function notUuidV7Provider(): array
{
return [
- [null],
- [new IntegerId(1)],
- [new StringId('foo')],
- [new Guid('SomeType', new Uuid(RamseyUuid::fromString('6dcbad65-ed92-4e60-973b-9ba58a022816')))],
- [Uuid::random()],
- [UuidV4::make()],
+ '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')]
- public function testIsWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ public function it_cannot_be_created_from_other_identifier_types(?Identifier $other): void
{
- $id = UuidV7::from(RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df'));
+ $this->expectException(ContractException::class);
+ $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other));
- $this->assertFalse($id->is($other));
- $this->assertFalse($id->any(null, UuidV7::make(), $other));
- $this->assertFalse($id->any());
+ UuidV7::from($other);
}
#[DataProvider('notUuidV7Provider')]
- public function testFromWithOtherIdentifiers(?Identifier $other): void
+ #[Test]
+ public function it_returns_null_when_trying_from_other_identifier_types(?Identifier $other): void
{
- $this->expectException(ContractException::class);
- $this->expectExceptionMessage('Unexpected identifier type, received: ' . get_debug_type($other));
- UuidV7::from($other);
+ $actual = UuidV7::tryFrom($other);
+
+ $this->assertNull($actual);
}
- #[DataProvider('notUuidV7Provider')]
- public function testTryFromWithOtherIdentifiers(?Identifier $other): void
+ // -------------------------------------------------------------------------
+ // is(), any() and equals()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_equals_a_uuid_with_the_same_value(): void
{
- $this->assertNull(UuidV7::tryFrom($other));
+ $id = UuidV7::from(self::UUID);
+
+ $this->assertObjectEquals(UuidV7::from(self::UUID), $id);
}
- public function testFromWithString(): void
+ #[Test]
+ 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::from($base->toString())));
+ $this->assertObjectNotEquals(UuidV7::from(self::OTHER_UUID), $id);
}
- public function testTryFromWithString(): void
+ #[Test]
+ public function it_is_a_uuid_v7_with_the_same_value(): void
{
- $base = RamseyUuid::fromString('019b7acc-aff8-7f70-adc9-e9c7f632e6df');
+ $base = RamseyUuid::uuid7();
+ $id = UuidV7::from($base);
- $this->assertTrue(UuidV7::from($base)->is(UuidV7::tryFrom($base->toString())));
- $this->assertNull(UuidV7::tryFrom('invalid'));
+ $actual = $id->is(UuidV7::from($base));
+
+ $this->assertTrue($actual);
}
- public function testTryFromWithNull(): void
+ #[Test]
+ public function it_is_a_uuid_with_the_same_value(): void
{
- $this->assertNull(Uuid::tryFrom(null));
+ $base = RamseyUuid::uuid7();
+ $id = UuidV7::from($base);
+
+ $actual = $id->is(new Uuid($base));
+
+ $this->assertTrue($actual);
}
- public function testCompareTo(): void
+ #[Test]
+ public function it_is_not_a_uuid_with_a_different_value(): void
{
- $uuid1 = UuidV7::make();
- $uuid2 = UuidV7::make();
- $uuid3 = UuidV7::make();
+ $id = UuidV7::from(self::UUID);
- $expected = [$uuid3->value, $uuid1->value, $uuid2->value];
- usort($expected, fn ($a, $b) => $a->compareTo($b));
+ $actual = $id->is(UuidV7::from(self::OTHER_UUID));
- $actual = [$uuid2, $uuid1, $uuid3];
- usort($actual, fn ($a, $b) => $a->compareTo($b));
- $actual = array_map(fn ($id) => $id->value, $actual);
+ $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 0d32e931..3a5a1114 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'];
@@ -37,10 +39,13 @@ public function __construct(string ...$values)
}
};
- $this->assertSame($expected, $list->all());
+ $actual = $list->all();
+
+ $this->assertSame($expected, $actual);
}
- public function testItYieldsListFromKeyedSet(): void
+ #[Test]
+ public function it_yields_list_from_keyed_set(): void
{
$expected = ['one' => 'foo', 'two' => 'bar', 'three' => 'baz'];
@@ -62,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 95fb30e8..4a43123b 100644
--- a/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php
+++ b/tests/Unit/Toolkit/Iterables/IsNonEmptyListTest.php
@@ -14,18 +14,50 @@
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_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;
@@ -34,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 6ea0a70f..0b0b62be 100644
--- a/tests/Unit/Toolkit/ModuleBasenameTest.php
+++ b/tests/Unit/Toolkit/ModuleBasenameTest.php
@@ -12,10 +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
{
@@ -124,67 +126,172 @@ 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);
$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')]
- 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);
$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);
}
- public function testToArray(): ModuleBasename
+ #[DataProvider('withoutModuleProvider')]
+ #[Test]
+ 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('testToArray')]
- public function testJsonSerialize(ModuleBasename $value): void
+ #[Test]
+ 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,
+ );
}
- 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);
+ $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 c010e1b8..b27a4f51 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();
@@ -26,17 +28,17 @@ public function test(): 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;
};
@@ -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();
@@ -55,17 +58,17 @@ public function testWithInitialValue(): 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;
};
@@ -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..708d07e5 100644
--- a/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php
+++ b/tests/Unit/Toolkit/Pipeline/LazyPipeTest.php
@@ -15,8 +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
{
@@ -31,13 +34,23 @@ 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
+ {
+ $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())
@@ -45,29 +58,48 @@ public function test(): void
->with('arg1', 'arg2')
->willReturn($expected = 'Hello World!');
- $lazyPipe = new LazyPipe($this->container, 'SomePipe');
$actual = $lazyPipe('arg1', 'arg2');
$this->assertSame($expected, $actual);
}
- public function testItRethrowsException(): void
+ #[Test]
+ 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 44fa9df0..485d499a 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),
@@ -71,6 +76,37 @@ public function testNoStagesWithDestination(): void
$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 75832ac5..14c81ed1 100644
--- a/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php
+++ b/tests/Unit/Toolkit/Pipeline/PipeContainerTest.php
@@ -13,21 +13,72 @@
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_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 62d79077..bdea3c37 100644
--- a/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php
+++ b/tests/Unit/Toolkit/Pipeline/PipelineBuilderTest.php
@@ -13,18 +13,21 @@
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;
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),
+ $processor = $this->createStub(Processor::class),
$stages = ['strtoupper', 'strtolower'],
);
@@ -36,10 +39,11 @@ 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);
+ $container = $this->createStub(PipeContainer::class);
+ $processor = $this->createStub(Processor::class);
$expected = new Pipeline($processor, [
'strtoupper',
@@ -54,17 +58,62 @@ 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);
$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 f725dc9d..c246ed75 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,19 +75,42 @@ 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, [
+ $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/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/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 0502cc56..f371961c 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);
@@ -29,11 +31,30 @@ public function test(): 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));
}
- public function testOnlyMessage(): void
+ #[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]
+ public function it_can_have_only_a_message(): void
{
$error = new Error(message: 'Hello World');
@@ -42,7 +63,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,11 +73,38 @@ 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.');
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 5094e275..6f0f1956 100644
--- a/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php
+++ b/tests/Unit/Toolkit/Result/FailedResultExceptionTest.php
@@ -12,14 +12,19 @@
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;
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,22 +35,22 @@ 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);
$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());
}
- public function testItHasCodeAndPreviousException(): void
+ #[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);
@@ -54,4 +59,54 @@ public function testItHasCodeAndPreviousException(): 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 ed514e2e..cb20302c 100644
--- a/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php
+++ b/tests/Unit/Toolkit/Result/KeyedSetOfErrorsTest.php
@@ -12,15 +12,20 @@
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
{
- public function test(): void
+ #[Test]
+ public function it_groups_errors_by_key(): void
{
$errors = new KeyedSetOfErrors(
$a = new Error(message: 'Message A', key: 'foo'),
@@ -48,11 +53,42 @@ public function test(): 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));
}
- public function testEmpty(): void
+ /**
+ * @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]
+ public function it_can_be_empty(): void
{
$errors = new KeyedSetOfErrors();
@@ -61,7 +97,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 +121,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 +144,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 +168,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 +191,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'),
@@ -191,4 +232,107 @@ public function testMerge(): 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 cd98e280..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,11 +20,17 @@
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
{
- public function test(): void
+ #[Test]
+ public function it_holds_errors(): void
{
$errors = new ListOfErrors(
$a = new Error(null, 'Message A'),
@@ -39,18 +46,20 @@ public function test(): void
$this->assertFalse($errors->isEmpty());
}
- public function testEmpty(): void
+ #[Test]
+ public function it_can_be_empty(): void
{
$errors = new ListOfErrors();
$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());
}
- public function testPush(): void
+ #[Test]
+ public function it_pushes_an_error(): void
{
$original = new ListOfErrors(
$a = new Error(null, 'Message A'),
@@ -64,7 +73,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 +95,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'),
@@ -93,26 +104,58 @@ public function testFirst(): void
new Error(null, 'Message C'),
);
- $this->assertSame($a, $errors->first());
+ $actual = $errors->first();
+
+ $this->assertSame($a, $actual);
}
- public function testFind(): void
+ /**
+ * @return array
+ */
+ public static function findProvider(): array
{
- $errors = new ListOfErrors(
+ 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(Closure|UnitEnum $matcher, ?int $expected): void
+ {
+ $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);
+
+ $actual = $errors->find($matcher);
- $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));
+ $this->assertSame($expected === null ? null : $all[$expected], $actual);
}
- public function testAny(): void
+ /**
+ * @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(Closure|UnitEnum $matcher, bool $expected): void
{
$errors = new ListOfErrors(
new Error(message: 'Message A'),
@@ -121,194 +164,297 @@ public function testAny(): 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);
}
- public function testEvery(): 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()));
+ 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_checks_if_every_error_matches(
+ ListOfErrors $errors,
+ Closure|UnitEnum $matcher,
+ bool $expected,
+ ): void {
+ $actual = $errors->every($matcher);
- $this->assertTrue($errors2->every(TestUnitEnum::Baz));
- $this->assertFalse($errors1->every(TestUnitEnum::Baz));
- $this->assertFalse($errors2->every(TestUnitEnum::Bat));
+ $this->assertSame($expected, $actual);
}
- public function testSoleWithExactlyOne(): void
+ /**
+ * @return array
+ */
+ public static function soleProvider(): array
{
- $errors1 = new ListOfErrors(
- $expected = new Error(message: 'Message A', code: $code = TestUnitEnum::Baz),
- );
-
- $errors2 = new ListOfErrors(
+ $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);
}
- 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.');
-
$errors = new ListOfErrors();
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Expected exactly one error but there are 0.');
+
$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.');
-
$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();
}
- 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.');
-
$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());
}
- 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.');
-
$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());
}
- 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.');
-
$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);
}
- 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.');
-
$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);
}
- public function testFilter(): void
+ #[Test]
+ 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());
}
- public function testCodes(): void
+ #[Test]
+ public function it_filters_the_list_by_code(): void
{
- $errors1 = new ListOfErrors(
+ $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
+ {
+ $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);
}
- public function testCode(): void
+ #[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);
}
- public function testMessages(): void
+ #[Test]
+ public function it_returns_unique_messages(): void
{
$errors = new ListOfErrors(
new Error(message: 'Message A'),
@@ -318,25 +464,122 @@ public function testMessages(): 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);
}
- public function testMessage(): void
+ #[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 45605069..35973a14 100644
--- a/tests/Unit/Toolkit/Result/MetaTest.php
+++ b/tests/Unit/Toolkit/Result/MetaTest.php
@@ -12,12 +12,17 @@
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;
final class MetaTest extends TestCase
{
- public function test(): void
+ #[Test]
+ public function it_holds_values(): void
{
$meta = new Meta($values = [
'foo' => 'bar',
@@ -27,17 +32,59 @@ public function test(): 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());
}
- public function testItIsIterable(): void
+ /**
+ * @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
{
$meta = new Meta($values = [
'foo' => 'bar',
@@ -48,7 +95,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,35 +105,67 @@ public function testEmpty(): void
$this->assertFalse($meta->isNotEmpty());
}
- public function testArrayAccess(): void
+ /**
+ * @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_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);
}
- public function testOffsetUnset(): void
+ #[Test]
+ 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']);
}
- public function testOffsetSet(): void
+ #[Test]
+ 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';
}
- 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');
$this->assertNotSame($original, $actual);
@@ -93,9 +173,11 @@ 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']);
$this->assertNotSame($original, $actual);
@@ -103,13 +185,85 @@ 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']));
$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 e91f6fd8..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,9 @@
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;
@@ -29,10 +33,26 @@
final class ResultTest extends TestCase
{
- public function testOk(): void
+ /**
+ * @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());
@@ -41,13 +61,11 @@ public function testOk(): 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());
}
- public function testOkWithValue(): void
+ #[Test]
+ public function it_creates_a_successful_result_with_a_value(): void
{
$result = Result::ok($value = 99);
@@ -57,16 +75,42 @@ public function testOkWithValue(): 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
*/
- public function testFailed(): Result
+ #[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(): void
{
$errors = new ListOfErrors(new Error(null, 'Something went wrong.'));
+
$result = Result::failed($errors);
$this->assertFalse($result->didSucceed());
@@ -74,176 +118,366 @@ public function testFailed(): 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('testFailed')]
- public function testAbort(Result $result): void
+ #[DataProvider('defaultMessageProvider')]
+ #[Test]
+ public function it_returns_the_error_message_when_failed(Closure|string|null $default): void
{
- try {
- $result->abort();
- $this->fail('No exception thrown.');
- } catch (FailedResultException $ex) {
- $this->assertSame($result, $ex->getResult());
- }
- }
+ $result = Result::failed(new Error(null, 'Something went wrong.'));
- public function testErrorWithMultipleErrors(): 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($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);
}
- public function testErrorWithMultipleCodedErrors(): 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('testFailed')]
- public function testItThrowsWhenGettingValueOnFailedResult(Result $result): void
- {
- try {
- $result->value();
- $this->fail('No exception thrown.');
- } catch (FailedResultException $ex) {
- $this->assertSame($result, $ex->getResult());
- }
+ #[DataProvider('failureProvider')]
+ #[Test]
+ 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);
}
- public function testFailedWithListOfErrorsInterface(): void
+ #[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);
$this->assertFalse($result->didSucceed());
$this->assertTrue($result->didFail());
$this->assertSame($errors, $result->errors());
- $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);
$this->assertEquals(new ListOfErrors($error), $result->errors());
- $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());
+ $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());
}
- 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]);
$this->assertEquals(new ListOfErrors($error), $result->errors());
- $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);
+ $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_throws_when_aborting_a_failed_result(): void
+ {
+ $result = Result::failed('Something went wrong.');
+
+ $this->expectException(FailedResultException::class);
+ $this->expectExceptionMessage('Something went wrong.');
+
+ $result->abort();
+ }
+
+ #[Test]
+ public function it_throws_with_the_result_when_aborting_a_failed_result(): void
+ {
+ $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);
}
- public function testFailedWithoutErrors(): void
+ #[Test]
+ public function it_throws_when_resolving_a_default_message_without_a_code(): void
{
- $this->expectException(\AssertionError::class);
- Result::failed(new ListOfErrors());
+ $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));
}
- public function testFailWithoutErrors(): void
+ #[Test]
+ public function it_returns_the_default_message_when_errors_have_no_message_or_code(): void
{
- $this->expectException(\AssertionError::class);
- Result::fail(new ListOfErrors());
+ $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);
}
- public function testWithMeta(): void
+ // -------------------------------------------------------------------------
+ // withMeta()
+ // -------------------------------------------------------------------------
+
+ #[Test]
+ public function it_sets_meta(): void
{
$meta = new Meta(['foo' => 'bar']);
+
$result = Result::ok()->withMeta($meta);
$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());
+ $result = Result::ok()->withMeta(['foo' => 'bar']);
- $this->assertEquals($meta, $result->meta());
+ $this->assertEquals(new Meta(['foo' => 'bar']), $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]);
+ $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);
+ }
+}