diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index c95f9dc..49b22b4 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -25,8 +25,6 @@ jobs: - "lowest" - "highest" php-version: - - "8.2" - - "8.3" - "8.4" - "8.5" operating-system: diff --git a/README.md b/README.md index baa20c1..0ad68d4 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,15 @@ # Event Sourcing PHPUnit -"Test your event-sourcing aggregates and subscribers with a clear given / when / then notation." +"Test your event-sourcing aggregates, decisions and subscribers with a clear given / when / then notation." ## Features * A [given / when / then test case](https://patchlevel.dev/docs/event-sourcing-phpunit/latest/testing-aggregates) for aggregate behaviour * A `when` that also [dispatches commands](https://patchlevel.dev/docs/event-sourcing-phpunit/latest/testing-aggregates) through your `#[Handle]` methods * [Aggregate state assertions](https://patchlevel.dev/docs/event-sourcing-phpunit/latest/testing-aggregates) with closures +* A [given / when / then test case for decisions](https://patchlevel.dev/docs/event-sourcing-phpunit/latest/testing-decisions) of the dynamic consistency boundary, including concurrent appends +* A [test case for projections](https://patchlevel.dev/docs/event-sourcing-phpunit/latest/testing-projections) that respects your tag filters * A [subscriber utility](https://patchlevel.dev/docs/event-sourcing-phpunit/latest/testing-subscribers) for setup, run and teardown * and much more... diff --git a/composer.json b/composer.json index 0952935..eb4b867 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "patchlevel/event-sourcing-phpunit", "type": "library", "license": "MIT", - "description": "Test your event-sourcing aggregates and subscribers with a clear given / when / then notation", + "description": "Test your event-sourcing aggregates, decisions and subscribers with a clear given / when / then notation", "keywords": [ "patchlevel", "event-sourcing", @@ -22,8 +22,8 @@ } ], "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", - "patchlevel/event-sourcing": "^3.13.0", + "php": "~8.4.0 || ~8.5.0", + "patchlevel/event-sourcing": "4.0.x-dev", "phpunit/phpunit": "^10.5.45 || ^11.0.0 || ^12.0.0 || ^13.0.0" }, "require-dev": { @@ -43,6 +43,7 @@ "composer/package-versions-deprecated": true } }, + "prefer-stable": true, "autoload": { "psr-4": { "Patchlevel\\EventSourcing\\PhpUnit\\": "src/" diff --git a/composer.lock b/composer.lock index eec19fc..346d09e 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "742a1772d5223d1cc85cdcc69dac0679", + "content-hash": "2550aeb9a2aa29c0ad89a1f71f94af55", "packages": [ { "name": "brick/math", @@ -64,8 +64,7 @@ "type": "github" } ], - "time": "2026-09-12T10:28:18+00:00", - "published-time": "2026-09-12T12:23:30+00:00" + "time": "2026-09-12T10:28:18+00:00" }, { "name": "doctrine/dbal", @@ -171,8 +170,7 @@ "type": "tidelift" } ], - "time": "2026-09-24T16:11:26+00:00", - "published-time": "2026-09-26T07:58:02+00:00" + "time": "2026-09-24T16:11:26+00:00" }, { "name": "doctrine/deprecations", @@ -220,8 +218,7 @@ "issues": "https://github.com/doctrine/deprecations/issues", "source": "https://github.com/doctrine/deprecations/tree/1.1.6" }, - "time": "2026-02-07T07:09:04+00:00", - "published-time": "2026-02-07T07:10:09+00:00" + "time": "2026-02-07T07:09:04+00:00" }, { "name": "doctrine/event-manager", @@ -312,8 +309,7 @@ "type": "tidelift" } ], - "time": "2026-01-29T07:11:08+00:00", - "published-time": "2026-01-29T07:11:33+00:00" + "time": "2026-01-29T07:11:08+00:00" }, { "name": "doctrine/migrations", @@ -416,8 +412,7 @@ "type": "tidelift" } ], - "time": "2026-10-04T12:35:58+00:00", - "published-time": "2026-10-04T13:06:24+00:00" + "time": "2026-10-04T12:35:58+00:00" }, { "name": "myclabs/deep-copy", @@ -477,8 +472,7 @@ "type": "github" } ], - "time": "2026-08-11T10:17:44+00:00", - "published-time": "2026-08-11T10:29:20+00:00" + "time": "2026-08-11T10:17:44+00:00" }, { "name": "nikic/php-parser", @@ -535,29 +529,28 @@ "issues": "https://github.com/nikic/PHP-Parser/issues", "source": "https://github.com/nikic/PHP-Parser/tree/v5.9.0" }, - "time": "2026-09-13T18:51:52+00:00", - "published-time": "2026-09-13T18:53:16+00:00" + "time": "2026-09-13T18:51:52+00:00" }, { "name": "patchlevel/event-sourcing", - "version": "3.22.1", + "version": "4.0.x-dev", "source": { "type": "git", "url": "https://github.com/patchlevel/event-sourcing.git", - "reference": "809e5641b1d2caf575fbddc5d0a988055af0aaf1" + "reference": "88eaac6892931d167a27511d1c5cdb6fc4d1db25" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/patchlevel/event-sourcing/zipball/809e5641b1d2caf575fbddc5d0a988055af0aaf1", - "reference": "809e5641b1d2caf575fbddc5d0a988055af0aaf1", + "url": "https://api.github.com/repos/patchlevel/event-sourcing/zipball/88eaac6892931d167a27511d1c5cdb6fc4d1db25", + "reference": "88eaac6892931d167a27511d1c5cdb6fc4d1db25", "shasum": "" }, "require": { "doctrine/dbal": "^4.4.0", "doctrine/migrations": "^3.3.2", - "patchlevel/hydrator": "^1.8.0", - "patchlevel/worker": "^1.4.0", - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "patchlevel/hydrator": "^2.0.2", + "patchlevel/worker": "^1.7.0", + "php": "~8.4.0 || ~8.5.0", "psr/cache": "^2.0.0 || ^3.0.0", "psr/clock": "^1.0", "psr/container": "^2.0", @@ -571,10 +564,11 @@ }, "require-dev": { "doctrine/orm": "^2.18.0 || ^3.0.0", - "ext-pdo_sqlite": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "ext-pdo_sqlite": "~8.4.0 || ~8.5.0", "infection/infection": "^0.32.0", "league/commonmark": "^2.6.1", "patchlevel/coding-standard": "^1.3.0", + "patchlevel/event-sourcing-phpstan-extension": "^1.2.0", "phpat/phpat": "^0.12.0", "phpbench/phpbench": "^1.4.1", "phpstan/phpstan": "^2.1.11", @@ -609,7 +603,7 @@ } ], "description": "A lightweight but also all-inclusive event sourcing library with a focus on developer experience", - "homepage": "https://event-sourcing.patchlevel.io", + "homepage": "https://patchlevel.dev/docs/event-sourcing/latest", "keywords": [ "Domain Driven Design", "aggregates", @@ -628,23 +622,22 @@ ], "support": { "issues": "https://github.com/patchlevel/event-sourcing/issues", - "source": "https://github.com/patchlevel/event-sourcing/tree/3.22.1" + "source": "https://github.com/patchlevel/event-sourcing/tree/4.0.x" }, - "time": "2026-10-07T10:28:14+00:00", - "published-time": "2026-10-07T10:29:11+00:00" + "time": "2026-10-16T20:28:35+00:00" }, { "name": "patchlevel/hydrator", - "version": "1.24.3", + "version": "2.1.1", "source": { "type": "git", "url": "https://github.com/patchlevel/hydrator.git", - "reference": "b0c79d2b80ccf0ab95cc9b4494105af6b6bf00de" + "reference": "092dae401161ae6beb54e02cded14eb2a5fd2dbc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/patchlevel/hydrator/zipball/b0c79d2b80ccf0ab95cc9b4494105af6b6bf00de", - "reference": "b0c79d2b80ccf0ab95cc9b4494105af6b6bf00de", + "url": "https://api.github.com/repos/patchlevel/hydrator/zipball/092dae401161ae6beb54e02cded14eb2a5fd2dbc", + "reference": "092dae401161ae6beb54e02cded14eb2a5fd2dbc", "shasum": "" }, "require": { @@ -652,7 +645,6 @@ "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", "psr/cache": "^2.0.0 || ^3.0.0", "psr/simple-cache": "^2.0.0 || ^3.0.0", - "symfony/event-dispatcher": "^5.4.29 || ^6.4.0 || ^7.0.0 || ^8.0.0", "symfony/type-info": "^7.3.0 || ^8.0.0" }, "require-dev": { @@ -664,7 +656,8 @@ "phpstan/phpstan-phpunit": "^2.0.15", "phpunit/phpunit": "^11.5.53", "symfony/cache": "^6.4.0 || ^7.0.0 || ^8.0.0", - "symfony/var-dumper": "^5.4.29 || ^6.4.0 || ^7.0.0 || ^8.0.0" + "symfony/var-dumper": "^5.4.29 || ^6.4.0 || ^7.0.0 || ^8.0.0", + "wnx/commonmark-markdown-renderer": "^1.6" }, "type": "library", "autoload": { @@ -686,18 +679,21 @@ "email": "david.badura@patchlevel.de" } ], - "description": "Hydrator", - "homepage": "https://github.com/patchlevel/hydrator", + "description": "A library for seamless hydration of objects to arrays - and back again, optimized for developer experience and performance", + "homepage": "https://patchlevel.dev/docs/hydrator/latest", "keywords": [ + "denormalizer", "hydrator", + "normalizer", + "object mapping", + "patchlevel", "serializer" ], "support": { "issues": "https://github.com/patchlevel/hydrator/issues", - "source": "https://github.com/patchlevel/hydrator/tree/1.24.3" + "source": "https://github.com/patchlevel/hydrator/tree/2.1.1" }, - "time": "2026-10-07T10:27:41+00:00", - "published-time": "2026-10-07T10:29:31+00:00" + "time": "2026-11-07T10:58:53+00:00" }, { "name": "patchlevel/worker", @@ -763,8 +759,7 @@ "issues": "https://github.com/patchlevel/worker/issues", "source": "https://github.com/patchlevel/worker/tree/1.7.0" }, - "time": "2026-10-05T07:23:26+00:00", - "published-time": "2026-10-05T07:24:55+00:00" + "time": "2026-10-05T07:23:26+00:00" }, { "name": "phar-io/manifest", @@ -831,8 +826,7 @@ "type": "github" } ], - "time": "2024-03-03T12:33:53+00:00", - "published-time": "2024-03-03T12:39:44+00:00" + "time": "2024-03-03T12:33:53+00:00" }, { "name": "phar-io/version", @@ -883,21 +877,20 @@ "issues": "https://github.com/phar-io/version/issues", "source": "https://github.com/phar-io/version/tree/3.2.1" }, - "time": "2022-02-21T01:04:05+00:00", - "published-time": "2022-02-21T01:04:30+00:00" + "time": "2022-02-21T01:04:05+00:00" }, { "name": "phpunit/php-code-coverage", - "version": "14.5.0", + "version": "14.5.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "1db2f40af7a6538742e4a634b71ee556d6219be7" + "reference": "4063552c678ce3beb4b7f131a5b7354a19ff3e2a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/1db2f40af7a6538742e4a634b71ee556d6219be7", - "reference": "1db2f40af7a6538742e4a634b71ee556d6219be7", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/4063552c678ce3beb4b7f131a5b7354a19ff3e2a", + "reference": "4063552c678ce3beb4b7f131a5b7354a19ff3e2a", "shasum": "" }, "require": { @@ -953,7 +946,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", - "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/14.5.0" + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/14.5.1" }, "funding": [ { @@ -973,8 +966,7 @@ "type": "tidelift" } ], - "time": "2026-10-30T08:11:15+00:00", - "published-time": "2026-10-30T08:11:34+00:00" + "time": "2026-11-02T11:47:37+00:00" }, { "name": "phpunit/php-file-iterator", @@ -1047,8 +1039,7 @@ "type": "tidelift" } ], - "time": "2026-08-25T14:47:43+00:00", - "published-time": "2026-08-25T14:48:49+00:00" + "time": "2026-08-25T14:47:43+00:00" }, { "name": "phpunit/php-invoker", @@ -1124,8 +1115,7 @@ "type": "tidelift" } ], - "time": "2026-02-06T04:34:47+00:00", - "published-time": "2026-02-06T04:35:29+00:00" + "time": "2026-02-06T04:34:47+00:00" }, { "name": "phpunit/php-text-template", @@ -1197,8 +1187,7 @@ "type": "tidelift" } ], - "time": "2026-10-03T04:54:24+00:00", - "published-time": "2026-10-03T04:54:39+00:00" + "time": "2026-10-03T04:54:24+00:00" }, { "name": "phpunit/php-timer", @@ -1270,8 +1259,7 @@ "type": "tidelift" } ], - "time": "2026-02-06T04:37:53+00:00", - "published-time": "2026-02-06T04:38:39+00:00" + "time": "2026-02-06T04:37:53+00:00" }, { "name": "phpunit/phpunit", @@ -1362,8 +1350,7 @@ "type": "other" } ], - "time": "2026-06-04T06:16:42+00:00", - "published-time": "2026-06-04T06:17:50+00:00" + "time": "2026-06-04T06:16:42+00:00" }, { "name": "psr/cache", @@ -1412,8 +1399,7 @@ "support": { "source": "https://github.com/php-fig/cache/tree/3.0.0" }, - "time": "2021-02-03T23:26:27+00:00", - "published-time": "2021-02-03T23:27:34+00:00" + "time": "2021-02-03T23:26:27+00:00" }, { "name": "psr/clock", @@ -1461,8 +1447,7 @@ "issues": "https://github.com/php-fig/clock/issues", "source": "https://github.com/php-fig/clock/tree/1.0.0" }, - "time": "2022-11-25T14:36:26+00:00", - "published-time": "2022-11-25T14:59:22+00:00" + "time": "2022-11-25T14:36:26+00:00" }, { "name": "psr/container", @@ -1515,8 +1500,7 @@ "issues": "https://github.com/php-fig/container/issues", "source": "https://github.com/php-fig/container/tree/2.0.2" }, - "time": "2021-11-05T16:47:00+00:00", - "published-time": "2021-11-05T16:53:27+00:00" + "time": "2021-11-05T16:47:00+00:00" }, { "name": "psr/event-dispatcher", @@ -1566,8 +1550,7 @@ "issues": "https://github.com/php-fig/event-dispatcher/issues", "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" }, - "time": "2019-01-08T18:20:26+00:00", - "published-time": "2019-03-25T15:31:44+00:00" + "time": "2019-01-08T18:20:26+00:00" }, { "name": "psr/log", @@ -1617,8 +1600,7 @@ "support": { "source": "https://github.com/php-fig/log/tree/3.0.2" }, - "time": "2024-09-11T13:17:53+00:00", - "published-time": "2024-09-11T13:21:14+00:00" + "time": "2024-09-11T13:17:53+00:00" }, { "name": "psr/simple-cache", @@ -1669,8 +1651,7 @@ "support": { "source": "https://github.com/php-fig/simple-cache/tree/3.0.0" }, - "time": "2021-10-29T13:26:27+00:00", - "published-time": "2021-10-29T13:27:19+00:00" + "time": "2021-10-29T13:26:27+00:00" }, { "name": "ramsey/collection", @@ -1746,8 +1727,7 @@ "issues": "https://github.com/ramsey/collection/issues", "source": "https://github.com/ramsey/collection/tree/2.1.1" }, - "time": "2025-03-22T05:38:12+00:00", - "published-time": "2025-03-22T05:39:22+00:00" + "time": "2025-03-22T05:38:12+00:00" }, { "name": "ramsey/uuid", @@ -1825,8 +1805,7 @@ "issues": "https://github.com/ramsey/uuid/issues", "source": "https://github.com/ramsey/uuid/tree/4.9.4" }, - "time": "2026-09-16T11:39:30+00:00", - "published-time": "2026-09-16T11:41:15+00:00" + "time": "2026-09-16T11:39:30+00:00" }, { "name": "sebastian/cli-parser", @@ -1895,8 +1874,7 @@ "type": "tidelift" } ], - "time": "2026-08-01T04:27:14+00:00", - "published-time": "2026-08-01T04:29:01+00:00" + "time": "2026-08-01T04:27:14+00:00" }, { "name": "sebastian/comparator", @@ -1988,8 +1966,7 @@ "type": "tidelift" } ], - "time": "2026-05-21T04:46:40+00:00", - "published-time": "2026-05-21T04:46:53+00:00" + "time": "2026-05-21T04:46:40+00:00" }, { "name": "sebastian/complexity", @@ -2059,8 +2036,7 @@ "type": "tidelift" } ], - "time": "2026-02-06T04:41:32+00:00", - "published-time": "2026-02-06T04:41:49+00:00" + "time": "2026-02-06T04:41:32+00:00" }, { "name": "sebastian/diff", @@ -2139,8 +2115,7 @@ "type": "tidelift" } ], - "time": "2026-05-15T04:58:09+00:00", - "published-time": "2026-05-15T04:58:22+00:00" + "time": "2026-05-15T04:58:09+00:00" }, { "name": "sebastian/environment", @@ -2216,8 +2191,7 @@ "type": "tidelift" } ], - "time": "2026-10-01T12:37:56+00:00", - "published-time": "2026-10-01T12:38:48+00:00" + "time": "2026-10-01T12:37:56+00:00" }, { "name": "sebastian/exporter", @@ -2307,8 +2281,7 @@ "type": "tidelift" } ], - "time": "2026-08-07T07:22:06+00:00", - "published-time": "2026-08-07T07:23:47+00:00" + "time": "2026-08-07T07:22:06+00:00" }, { "name": "sebastian/git-state", @@ -2377,8 +2350,7 @@ "type": "tidelift" } ], - "time": "2026-10-21T05:59:52+00:00", - "published-time": "2026-10-21T06:01:28+00:00" + "time": "2026-10-21T05:59:52+00:00" }, { "name": "sebastian/global-state", @@ -2452,8 +2424,7 @@ "type": "tidelift" } ], - "time": "2026-06-01T15:11:33+00:00", - "published-time": "2026-06-01T15:20:45+00:00" + "time": "2026-06-01T15:11:33+00:00" }, { "name": "sebastian/lines-of-code", @@ -2523,8 +2494,7 @@ "type": "tidelift" } ], - "time": "2026-07-09T08:42:34+00:00", - "published-time": "2026-07-09T08:44:06+00:00" + "time": "2026-07-09T08:42:34+00:00" }, { "name": "sebastian/object-enumerator", @@ -2593,8 +2563,7 @@ "type": "tidelift" } ], - "time": "2026-08-13T07:05:05+00:00", - "published-time": "2026-08-13T07:07:58+00:00" + "time": "2026-08-13T07:05:05+00:00" }, { "name": "sebastian/object-reflector", @@ -2662,8 +2631,7 @@ "type": "tidelift" } ], - "time": "2026-08-13T06:34:36+00:00", - "published-time": "2026-08-13T06:39:22+00:00" + "time": "2026-08-13T06:34:36+00:00" }, { "name": "sebastian/recursion-context", @@ -2739,8 +2707,7 @@ "type": "tidelift" } ], - "time": "2026-08-03T05:58:12+00:00", - "published-time": "2026-08-03T05:59:59+00:00" + "time": "2026-08-03T05:58:12+00:00" }, { "name": "sebastian/type", @@ -2809,8 +2776,7 @@ "type": "tidelift" } ], - "time": "2026-08-10T08:00:57+00:00", - "published-time": "2026-08-10T08:01:43+00:00" + "time": "2026-08-10T08:00:57+00:00" }, { "name": "sebastian/version", @@ -2876,8 +2842,7 @@ "type": "tidelift" } ], - "time": "2026-10-04T05:51:14+00:00", - "published-time": "2026-10-04T05:52:22+00:00" + "time": "2026-10-04T05:51:14+00:00" }, { "name": "staabm/side-effects-detector", @@ -2929,21 +2894,20 @@ "type": "github" } ], - "time": "2024-10-20T05:08:20+00:00", - "published-time": "2024-10-20T05:09:39+00:00" + "time": "2024-10-20T05:08:20+00:00" }, { "name": "symfony/console", - "version": "v8.1.10", + "version": "v8.1.11", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "5b6d9b127ec27bc6db59bf65e2e37b6fe5b00083" + "reference": "5a315b092b81f3e920e9daea1a2ae4c66ed298b9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/5b6d9b127ec27bc6db59bf65e2e37b6fe5b00083", - "reference": "5b6d9b127ec27bc6db59bf65e2e37b6fe5b00083", + "url": "https://api.github.com/repos/symfony/console/zipball/5a315b092b81f3e920e9daea1a2ae4c66ed298b9", + "reference": "5a315b092b81f3e920e9daea1a2ae4c66ed298b9", "shasum": "" }, "require": { @@ -3010,7 +2974,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v8.1.10" + "source": "https://github.com/symfony/console/tree/v8.1.11" }, "funding": [ { @@ -3030,21 +2994,20 @@ "type": "tidelift" } ], - "time": "2026-10-28T11:16:19+00:00", - "published-time": "2026-10-28T18:23:59+00:00" + "time": "2026-11-04T07:07:11+00:00" }, { "name": "symfony/deprecation-contracts", - "version": "v3.7.1", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d" + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/feb1edf4e546af3b85c5caebe8359a20db230ca3", + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3", "shasum": "" }, "require": { @@ -3057,7 +3020,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -3082,7 +3045,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.8.1" }, "funding": [ { @@ -3102,8 +3065,7 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00", - "published-time": "2026-06-27T21:46:34+00:00" + "time": "2026-09-16T14:15:10+00:00" }, { "name": "symfony/event-dispatcher", @@ -3189,21 +3151,20 @@ "type": "tidelift" } ], - "time": "2026-08-21T17:47:34+00:00", - "published-time": "2026-08-22T13:46:58+00:00" + "time": "2026-08-21T17:47:34+00:00" }, { "name": "symfony/event-dispatcher-contracts", - "version": "v3.7.1", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher-contracts.git", - "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e" + "reference": "658e29751424da3ef4758c60f769e59d1b2981eb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/c7de7a00ffb67842132da02ea92988a39ccd9f4e", - "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/658e29751424da3ef4758c60f769e59d1b2981eb", + "reference": "658e29751424da3ef4758c60f769e59d1b2981eb", "shasum": "" }, "require": { @@ -3217,7 +3178,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -3250,7 +3211,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.8.1" }, "funding": [ { @@ -3270,21 +3231,20 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00", - "published-time": "2026-06-27T21:46:35+00:00" + "time": "2026-09-16T14:15:10+00:00" }, { "name": "symfony/finder", - "version": "v8.1.10", + "version": "v8.1.11", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "2f4c0f26106520d82e1b71759d2fb8d32d8b7a43" + "reference": "a2902e479ba5691d20d51d100a715ea19ad2c837" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/2f4c0f26106520d82e1b71759d2fb8d32d8b7a43", - "reference": "2f4c0f26106520d82e1b71759d2fb8d32d8b7a43", + "url": "https://api.github.com/repos/symfony/finder/zipball/a2902e479ba5691d20d51d100a715ea19ad2c837", + "reference": "a2902e479ba5691d20d51d100a715ea19ad2c837", "shasum": "" }, "require": { @@ -3319,7 +3279,7 @@ "description": "Finds files and directories via an intuitive fluent interface", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/finder/tree/v8.1.10" + "source": "https://github.com/symfony/finder/tree/v8.1.11" }, "funding": [ { @@ -3339,8 +3299,7 @@ "type": "tidelift" } ], - "time": "2026-10-19T17:00:07+00:00", - "published-time": "2026-10-28T18:25:54+00:00" + "time": "2026-11-02T10:58:30+00:00" }, { "name": "symfony/polyfill-ctype", @@ -3423,8 +3382,7 @@ "type": "tidelift" } ], - "time": "2026-04-10T16:19:22+00:00", - "published-time": "2026-04-26T14:44:50+00:00" + "time": "2026-04-10T16:19:22+00:00" }, { "name": "symfony/polyfill-deepclone", @@ -3511,8 +3469,7 @@ "type": "tidelift" } ], - "time": "2026-10-14T07:17:09+00:00", - "published-time": "2026-10-14T09:42:25+00:00" + "time": "2026-10-14T07:17:09+00:00" }, { "name": "symfony/polyfill-intl-grapheme", @@ -3594,8 +3551,7 @@ "type": "tidelift" } ], - "time": "2026-10-15T09:18:53+00:00", - "published-time": "2026-10-28T10:07:44+00:00" + "time": "2026-10-15T09:18:53+00:00" }, { "name": "symfony/polyfill-intl-normalizer", @@ -3680,8 +3636,7 @@ "type": "tidelift" } ], - "time": "2026-09-23T22:02:09+00:00", - "published-time": "2026-09-30T10:23:47+00:00" + "time": "2026-09-23T22:02:09+00:00" }, { "name": "symfony/polyfill-mbstring", @@ -3766,8 +3721,7 @@ "type": "tidelift" } ], - "time": "2026-10-28T09:35:49+00:00", - "published-time": "2026-10-28T10:07:45+00:00" + "time": "2026-10-28T09:35:49+00:00" }, { "name": "symfony/polyfill-php85", @@ -3847,21 +3801,20 @@ "type": "tidelift" } ], - "time": "2026-09-25T15:46:47+00:00", - "published-time": "2026-09-30T10:23:32+00:00" + "time": "2026-09-25T15:46:47+00:00" }, { "name": "symfony/service-contracts", - "version": "v3.7.3", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/service-contracts.git", - "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257" + "reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/service-contracts/zipball/15e6a07ec2a2c75ceb1b21dd98105ee8456d2257", - "reference": "15e6a07ec2a2c75ceb1b21dd98105ee8456d2257", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/052852a96fd5e5ebdb617dba22031e41a3300fb5", + "reference": "052852a96fd5e5ebdb617dba22031e41a3300fb5", "shasum": "" }, "require": { @@ -3879,7 +3832,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -3915,7 +3868,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/service-contracts/tree/v3.7.3" + "source": "https://github.com/symfony/service-contracts/tree/v3.8.1" }, "funding": [ { @@ -3935,8 +3888,7 @@ "type": "tidelift" } ], - "time": "2026-07-27T15:39:01+00:00", - "published-time": "2026-08-30T19:56:37+00:00" + "time": "2026-10-20T17:38:25+00:00" }, { "name": "symfony/stopwatch", @@ -4002,8 +3954,7 @@ "type": "tidelift" } ], - "time": "2026-05-29T05:06:50+00:00", - "published-time": "2026-05-29T08:53:18+00:00" + "time": "2026-05-29T05:06:50+00:00" }, { "name": "symfony/string", @@ -4093,21 +4044,20 @@ "type": "tidelift" } ], - "time": "2026-10-23T17:06:53+00:00", - "published-time": "2026-10-28T18:24:27+00:00" + "time": "2026-10-23T17:06:53+00:00" }, { "name": "symfony/type-info", - "version": "v8.1.10", + "version": "v8.1.11", "source": { "type": "git", "url": "https://github.com/symfony/type-info.git", - "reference": "2083d4516f9041b8ac550d9029afb08fcf09d0ad" + "reference": "9fd1414061c4bbf953bcfc183b133cbfa0a73c73" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/type-info/zipball/2083d4516f9041b8ac550d9029afb08fcf09d0ad", - "reference": "2083d4516f9041b8ac550d9029afb08fcf09d0ad", + "url": "https://api.github.com/repos/symfony/type-info/zipball/9fd1414061c4bbf953bcfc183b133cbfa0a73c73", + "reference": "9fd1414061c4bbf953bcfc183b133cbfa0a73c73", "shasum": "" }, "require": { @@ -4156,7 +4106,7 @@ "type" ], "support": { - "source": "https://github.com/symfony/type-info/tree/v8.1.10" + "source": "https://github.com/symfony/type-info/tree/v8.1.11" }, "funding": [ { @@ -4176,8 +4126,7 @@ "type": "tidelift" } ], - "time": "2026-10-25T14:40:25+00:00", - "published-time": "2026-10-28T18:24:43+00:00" + "time": "2026-11-02T10:58:30+00:00" }, { "name": "symfony/var-exporter", @@ -4260,8 +4209,7 @@ "type": "tidelift" } ], - "time": "2026-10-22T14:30:01+00:00", - "published-time": "2026-10-28T18:24:08+00:00" + "time": "2026-10-22T14:30:01+00:00" } ], "packages-dev": [ @@ -4351,8 +4299,7 @@ "type": "patreon" } ], - "time": "2024-02-09T13:06:12+00:00", - "published-time": "2024-02-09T13:06:43+00:00" + "time": "2024-02-09T13:06:12+00:00" }, { "name": "composer/pcre", @@ -4428,8 +4375,7 @@ "type": "github" } ], - "time": "2026-06-07T11:47:49+00:00", - "published-time": "2026-06-11T12:12:37+00:00" + "time": "2026-06-07T11:47:49+00:00" }, { "name": "composer/xdebug-handler", @@ -4495,8 +4441,7 @@ "type": "tidelift" } ], - "time": "2024-05-06T16:37:16+00:00", - "published-time": "2024-05-06T17:01:42+00:00" + "time": "2024-05-06T16:37:16+00:00" }, { "name": "dealerdirect/phpcodesniffer-composer-installer", @@ -4592,8 +4537,7 @@ "type": "thanks_dev" } ], - "time": "2026-05-06T08:26:05+00:00", - "published-time": "2026-05-06T12:56:03+00:00" + "time": "2026-05-06T08:26:05+00:00" }, { "name": "dflydev/dot-access-data", @@ -4668,8 +4612,7 @@ "issues": "https://github.com/dflydev/dflydev-dot-access-data/issues", "source": "https://github.com/dflydev/dflydev-dot-access-data/tree/v3.0.3" }, - "time": "2024-07-08T12:26:09+00:00", - "published-time": "2024-07-08T12:27:13+00:00" + "time": "2024-07-08T12:26:09+00:00" }, { "name": "fidry/cpu-core-counter", @@ -4731,8 +4674,7 @@ "type": "github" } ], - "time": "2026-09-29T22:11:39+00:00", - "published-time": "2026-09-29T22:12:43+00:00" + "time": "2026-09-29T22:11:39+00:00" }, { "name": "infection/abstract-testframework-adapter", @@ -4789,8 +4731,7 @@ "type": "open_collective" } ], - "time": "2026-05-28T19:10:29+00:00", - "published-time": "2026-05-28T19:12:08+00:00" + "time": "2026-05-28T19:10:29+00:00" }, { "name": "infection/extension-installer", @@ -4856,8 +4797,7 @@ "type": "open_collective" } ], - "time": "2021-10-20T22:08:34+00:00", - "published-time": "2022-01-17T16:32:15+00:00" + "time": "2021-10-20T22:08:34+00:00" }, { "name": "infection/include-interceptor", @@ -4913,8 +4853,7 @@ "type": "open_collective" } ], - "time": "2021-08-09T10:03:57+00:00", - "published-time": "2021-08-09T10:05:07+00:00" + "time": "2021-08-09T10:03:57+00:00" }, { "name": "infection/infection", @@ -5052,8 +4991,7 @@ "type": "open_collective" } ], - "time": "2026-04-23T21:11:41+00:00", - "published-time": "2026-04-23T21:15:36+00:00" + "time": "2026-04-23T21:11:41+00:00" }, { "name": "infection/mutator", @@ -5106,8 +5044,7 @@ "type": "open_collective" } ], - "time": "2025-04-29T08:19:52+00:00", - "published-time": "2025-04-29T08:21:00+00:00" + "time": "2025-04-29T08:19:52+00:00" }, { "name": "justinrainbow/json-schema", @@ -5172,8 +5109,7 @@ "issues": "https://github.com/jsonrainbow/json-schema/issues", "source": "https://github.com/jsonrainbow/json-schema/tree/6.14.0" }, - "time": "2026-10-24T08:53:34+00:00", - "published-time": "2026-10-24T08:53:38+00:00" + "time": "2026-10-24T08:53:34+00:00" }, { "name": "league/commonmark", @@ -5280,8 +5216,7 @@ "type": "tidelift" } ], - "time": "2026-10-31T13:35:37+00:00", - "published-time": "2026-10-31T13:35:57+00:00" + "time": "2026-10-31T13:35:37+00:00" }, { "name": "league/config", @@ -5363,8 +5298,7 @@ "type": "github" } ], - "time": "2022-12-11T20:36:23+00:00", - "published-time": "2022-12-11T20:36:45+00:00" + "time": "2022-12-11T20:36:23+00:00" }, { "name": "marc-mabe/php-enum", @@ -5437,8 +5371,7 @@ "issues": "https://github.com/marc-mabe/php-enum/issues", "source": "https://github.com/marc-mabe/php-enum/tree/v4.7.2" }, - "time": "2025-09-14T11:18:39+00:00", - "published-time": "2025-09-14T11:32:17+00:00" + "time": "2025-09-14T11:18:39+00:00" }, { "name": "nette/schema", @@ -5505,8 +5438,7 @@ "issues": "https://github.com/nette/schema/issues", "source": "https://github.com/nette/schema/tree/v1.4.0" }, - "time": "2026-10-22T02:12:50+00:00", - "published-time": "2026-10-22T02:14:45+00:00" + "time": "2026-10-22T02:12:50+00:00" }, { "name": "nette/utils", @@ -5597,8 +5529,7 @@ "issues": "https://github.com/nette/utils/issues", "source": "https://github.com/nette/utils/tree/v4.1.6" }, - "time": "2026-10-20T17:07:56+00:00", - "published-time": "2026-10-20T17:48:30+00:00" + "time": "2026-10-20T17:07:56+00:00" }, { "name": "ondram/ci-detector", @@ -5676,8 +5607,7 @@ "issues": "https://github.com/OndraM/ci-detector/issues", "source": "https://github.com/OndraM/ci-detector/tree/4.2.0" }, - "time": "2024-03-12T13:22:30+00:00", - "published-time": "2024-03-12T13:23:38+00:00" + "time": "2024-03-12T13:22:30+00:00" }, { "name": "patchlevel/coding-standard", @@ -5732,8 +5662,7 @@ "issues": "https://github.com/patchlevel/coding-standard/issues", "source": "https://github.com/patchlevel/coding-standard/tree/1.3.0" }, - "time": "2023-06-02T10:05:08+00:00", - "published-time": "2023-06-02T10:07:01+00:00" + "time": "2023-06-02T10:05:08+00:00" }, { "name": "phpstan/phpdoc-parser", @@ -5780,16 +5709,15 @@ "issues": "https://github.com/phpstan/phpdoc-parser/issues", "source": "https://github.com/phpstan/phpdoc-parser/tree/2.4.1" }, - "time": "2026-10-30T19:36:28+00:00", - "published-time": "2026-10-30T19:37:11+00:00" + "time": "2026-10-30T19:36:28+00:00" }, { "name": "phpstan/phpstan", - "version": "2.3.4", + "version": "2.3.5", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/f20ce6f3c82556cfcfc086b152445a12d1d64fff", - "reference": "f20ce6f3c82556cfcfc086b152445a12d1d64fff", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/645a1bd6bead15fc1b8474137467961d0fa30a79", + "reference": "645a1bd6bead15fc1b8474137467961d0fa30a79", "shasum": "" }, "require": { @@ -5845,8 +5773,7 @@ "type": "github" } ], - "time": "2026-10-28T22:38:53+00:00", - "published-time": "2026-10-28T22:39:06+00:00" + "time": "2026-11-03T12:14:22+00:00" }, { "name": "sanmai/di-container", @@ -5925,21 +5852,20 @@ "type": "github" } ], - "time": "2026-08-11T00:58:41+00:00", - "published-time": "2026-08-11T01:02:27+00:00" + "time": "2026-08-11T00:58:41+00:00" }, { "name": "sanmai/duoclock", - "version": "0.1.3", + "version": "0.1.4", "source": { "type": "git", "url": "https://github.com/sanmai/DuoClock.git", - "reference": "47461e3ff65b7308635047831a55615652e7be1a" + "reference": "9fa79ec9445c8a43e3e6f5deefdebe920085f284" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sanmai/DuoClock/zipball/47461e3ff65b7308635047831a55615652e7be1a", - "reference": "47461e3ff65b7308635047831a55615652e7be1a", + "url": "https://api.github.com/repos/sanmai/DuoClock/zipball/9fa79ec9445c8a43e3e6f5deefdebe920085f284", + "reference": "9fa79ec9445c8a43e3e6f5deefdebe920085f284", "shasum": "" }, "require": { @@ -5981,7 +5907,7 @@ "description": "PHP time mocking for tests - PSR-20 clock with mockable sleep(), time(), and TimeSpy for PHPUnit testing", "support": { "issues": "https://github.com/sanmai/DuoClock/issues", - "source": "https://github.com/sanmai/DuoClock/tree/0.1.3" + "source": "https://github.com/sanmai/DuoClock/tree/0.1.4" }, "funding": [ { @@ -5989,8 +5915,7 @@ "type": "github" } ], - "time": "2025-12-26T06:12:34+00:00", - "published-time": "2025-12-26T06:13:23+00:00" + "time": "2026-11-06T08:04:12+00:00" }, { "name": "sanmai/later", @@ -6054,8 +5979,7 @@ "type": "github" } ], - "time": "2026-06-29T07:24:33+00:00", - "published-time": "2026-07-29T07:33:40+00:00" + "time": "2026-06-29T07:24:33+00:00" }, { "name": "sanmai/pipeline", @@ -6122,8 +6046,7 @@ "type": "github" } ], - "time": "2026-09-30T13:46:33+00:00", - "published-time": "2026-09-30T13:48:53+00:00" + "time": "2026-09-30T13:46:33+00:00" }, { "name": "slevomat/coding-standard", @@ -6188,8 +6111,7 @@ "type": "tidelift" } ], - "time": "2025-09-13T08:53:30+00:00", - "published-time": "2025-09-13T08:55:12+00:00" + "time": "2025-09-13T08:53:30+00:00" }, { "name": "squizlabs/php_codesniffer", @@ -6268,21 +6190,20 @@ "type": "thanks_dev" } ], - "time": "2026-08-06T00:17:32+00:00", - "published-time": "2026-08-06T01:05:02+00:00" + "time": "2026-08-06T00:17:32+00:00" }, { "name": "symfony/filesystem", - "version": "v8.1.9", + "version": "v8.1.11", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "43d109c803d22c00bb820ed45df250b6a8792ca2" + "reference": "58f57b6a33e3495f7f41e01258f1ae5ef76cccd2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/43d109c803d22c00bb820ed45df250b6a8792ca2", - "reference": "43d109c803d22c00bb820ed45df250b6a8792ca2", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/58f57b6a33e3495f7f41e01258f1ae5ef76cccd2", + "reference": "58f57b6a33e3495f7f41e01258f1ae5ef76cccd2", "shasum": "" }, "require": { @@ -6320,7 +6241,7 @@ "description": "Provides basic utilities for the filesystem", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/filesystem/tree/v8.1.9" + "source": "https://github.com/symfony/filesystem/tree/v8.1.11" }, "funding": [ { @@ -6340,8 +6261,7 @@ "type": "tidelift" } ], - "time": "2026-10-06T20:05:50+00:00", - "published-time": "2026-10-14T06:48:55+00:00" + "time": "2026-11-04T08:39:20+00:00" }, { "name": "symfony/polyfill-php80", @@ -6425,8 +6345,7 @@ "type": "tidelift" } ], - "time": "2026-09-25T15:50:05+00:00", - "published-time": "2026-09-30T10:23:35+00:00" + "time": "2026-09-25T15:50:05+00:00" }, { "name": "symfony/process", @@ -6491,8 +6410,7 @@ "type": "tidelift" } ], - "time": "2026-10-25T14:40:25+00:00", - "published-time": "2026-10-28T18:25:20+00:00" + "time": "2026-10-25T14:40:25+00:00" }, { "name": "thecodingmachine/safe", @@ -6635,8 +6553,7 @@ "type": "github" } ], - "time": "2026-02-04T18:08:13+00:00", - "published-time": "2026-02-15T15:48:29+00:00" + "time": "2026-02-04T18:08:13+00:00" }, { "name": "webmozart/assert", @@ -6702,21 +6619,20 @@ "issues": "https://github.com/webmozarts/assert/issues", "source": "https://github.com/webmozarts/assert/tree/2.5.0" }, - "time": "2026-10-05T23:14:19+00:00", - "published-time": "2026-10-05T23:14:25+00:00" + "time": "2026-10-05T23:14:19+00:00" }, { "name": "wnx/commonmark-markdown-renderer", - "version": "v1.7.0", + "version": "v1.7.1", "source": { "type": "git", "url": "https://github.com/stefanzweifel/commonmark-markdown-renderer.git", - "reference": "9674a70459664459fd6bb1435891c76824ecfdb0" + "reference": "035733dc26f8ec9cf62cd1437315b8ab87f449df" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/stefanzweifel/commonmark-markdown-renderer/zipball/9674a70459664459fd6bb1435891c76824ecfdb0", - "reference": "9674a70459664459fd6bb1435891c76824ecfdb0", + "url": "https://api.github.com/repos/stefanzweifel/commonmark-markdown-renderer/zipball/035733dc26f8ec9cf62cd1437315b8ab87f449df", + "reference": "035733dc26f8ec9cf62cd1437315b8ab87f449df", "shasum": "" }, "require": { @@ -6756,7 +6672,7 @@ ], "support": { "issues": "https://github.com/stefanzweifel/commonmark-markdown-renderer/issues", - "source": "https://github.com/stefanzweifel/commonmark-markdown-renderer/tree/v1.7.0" + "source": "https://github.com/stefanzweifel/commonmark-markdown-renderer/tree/v1.7.1" }, "funding": [ { @@ -6764,18 +6680,19 @@ "type": "github" } ], - "time": "2026-10-24T09:39:02+00:00", - "published-time": "2026-10-24T09:44:53+00:00" + "time": "2026-11-03T12:54:09+00:00" } ], "aliases": [], "minimum-stability": "stable", - "stability-flags": {}, - "prefer-stable": false, + "stability-flags": { + "patchlevel/event-sourcing": 20 + }, + "prefer-stable": true, "prefer-lowest": false, "platform": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0" + "php": "~8.4.0 || ~8.5.0" }, "platform-dev": {}, - "plugin-api-version": "2.11.0" + "plugin-api-version": "2.6.0" } diff --git a/docs/UPGRADE-2.0.md b/docs/UPGRADE-2.0.md new file mode 100644 index 0000000..9dd8eb1 --- /dev/null +++ b/docs/UPGRADE-2.0.md @@ -0,0 +1,97 @@ + +--- + +## searchable: false + +# Upgrade 2.0 + +## Requirements + +### PHP + +The minimum PHP version is now 8.4. + +### Event Sourcing + +This version requires `patchlevel/event-sourcing` 4.x, support for 3.x has been removed. +Your aggregates, events and subscribers have to be migrated as well, +follow the [event-sourcing upgrade guide](https://github.com/patchlevel/event-sourcing/blob/4.0.x/docs/UPGRADE-4.0.md) for that. + +## Subscriber Tests + +### Custom ArgumentResolver + +The third constructor argument of `SubscriberUtilities` still takes your argument resolvers, +but event-sourcing 4.x changed the `ArgumentResolver` interface. +`resolve` receives an `ArgumentResolverContext` instead of the `Message`, and `ArgumentMetadata::$type` is now a `Symfony\Component\TypeInfo\Type`. + +before: + +```php +use Patchlevel\EventSourcing\Message\Message; +use Patchlevel\EventSourcing\Metadata\Subscriber\ArgumentMetadata; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\ArgumentResolver; + +final class TokenResolver implements ArgumentResolver +{ + public function resolve(ArgumentMetadata $argument, Message $message): mixed + { + return $message->header(TokenHeader::class); + } + + public function support(ArgumentMetadata $argument, string $eventClass): bool + { + return $argument->type === TokenHeader::class; + } +} +``` +after: + +```php +use Patchlevel\EventSourcing\Metadata\Subscriber\ArgumentMetadata; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\ArgumentResolver; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\ArgumentResolverContext; + +final class TokenResolver implements ArgumentResolver +{ + public function resolve(ArgumentMetadata $argument, ArgumentResolverContext $context): mixed + { + return $context->message->header(TokenHeader::class); + } + + public function support(ArgumentMetadata $argument, string $eventClass): bool + { + return $argument->type->isIdentifiedBy(TokenHeader::class); + } +} +``` +### Batching + +The `BatchableSubscriber` interface has been removed in event-sourcing 4.x in favor of the batch attributes. +`executeRun()` now drives the batch for you, so remove your manual calls. It begins the batch, passes the state +to the parameters marked with `#[BatchState]`, flushes it and rolls it back if a subscribe method throws. + +before: + +```php +use Patchlevel\EventSourcing\PhpUnit\Test\SubscriberUtilities; + +$subscriber = new ProfileBatchCounter(); + +$util = new SubscriberUtilities($subscriber); + +$subscriber->beginBatch(); +$util->executeRun(new ProfileCreated(ProfileId::fromString('1'), Email::fromString('hq@patchlevel.de'))); +$subscriber->commitBatch(); +``` +after: + +```php +use Patchlevel\EventSourcing\PhpUnit\Test\SubscriberUtilities; + +$subscriber = new ProfileBatchCounter(); + +$util = new SubscriberUtilities($subscriber); + +$util->executeRun(new ProfileCreated(ProfileId::fromString('1'), Email::fromString('hq@patchlevel.de'))); +``` \ No newline at end of file diff --git a/docs/getting-started.md b/docs/getting-started.md index 5abceb2..f5e8771 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -172,4 +172,5 @@ You now have a fast unit test suite for your aggregates and subscribers, written ## Learn more * [How to test aggregates](testing-aggregates.md) +* [How to test decisions](testing-decisions.md) * [How to test subscribers](testing-subscribers.md) diff --git a/docs/introduction.md b/docs/introduction.md index 4e590a1..dae5f9e 100644 --- a/docs/introduction.md +++ b/docs/introduction.md @@ -1,12 +1,14 @@ # Event Sourcing PHPUnit -Testing utilities that make it easy to test your [event-sourcing](https://patchlevel.dev/docs/event-sourcing/latest) code with PHPUnit. It ships a given / when / then test case for aggregates and a helper that drives subscribers through their lifecycle, so your tests describe behaviour instead of wiring. +Testing utilities that make it easy to test your [event-sourcing](https://patchlevel.dev/docs/event-sourcing/latest) code with PHPUnit. It ships given / when / then test cases for aggregates, decisions and projections and a helper that drives subscribers through their lifecycle, so your tests describe behaviour instead of wiring. ## Features * A [given / when / then test case](testing-aggregates.md) for aggregate behaviour * A `when` that also [dispatches commands](testing-aggregates.md) through your `#[Handle]` methods * [Aggregate state assertions](testing-aggregates.md) with closures +* A [given / when / then test case for decisions](testing-decisions.md) of the dynamic consistency boundary, including concurrent appends +* A [test case for projections](testing-projections.md) that respects your tag filters * A [subscriber utility](testing-subscribers.md) for setup, run and teardown * and much more... diff --git a/docs/project.json b/docs/project.json index be50991..10edaee 100644 --- a/docs/project.json +++ b/docs/project.json @@ -3,6 +3,9 @@ { "title": "Introduction", "file": "introduction.md" }, { "title": "Getting Started", "file": "getting-started.md" }, { "title": "Testing Aggregates", "file": "testing-aggregates.md" }, - { "title": "Testing Subscribers", "file": "testing-subscribers.md" } + { "title": "Testing Decisions", "file": "testing-decisions.md" }, + { "title": "Testing Projections", "file": "testing-projections.md" }, + { "title": "Testing Subscribers", "file": "testing-subscribers.md" }, + { "title": "Upgrade from 1.x", "file": "UPGRADE-2.0.md" } ] } diff --git a/docs/testing-aggregates.md b/docs/testing-aggregates.md index 6b5368c..22da384 100644 --- a/docs/testing-aggregates.md +++ b/docs/testing-aggregates.md @@ -252,5 +252,6 @@ The test case guards against incomplete tests with dedicated errors, all extendi ## Learn more +* [How to test decisions](testing-decisions.md) * [How to test subscribers](testing-subscribers.md) * [How to get started](getting-started.md) diff --git a/docs/testing-decisions.md b/docs/testing-decisions.md new file mode 100644 index 0000000..88e3286 --- /dev/null +++ b/docs/testing-decisions.md @@ -0,0 +1,425 @@ +# Testing Decisions + +With the [dynamic consistency boundary](https://patchlevel.dev/docs/event-sourcing/latest/dynamic-consistency-boundary) a command handler reads a few small projections through a `Decision` and appends new events. `DecisionTestCase` lets you test these handlers with the same given / when / then notation as [aggregates](testing-aggregates.md). Your tests run against an in-memory store that applies the real tag queries and append conditions, so no database is involved. + +:::experimental +The dynamic consistency boundary is still experimental in the event-sourcing library and so are these test helpers. They may change in a minor release. +::: + +## The example domain + +The examples on this page create profiles and make sure that every email address is only used once. This rule spans all profiles, so no single aggregate can enforce it. The event tags both the profile and the email address. + +```php +use Patchlevel\EventSourcing\Attribute\Event; +use Patchlevel\EventSourcing\Attribute\EventTag; + +#[Event('profile.created')] +final class ProfileCreated +{ + public function __construct( + #[EventTag(prefix: 'profile')] + public readonly ProfileId $profileId, + public readonly Email $email, + ) { + } + + #[EventTag(prefix: 'email')] + public function emailTag(): string + { + return $this->email->toString(); + } +} +``` +A projection answers whether the email address is already taken. Its tag filter only selects the events of this one address. + +```php +use Patchlevel\EventSourcing\Attribute\Apply; +use Patchlevel\EventSourcing\Projection\BasicProjection; + +/** @extends BasicProjection */ +final class EmailIsTaken extends BasicProjection +{ + public function __construct( + private readonly Email $email, + ) { + } + + public function initialState(): bool + { + return false; + } + + /** @return list */ + protected function tagFilter(): array + { + return ['email:' . $this->email->toString()]; + } + + #[Apply] + public function applyProfileCreated(bool $state, ProfileCreated $event): bool + { + return true; + } +} +``` +The handler reads the projection through the decision and appends the new event. + +```php +use Patchlevel\EventSourcing\Attribute\Handle; +use Patchlevel\EventSourcing\DecisionModel\Decision; + +final class EmailAlreadyTaken extends RuntimeException +{ +} + +final class CreateProfile +{ + public function __construct( + public readonly ProfileId $id, + public readonly Email $email, + ) { + } +} + +final class CreateProfileHandler +{ + #[Handle] + public function __invoke(CreateProfile $command, Decision $decision): void + { + if ($decision->read(new EmailIsTaken($command->email))) { + throw new EmailAlreadyTaken('This email is already taken.'); + } + + $decision->append([new ProfileCreated($command->id, $command->email)]); + } +} +``` +:::note +Decisions, projections and the `#[EventTag]` attribute come from the [event-sourcing](https://patchlevel.dev/docs/event-sourcing/latest/dynamic-consistency-boundary) library, not from this package. +::: + +## The test case + +Extend `DecisionTestCase` and return the services with your `#[Handle]` methods from `handlers()`. A command passed to `when()` is dispatched to them, and every parameter of type `Decision` receives a new decision. + +```php +use Patchlevel\EventSourcing\PhpUnit\Test\DecisionTestCase; + +final class CreateProfileHandlerTest extends DecisionTestCase +{ + protected function handlers(): iterable + { + return [new CreateProfileHandler()]; + } +} +``` +## Given, when, then + +`given()` takes the events that already happened, `when()` runs the command and `then()` asserts the events that were appended. The events from `given()` are not part of that comparison. + +```php +use Patchlevel\EventSourcing\PhpUnit\Test\DecisionTestCase; + +final class CreateProfileHandlerTest extends DecisionTestCase +{ + protected function handlers(): iterable + { + return [new CreateProfileHandler()]; + } + + public function testCreateProfile(): void + { + $this + ->given( + new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + ), + ) + ->when(new CreateProfile( + ProfileId::fromString('2'), + Email::fromString('info@patchlevel.de'), + )) + ->then(new ProfileCreated( + ProfileId::fromString('2'), + Email::fromString('info@patchlevel.de'), + )); + } +} +``` +:::note +Given events are tagged with your `#[EventTag]` attributes exactly like in production. A projection only sees an event if its tag filter really matches, so a wrong tag fails your test. +::: + +:::warning +Without `then()`, or when it receives only closures, the test asserts that no events were appended. Always list the events you expect. +::: + +## Expecting exceptions + +Use `expectsException()` and `expectsExceptionMessage()` to assert that a command is rejected. They work like in the [aggregate test case](testing-aggregates.md). + +```php +use Patchlevel\EventSourcing\PhpUnit\Test\DecisionTestCase; + +final class CreateProfileHandlerTest extends DecisionTestCase +{ + protected function handlers(): iterable + { + return [new CreateProfileHandler()]; + } + + public function testEmailMustBeUnique(): void + { + $this + ->given( + new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + ), + ) + ->when(new CreateProfile( + ProfileId::fromString('2'), + Email::fromString('hq@patchlevel.de'), + )) + ->expectsException(EmailAlreadyTaken::class) + ->expectsExceptionMessage('already taken'); + } +} +``` +## Testing the consistency boundary + +A decision must fail if something it has read changes before it appends. Pass the events of the other process to `concurrently()`. They are appended after the decision has read its state and right before it appends, so the real append condition decides what happens. `expectsConflict()` asserts that the append was rejected. + +```php +use Patchlevel\EventSourcing\PhpUnit\Test\DecisionTestCase; + +final class CreateProfileHandlerTest extends DecisionTestCase +{ + protected function handlers(): iterable + { + return [new CreateProfileHandler()]; + } + + public function testConflictsWithTheSameEmail(): void + { + $this + ->concurrently(new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + )) + ->when(new CreateProfile( + ProfileId::fromString('2'), + Email::fromString('hq@patchlevel.de'), + )) + ->expectsConflict(); + } + + public function testIsNotAffectedByOtherEmails(): void + { + $this + ->concurrently(new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('info@patchlevel.de'), + )) + ->when(new CreateProfile( + ProfileId::fromString('2'), + Email::fromString('hq@patchlevel.de'), + )) + ->then(new ProfileCreated( + ProfileId::fromString('2'), + Email::fromString('hq@patchlevel.de'), + )); + } +} +``` +:::tip +Test both directions. The conflict shows that your boundary is wide enough to protect the rule, the second test shows that it is not wider than necessary and does not block unrelated commands. +::: + +:::note +`expectsConflict()` is a shorthand for `expectsException(AppendConditionNotMet::class)`. The events from `concurrently()` are not part of the comparison in `then()`. +::: + +## Asserting the state after the append + +Pass a closure to `then()` to check the state after the append. The closure receives a new decision, so you can read any projection. + +```php +use Patchlevel\EventSourcing\DecisionModel\Decision; +use Patchlevel\EventSourcing\PhpUnit\Test\DecisionTestCase; + +final class CreateProfileHandlerTest extends DecisionTestCase +{ + protected function handlers(): iterable + { + return [new CreateProfileHandler()]; + } + + public function testEmailIsTakenAfterwards(): void + { + $this + ->when(new CreateProfile( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + )) + ->then( + new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + ), + static fn (Decision $decision) => self::assertTrue( + $decision->read(new EmailIsTaken(Email::fromString('hq@patchlevel.de'))), + ), + ); + } +} +``` +## Passing extra parameters + +When a handler needs more than the command and the decision, pass the extra values after the command. They are forwarded in order to the parameters that are not a `Decision`. + +```php +use Patchlevel\EventSourcing\Attribute\Handle; +use Patchlevel\EventSourcing\Clock\FrozenClock; +use Patchlevel\EventSourcing\DecisionModel\Decision; +use Patchlevel\EventSourcing\PhpUnit\Test\DecisionTestCase; +use Psr\Clock\ClockInterface; + +final class CreateProfileWithClockHandler +{ + #[Handle] + public function __invoke(CreateProfile $command, Decision $decision, ClockInterface $clock): void + { + $decision->append([new ProfileCreated($command->id, $command->email)]); + } +} + +final class CreateProfileWithClockHandlerTest extends DecisionTestCase +{ + protected function handlers(): iterable + { + return [new CreateProfileWithClockHandler()]; + } + + public function testCreateProfile(): void + { + $this + ->when( + new CreateProfile( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + ), + new FrozenClock(new DateTimeImmutable('2026-06-14 12:00:00')), + ) + ->then(new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + )); + } +} +``` +## Handlers without the command bus + +If you don't use `#[Handle]`, for example with Symfony Messenger, pass a closure to `when()`. It receives a new decision. A handler that gets the `DecisionFactory` injected can use `decisionFactory()`, which works on the store of the test. + +```php +use Patchlevel\EventSourcing\DecisionModel\DecisionFactory; +use Patchlevel\EventSourcing\PhpUnit\Test\DecisionTestCase; + +final class CreateProfileMessengerHandler +{ + public function __construct( + private readonly DecisionFactory $decisionFactory, + ) { + } + + public function __invoke(CreateProfile $command): void + { + $decision = $this->decisionFactory->begin(); + + if ($decision->read(new EmailIsTaken($command->email))) { + throw new EmailAlreadyTaken('This email is already taken.'); + } + + $decision->append([new ProfileCreated($command->id, $command->email)]); + } +} + +final class CreateProfileMessengerHandlerTest extends DecisionTestCase +{ + public function testCreateProfile(): void + { + $handler = new CreateProfileMessengerHandler($this->decisionFactory()); + + $this + ->when(static fn () => $handler(new CreateProfile( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + ))) + ->then(new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + )); + } +} +``` +## Working with headers + +`given()` and `concurrently()` also accept a `Message`, which lets you set the stream name or your own tags. Headers you don't set are added automatically. To assert the headers of what was appended, read `appendedMessages()` after `when()`. + +```php +use Patchlevel\EventSourcing\Message\Message; +use Patchlevel\EventSourcing\PhpUnit\Test\DecisionTestCase; +use Patchlevel\EventSourcing\Store\Header\StreamNameHeader; +use Patchlevel\EventSourcing\Store\Header\TagsHeader; + +final class CreateProfileHandlerTest extends DecisionTestCase +{ + protected function handlers(): iterable + { + return [new CreateProfileHandler()]; + } + + public function testHeaders(): void + { + $this + ->given( + Message::createWithHeaders( + new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('info@patchlevel.de'), + ), + [new StreamNameHeader('profile-1')], + ), + ) + ->when(new CreateProfile( + ProfileId::fromString('2'), + Email::fromString('hq@patchlevel.de'), + )) + ->then(new ProfileCreated( + ProfileId::fromString('2'), + Email::fromString('hq@patchlevel.de'), + )); + + $message = $this->appendedMessages()[0]; + + self::assertSame('main', $message->header(StreamNameHeader::class)->streamName); + self::assertSame(['profile:2', 'email:hq@patchlevel.de'], $message->header(TagsHeader::class)->tags); + } +} +``` +## Common errors + +The test case guards against tests that would pass without testing anything: + +* `NoWhenProvided` is raised when a test forgets to call `when()`. +* `WhenAlreadyCalled` is raised when `given()`, `concurrently()` or a second `when()` follow a `when()`. It runs immediately so that your mocks are verified correctly, which means everything it depends on has to come first. +* `HandlerNotFound` from the command bus is raised when `handlers()` does not return a handler for the command. + +## Learn more + +* [How to test projections](testing-projections.md) +* [How to test aggregates](testing-aggregates.md) +* [How to test subscribers](testing-subscribers.md) diff --git a/docs/testing-projections.md b/docs/testing-projections.md new file mode 100644 index 0000000..be87678 --- /dev/null +++ b/docs/testing-projections.md @@ -0,0 +1,109 @@ +# Testing Projections + +A [decision](testing-decisions.md) gets its state from small projections, and each one depends on its tag filter and its apply methods. `ProjectionTestCase` tests a projection on its own: you describe the events that happened and assert the state you expect. The events run through an in-memory store, so tag filters, event filters and checkpoints behave like in production. + +:::experimental +The dynamic consistency boundary is still experimental in the event-sourcing library and so are these test helpers. They may change in a minor release. +::: + +## Given, when, then + +Extend `ProjectionTestCase`. `given()` takes the events that already happened, `when()` takes the projection to read and `then()` takes the state you expect. The examples use the `EmailIsTaken` projection from [testing decisions](testing-decisions.md). + +```php +use Patchlevel\EventSourcing\PhpUnit\Test\ProjectionTestCase; + +final class EmailIsTakenTest extends ProjectionTestCase +{ + public function testEmailIsFree(): void + { + $this + ->when(new EmailIsTaken(Email::fromString('hq@patchlevel.de'))) + ->then(false); + } + + public function testEmailIsTaken(): void + { + $this + ->given(new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + )) + ->when(new EmailIsTaken(Email::fromString('hq@patchlevel.de'))) + ->then(true); + } + + public function testIgnoresOtherEmails(): void + { + $this + ->given(new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('info@patchlevel.de'), + )) + ->when(new EmailIsTaken(Email::fromString('hq@patchlevel.de'))) + ->then(false); + } +} +``` +:::note +Scalars and `null` are compared strictly, so `then(1)` does not pass for the state `true`. Objects and arrays are compared with `assertEquals`, so value objects inside your state are matched by value, not by identity. +::: + +:::tip +Always add a test with an event outside of the tag filter. It is the cheapest way to catch a filter that is too wide. +::: + +## Reading several projections + +Pass an array of projections to read them at once, like `Decision::read()` does. The state has the same keys. + +```php +use Patchlevel\EventSourcing\PhpUnit\Test\ProjectionTestCase; + +final class EmailIsTakenTest extends ProjectionTestCase +{ + public function testSeveralEmails(): void + { + $this + ->given(new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + )) + ->when([ + 'hq' => new EmailIsTaken(Email::fromString('hq@patchlevel.de')), + 'info' => new EmailIsTaken(Email::fromString('info@patchlevel.de')), + ]) + ->then(['hq' => true, 'info' => false]); + } +} +``` +## Asserting with a closure + +For a state that is awkward to compare as a whole, pass a closure to `then()`. It receives the state and can run any PHPUnit assertion. + +```php +use Patchlevel\EventSourcing\PhpUnit\Test\ProjectionTestCase; + +final class EmailIsTakenTest extends ProjectionTestCase +{ + public function testWithClosure(): void + { + $this + ->when(new EmailIsTaken(Email::fromString('hq@patchlevel.de'))) + ->then(static fn (bool $state) => self::assertFalse($state)); + } +} +``` +## Common errors + +The test case raises a dedicated error for tests that would not assert anything: + +* `NoWhenProvided` is raised when a test forgets to call `when()`. +* `NoThenProvided` is raised when a test forgets to call `then()`. +* `WhenAlreadyCalled` is raised when `given()` or a second `when()` follow a `when()`. + +## Learn more + +* [How to test decisions](testing-decisions.md) +* [How to test subscribers](testing-subscribers.md) +* [How to get started](getting-started.md) diff --git a/docs/testing-subscribers.md b/docs/testing-subscribers.md index bd19b86..11f3acb 100644 --- a/docs/testing-subscribers.md +++ b/docs/testing-subscribers.md @@ -167,7 +167,130 @@ $util = new SubscriberUtilities( Metadata factories and argument resolvers are defined by the [event-sourcing](https://patchlevel.dev/docs/event-sourcing/latest) library. You only need them when your subscribers go beyond the default event and header arguments. ::: +## Emitting events + +A subscribe method can ask for an `EventEmitter` to write new events. Like the subscription engine, the utility needs an `EventEmitterResolver` for that. Give it an `InMemoryStore` and assert what ended up in there. + +```php +use Patchlevel\EventSourcing\Attribute\Subscribe; +use Patchlevel\EventSourcing\Attribute\Subscriber; +use Patchlevel\EventSourcing\Metadata\Subscriber\AttributeSubscriberMetadataFactory; +use Patchlevel\EventSourcing\PhpUnit\Test\SubscriberUtilities; +use Patchlevel\EventSourcing\Store\InMemoryStore; +use Patchlevel\EventSourcing\Subscription\RunMode; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\EventEmitterResolver; +use Patchlevel\EventSourcing\Subscription\Subscriber\EventEmitter\EventEmitter; +use PHPUnit\Framework\TestCase; + +#[Subscriber('profile_welcome', RunMode::FromBeginning)] +final class ProfileWelcome +{ + #[Subscribe(ProfileCreated::class)] + public function onProfileCreated(ProfileCreated $event, EventEmitter $eventEmitter): void + { + $eventEmitter->emit([new ProfileVisited($event->profileId)]); + } +} + +final class ProfileWelcomeTest extends TestCase +{ + public function testEmitsVisit(): void + { + $store = new InMemoryStore(); + + $util = new SubscriberUtilities( + new ProfileWelcome(), + new AttributeSubscriberMetadataFactory(), + [new EventEmitterResolver($store)], + ); + $util->executeRun( + new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + ), + ); + + self::assertEquals( + new ProfileVisited(ProfileId::fromString('1')), + $store->load()->current()?->event(), + ); + } +} +``` +## Batching and partitions + +A subscriber with batch attributes works like in the subscription engine. Each `executeRun()` begins a batch on the first message, passes the state to the parameters marked with `#[BatchState]`, flushes it when `afterMessages` or `#[BatchShouldFlush]` say so and flushes the rest at the end. If a subscribe method throws, the batch is rolled back and the exception is passed on to your test. + +```php +use Patchlevel\EventSourcing\Attribute\BatchBegin; +use Patchlevel\EventSourcing\Attribute\BatchFlush; +use Patchlevel\EventSourcing\Attribute\BatchState; +use Patchlevel\EventSourcing\Attribute\Subscribe; +use Patchlevel\EventSourcing\Attribute\Subscriber; +use Patchlevel\EventSourcing\PhpUnit\Test\SubscriberUtilities; +use Patchlevel\EventSourcing\Subscription\RunMode; +use PHPUnit\Framework\TestCase; + +final class ProfileCountBatch +{ + public int $count = 0; +} + +#[Subscriber('profile_batch_counter', RunMode::FromBeginning)] +final class ProfileBatchCounter +{ + public int $flushed = 0; + + #[BatchBegin] + public function begin(): ProfileCountBatch + { + return new ProfileCountBatch(); + } + + #[Subscribe(ProfileCreated::class)] + public function onProfileCreated( + ProfileCreated $event, + #[BatchState] + ProfileCountBatch $batch, + ): void { + $batch->count++; + } + + #[BatchFlush] + public function flush(ProfileCountBatch $batch): void + { + $this->flushed += $batch->count; + } +} + +final class ProfileBatchCounterTest extends TestCase +{ + public function testFlushesAtTheEnd(): void + { + $subscriber = new ProfileBatchCounter(); + + $util = new SubscriberUtilities($subscriber); + $util->executeRun( + new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('hq@patchlevel.de'), + ), + new ProfileCreated( + ProfileId::fromString('2'), + Email::fromString('info@patchlevel.de'), + ), + ); + + self::assertSame(2, $subscriber->flushed); + } +} +``` +:::note +Subscribers with a `#[Partition]` attribute get their partition key from the partitioner, and every partition has its own batch. Your messages need the headers the partitioner reads, for example a `StreamNameHeader` for the `StreamPartitioner`. +::: + ## Learn more * [How to test aggregates](testing-aggregates.md) +* [How to test decisions](testing-decisions.md) * [How to get started](getting-started.md) diff --git a/src/Test/AggregateRootTestCase.php b/src/Test/AggregateRootTestCase.php index 1ecb976..6df8be7 100644 --- a/src/Test/AggregateRootTestCase.php +++ b/src/Test/AggregateRootTestCase.php @@ -9,19 +9,17 @@ use Patchlevel\EventSourcing\CommandBus\HandlerFinder; use PHPUnit\Framework\Attributes\After; use PHPUnit\Framework\Attributes\Before; -use PHPUnit\Framework\Constraint\Exception as ExceptionConstraint; -use PHPUnit\Framework\Constraint\ExceptionMessageIsOrContains; use PHPUnit\Framework\TestCase; use ReflectionClass; -use ReflectionFunction; use Throwable; use function array_filter; use function array_values; -use function sprintf; abstract class AggregateRootTestCase extends TestCase { + use Expectations; + /** @var array */ private array $givenEvents = []; private object|null $when = null; @@ -34,9 +32,6 @@ abstract class AggregateRootTestCase extends TestCase private array $thenExpectations = []; private Throwable|null $thrownException = null; - /** @var class-string|null */ - private string|null $expectedException = null; - private string|null $expectedExceptionMessage = null; /** @return class-string */ abstract protected function aggregateClass(): string; @@ -106,21 +101,6 @@ final public function then(object ...$events): self return $this; } - /** @param class-string $exception */ - final public function expectsException(string $exception): self - { - $this->expectedException = $exception; - - return $this; - } - - final public function expectsExceptionMessage(string $exceptionMessage): self - { - $this->expectedExceptionMessage = $exceptionMessage; - - return $this; - } - #[After] final public function assert(): self { @@ -148,20 +128,7 @@ final public function assert(): self self::assertEquals($expectedEvents, $events, 'The events doesn\'t match the expected events.'); foreach ($expectationCallbacks as $callback) { - try { - $callback($this->aggregate); - } catch (Throwable $t) { - $reflection = new ReflectionFunction($callback); - - self::fail( - sprintf( - 'then() callback defined in %s on line %d failed: %s', - $reflection->getFileName(), - $reflection->getStartLine(), - $t->getMessage(), - ), - ); - } + $this->runThenCallback($callback, $this->aggregate); } return $this; @@ -179,43 +146,4 @@ final public function reset(): void $this->aggregate = null; $this->thrownException = null; } - - private function handleException(Throwable $throwable): void - { - $checked = false; - - if ($this->expectedException) { - self::assertThat($throwable, new ExceptionConstraint($this->expectedException)); - $checked = true; - } - - if ($this->expectedExceptionMessage) { - self::assertThat($throwable->getMessage(), new ExceptionMessageIsOrContains($this->expectedExceptionMessage)); - $checked = true; - } - - if (!$checked) { - throw $throwable; - } - } - - private function expectedExceptionWasNotThrown(): void - { - if ($this->expectedException !== null) { - self::assertThat(null, new ExceptionConstraint($this->expectedException)); - } - - if ($this->expectedExceptionMessage === null) { - return; - } - - self::assertThat( - null, - new ExceptionMessageIsOrContains($this->expectedExceptionMessage), - sprintf( - 'Failed asserting that exception with message "%s" is thrown', - $this->expectedExceptionMessage, - ), - ); - } } diff --git a/src/Test/AggregateTestError.php b/src/Test/AggregateTestError.php index 1f013b0..6162157 100644 --- a/src/Test/AggregateTestError.php +++ b/src/Test/AggregateTestError.php @@ -4,8 +4,6 @@ namespace Patchlevel\EventSourcing\PhpUnit\Test; -use RuntimeException; - -abstract class AggregateTestError extends RuntimeException +abstract class AggregateTestError extends TestError { } diff --git a/src/Test/DecisionTestCase.php b/src/Test/DecisionTestCase.php new file mode 100644 index 0000000..0f45a1d --- /dev/null +++ b/src/Test/DecisionTestCase.php @@ -0,0 +1,200 @@ + */ + private array $givenEvents = []; + + /** @var array */ + private array $concurrentEvents = []; + private object|null $when = null; + + /** @var array */ + private array $thenExpectations = []; + + private Throwable|null $thrownException = null; + + /** + * The services with the #[Handle] methods that are called when a command is passed to when(). + * + * @return iterable + */ + protected function handlers(): iterable + { + return []; + } + + /** @param object ...$events Events or messages that already happened. Events are tagged automatically. */ + final public function given(object ...$events): self + { + if ($this->when !== null) { + throw new WhenAlreadyCalled(); + } + + $this->givenEvents = $events; + + return $this; + } + + /** @param object ...$events Events or messages another process appends after the decision has read its state. */ + final public function concurrently(object ...$events): self + { + if ($this->when !== null) { + throw new WhenAlreadyCalled(); + } + + $this->concurrentEvents = $events; + + return $this; + } + + /** + * @param object|Closure(Decision): mixed $commandOrCallable A command that is dispatched to the handlers or a closure that receives a new decision. + * @param mixed ...$parameters Passed to the handler parameters that are not a decision. + */ + final public function when(object $commandOrCallable, mixed ...$parameters): self + { + if ($this->when !== null) { + throw new WhenAlreadyCalled(); + } + + $this->when = $commandOrCallable; + + $store = $this->store(); + $store->given(...$this->givenEvents); + $store->concurrently(...$this->concurrentEvents); + + try { + if ($commandOrCallable instanceof Closure) { + $commandOrCallable($store->decisionFactory()->begin()); + } else { + $this->dispatch($commandOrCallable, $parameters); + } + } catch (Throwable $throwable) { + $this->thrownException = $throwable; + } + + return $this; + } + + /** + * @param object|Closure(Decision): void ...$expectations Events you expect to be appended and/or callbacks. + * Callbacks receive a new decision to read the state after the append. + */ + final public function then(object ...$expectations): self + { + $this->thenExpectations = $expectations; + + return $this; + } + + /** Expects that the append was rejected because something the decision has read changed in the meantime. */ + final public function expectsConflict(): self + { + return $this->expectsException(AppendConditionNotMet::class); + } + + /** + * Use it for handlers that get the factory injected instead of a decision per command. + * All decisions of this factory work on the store of this test. + */ + final public function decisionFactory(): DecisionFactory + { + return $this->store()->decisionFactory(); + } + + /** + * The messages with all their headers, like tags and stream name, the code under test has appended. + * + * @return list + */ + final public function appendedMessages(): array + { + return $this->store()->appendedMessages(); + } + + #[After] + final public function assert(): self + { + if ($this->when === null) { + throw new NoWhenProvided(); + } + + if ($this->thrownException !== null) { + $this->handleException($this->thrownException); + + return $this; + } + + $this->expectedExceptionWasNotThrown(); + + $expectedEvents = array_values(array_filter($this->thenExpectations, static fn (object $item) => !$item instanceof Closure)); + $expectationCallbacks = array_filter($this->thenExpectations, static fn (object $item) => $item instanceof Closure); + + $events = array_map(static fn (Message $message) => $message->event(), $this->appendedMessages()); + + self::assertEquals($expectedEvents, $events, 'The appended events doesn\'t match the expected events.'); + + foreach ($expectationCallbacks as $callback) { + $this->runThenCallback($callback, $this->decisionFactory()->begin()); + } + + return $this; + } + + #[Before] + final public function reset(): void + { + $this->store = null; + $this->givenEvents = []; + $this->concurrentEvents = []; + $this->when = null; + $this->thenExpectations = []; + $this->expectedException = null; + $this->expectedExceptionMessage = null; + $this->thrownException = null; + } + + /** @param array $parameters */ + private function dispatch(object $command, array $parameters): void + { + $commandBus = new SyncCommandBus( + new ServiceHandlerProvider( + $this->handlers(), + new HandlerParameterResolver($this->decisionFactory(), $parameters), + ), + ); + + $commandBus->dispatch($command); + } + + private function store(): DecisionTestStore + { + return $this->store ??= new DecisionTestStore(); + } +} diff --git a/src/Test/DecisionTestStore.php b/src/Test/DecisionTestStore.php new file mode 100644 index 0000000..83c22ac --- /dev/null +++ b/src/Test/DecisionTestStore.php @@ -0,0 +1,114 @@ + */ + private array $concurrentMessages = []; + + /** @var list */ + private array $appendedMessages = []; + + public function __construct() + { + $this->store = new InMemoryStore(); + $this->eventAppender = new StoreEventAppender($this->store, defaultStreamName: self::DEFAULT_STREAM_NAME); + $this->eventTagExtractor = new AttributeEventTagExtractor(); + } + + public function decisionFactory(): DecisionFactory + { + return new DecisionFactory($this->store, $this); + } + + public function given(object ...$events): void + { + $this->store->append($this->messages($events)); + } + + /** The events are appended right before the next append, so after the decision has read its state. */ + public function concurrently(object ...$events): void + { + $this->concurrentMessages = $this->messages($events); + } + + /** @param list $events */ + public function append( + array $events, + AppendCondition|null $appendCondition = null, + string|null $streamName = null, + ): void { + $this->store->append($this->concurrentMessages); + $this->concurrentMessages = []; + + $head = $this->store->head(); + + $this->eventAppender->append($events, $appendCondition, $streamName); + + $this->appendedMessages = [ + ...$this->appendedMessages, + ...$this->store->query(new Query(), $head + 1), + ]; + } + + /** @return list */ + public function appendedMessages(): array + { + return $this->appendedMessages; + } + + /** + * @param array $events + * + * @return array + */ + private function messages(array $events): array + { + return array_map($this->message(...), $events); + } + + private function message(object $event): Message + { + $message = $event instanceof Message ? $event : Message::create($event); + + if (!$message->hasHeader(StreamNameHeader::class)) { + $message = $message->withHeader(new StreamNameHeader(self::DEFAULT_STREAM_NAME)); + } + + if ($message->hasHeader(TagsHeader::class)) { + return $message; + } + + return $message->withHeader(new TagsHeader($this->eventTagExtractor->extract($message->event()))); + } +} diff --git a/src/Test/Expectations.php b/src/Test/Expectations.php new file mode 100644 index 0000000..cea7a1e --- /dev/null +++ b/src/Test/Expectations.php @@ -0,0 +1,93 @@ +|null */ + private string|null $expectedException = null; + private string|null $expectedExceptionMessage = null; + + /** @param class-string $exception */ + final public function expectsException(string $exception): self + { + $this->expectedException = $exception; + + return $this; + } + + final public function expectsExceptionMessage(string $exceptionMessage): self + { + $this->expectedExceptionMessage = $exceptionMessage; + + return $this; + } + + private function handleException(Throwable $throwable): void + { + $checked = false; + + if ($this->expectedException) { + self::assertThat($throwable, new ExceptionConstraint($this->expectedException)); + $checked = true; + } + + if ($this->expectedExceptionMessage) { + self::assertThat($throwable->getMessage(), new ExceptionMessageIsOrContains($this->expectedExceptionMessage)); + $checked = true; + } + + if (!$checked) { + throw $throwable; + } + } + + private function expectedExceptionWasNotThrown(): void + { + if ($this->expectedException !== null) { + self::assertThat(null, new ExceptionConstraint($this->expectedException)); + } + + if ($this->expectedExceptionMessage === null) { + return; + } + + self::assertThat( + null, + new ExceptionMessageIsOrContains($this->expectedExceptionMessage), + sprintf( + 'Failed asserting that exception with message "%s" is thrown', + $this->expectedExceptionMessage, + ), + ); + } + + private function runThenCallback(Closure $callback, mixed $subject): void + { + try { + $callback($subject); + } catch (Throwable $t) { + $reflection = new ReflectionFunction($callback); + + self::fail( + sprintf( + 'then() callback defined in %s on line %d failed: %s', + $reflection->getFileName(), + $reflection->getStartLine(), + $t->getMessage(), + ), + ); + } + } +} diff --git a/src/Test/HandlerParameterResolver.php b/src/Test/HandlerParameterResolver.php new file mode 100644 index 0000000..12c2053 --- /dev/null +++ b/src/Test/HandlerParameterResolver.php @@ -0,0 +1,58 @@ + $parameters */ + public function __construct( + private readonly DecisionFactory $decisionFactory, + private readonly array $parameters, + ) { + } + + /** @return iterable */ + public function resolve(ReflectionMethod $method, object $command): iterable + { + $parameters = $this->parameters; + + yield $command; + + foreach ($method->getParameters() as $index => $parameter) { + if ($index === 0) { + continue; + } + + $type = $parameter->getType(); + + if ($type instanceof ReflectionNamedType && $type->getName() === Decision::class) { + yield $this->decisionFactory->begin(); + + continue; + } + + if ($parameters === []) { + return; + } + + yield array_shift($parameters); + } + } +} diff --git a/src/Test/NoThenProvided.php b/src/Test/NoThenProvided.php new file mode 100644 index 0000000..60b5c81 --- /dev/null +++ b/src/Test/NoThenProvided.php @@ -0,0 +1,13 @@ + */ + private array $givenEvents = []; + + private bool $whenCalled = false; + private mixed $state = null; + private bool $thenCalled = false; + private mixed $expectedState = null; + private Throwable|null $thrownException = null; + + /** @param object ...$events Events or messages that already happened. Events are tagged automatically. */ + final public function given(object ...$events): self + { + if ($this->whenCalled) { + throw new WhenAlreadyCalled(); + } + + $this->givenEvents = $events; + + return $this; + } + + /** + * @param Projection|array> $projection The projection to read or several of them with one read, like Decision::read(). + * + * @template S + */ + final public function when(Projection|array $projection): self + { + if ($this->whenCalled) { + throw new WhenAlreadyCalled(); + } + + $this->whenCalled = true; + + $store = new DecisionTestStore(); + $store->given(...$this->givenEvents); + + try { + $this->state = $store->decisionFactory()->begin()->read($projection); + } catch (Throwable $throwable) { + $this->thrownException = $throwable; + } + + return $this; + } + + /** @param mixed|Closure(mixed): void $state The state you expect or a callback that receives the state. */ + final public function then(mixed $state): self + { + $this->thenCalled = true; + $this->expectedState = $state; + + return $this; + } + + #[After] + final public function assert(): self + { + if (!$this->whenCalled) { + throw new NoWhenProvided(); + } + + if ($this->thrownException !== null) { + $this->handleException($this->thrownException); + + return $this; + } + + $this->expectedExceptionWasNotThrown(); + + if (!$this->thenCalled) { + throw new NoThenProvided(); + } + + $expected = $this->expectedState; + + if ($expected instanceof Closure) { + $this->runThenCallback($expected, $this->state); + + return $this; + } + + if (is_object($expected) || is_array($expected)) { + self::assertEquals($expected, $this->state, 'The state doesn\'t match the expected state.'); + + return $this; + } + + self::assertSame($expected, $this->state, 'The state doesn\'t match the expected state.'); + + return $this; + } + + #[Before] + final public function reset(): void + { + $this->givenEvents = []; + $this->whenCalled = false; + $this->state = null; + $this->thenCalled = false; + $this->expectedState = null; + $this->expectedException = null; + $this->expectedExceptionMessage = null; + $this->thrownException = null; + } +} diff --git a/src/Test/SubscriberBatch.php b/src/Test/SubscriberBatch.php new file mode 100644 index 0000000..fc8e4ca --- /dev/null +++ b/src/Test/SubscriberBatch.php @@ -0,0 +1,63 @@ +beginMethod; + + /** @var object|null $state */ + $state = $beginMethod !== null ? $subscriber->$beginMethod() : null; + + return new self($subscriber, $metadata, $state ?? new stdClass()); + } + + /** Counts a processed message and tells whether the batch has to be flushed now. */ + public function messageProcessed(): bool + { + $this->count++; + + if ($this->metadata->afterMessages !== null && $this->count >= $this->metadata->afterMessages) { + return true; + } + + $shouldFlushMethod = $this->metadata->shouldFlushMethod; + + return $shouldFlushMethod !== null && $this->subscriber->$shouldFlushMethod($this->state) === true; + } + + public function flush(): void + { + $flushMethod = $this->metadata->flushMethod; + + $this->subscriber->$flushMethod($this->state); + } + + public function rollback(): void + { + $rollbackMethod = $this->metadata->rollbackMethod; + + if ($rollbackMethod === null) { + return; + } + + $this->subscriber->$rollbackMethod($this->state); + } +} diff --git a/src/Test/SubscriberUtilities.php b/src/Test/SubscriberUtilities.php index 7bc1b97..c19e5a0 100644 --- a/src/Test/SubscriberUtilities.php +++ b/src/Test/SubscriberUtilities.php @@ -4,19 +4,39 @@ namespace Patchlevel\EventSourcing\PhpUnit\Test; +use Patchlevel\EventSourcing\Attribute\BatchState; use Patchlevel\EventSourcing\Message\Message; +use Patchlevel\EventSourcing\Metadata\Subscriber\ArgumentMetadata; use Patchlevel\EventSourcing\Metadata\Subscriber\AttributeSubscriberMetadataFactory; +use Patchlevel\EventSourcing\Metadata\Subscriber\SubscribeMethodMetadata; use Patchlevel\EventSourcing\Metadata\Subscriber\SubscriberMetadataFactory; +use Patchlevel\EventSourcing\Subscription\Status; use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\ArgumentResolver; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\ArgumentResolverContext; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\EventArgumentResolver; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\MessageArgumentResolver; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\PartitionKeyArgumentResolver; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\RecordedOnArgumentResolver; +use Patchlevel\EventSourcing\Subscription\Subscriber\MetadataSubscriberAccessor; use Patchlevel\EventSourcing\Subscription\Subscriber\MetadataSubscriberAccessorRepository; +use Patchlevel\EventSourcing\Subscription\Subscriber\NoSuitableResolver; use Patchlevel\EventSourcing\Subscription\Subscriber\SubscriberAccessorRepository; +use Patchlevel\EventSourcing\Subscription\Subscription; +use Throwable; +use function array_map; use function is_array; final class SubscriberUtilities { private SubscriberAccessorRepository $subscriberAccessorRepository; + /** @var array */ + private array $argumentResolvers; + + /** @var array */ + private array $batches = []; + /** * @param object|array $subscribers * @param iterable $argumentResolvers @@ -29,8 +49,15 @@ public function __construct( $this->subscriberAccessorRepository = new MetadataSubscriberAccessorRepository( is_array($subscribers) ? $subscribers : [$subscribers], $metadataFactory, - $argumentResolvers, ); + + $this->argumentResolvers = [ + ...$argumentResolvers, + new PartitionKeyArgumentResolver(), + new MessageArgumentResolver(), + new EventArgumentResolver(), + new RecordedOnArgumentResolver(), + ]; } public function executeSetup(): self @@ -55,17 +82,18 @@ public function executeRun(object ...$events): self $subscriberAccessors = $this->subscriberAccessorRepository->all(); foreach ($events as $event) { - if (!$event instanceof Message) { - $event = Message::create($event); - } + $message = $event instanceof Message ? $event : Message::create($event); foreach ($subscriberAccessors as $subscriberAccessor) { - foreach ($subscriberAccessor->subscribeMethods($event->event()::class) as $subscribeMethod) { - $subscribeMethod($event); - } + $this->process($subscriberAccessor, $message); } } + foreach ($this->batches as $subscriptionId => $batch) { + unset($this->batches[$subscriptionId]); + $batch->flush(); + } + return $this; } @@ -85,4 +113,105 @@ public function executeTeardown(): self return $this; } + + /** @param MetadataSubscriberAccessor $subscriberAccessor */ + private function process(MetadataSubscriberAccessor $subscriberAccessor, Message $message): void + { + $subscribeMethods = $subscriberAccessor->subscribeMethods($message->event()::class); + + if ($subscribeMethods === []) { + return; + } + + $subscription = $this->subscription($subscriberAccessor, $message); + $subscriptionId = $subscription->id(); + $batch = $this->batch($subscriberAccessor, $subscriptionId); + $context = new ArgumentResolverContext($message, $subscription, $subscriberAccessor->metadata()); + + try { + foreach ($subscribeMethods as $subscribeMethod) { + $subscriberAccessor->subscriber()->{$subscribeMethod->name}( + ...array_map( + fn (ArgumentMetadata $argument): mixed => $this->resolveArgument( + $subscriberAccessor, + $subscribeMethod, + $argument, + $context, + $batch, + ), + $subscribeMethod->arguments, + ), + ); + } + } catch (Throwable $exception) { + unset($this->batches[$subscriptionId]); + $batch?->rollback(); + + throw $exception; + } + + if ($batch === null || !$batch->messageProcessed()) { + return; + } + + unset($this->batches[$subscriptionId]); + $batch->flush(); + } + + /** @param MetadataSubscriberAccessor $subscriberAccessor */ + private function subscription(MetadataSubscriberAccessor $subscriberAccessor, Message $message): Subscription + { + $metadata = $subscriberAccessor->metadata(); + $partitioner = $subscriberAccessor->partitioner(); + + if ($partitioner === null) { + return new Subscription($metadata->id, $metadata->group, $metadata->runMode, Status::Active); + } + + $partitionKey = $partitioner($message); + + return new Subscription( + Subscription::partitionId($metadata->id, $partitionKey), + $metadata->group, + $metadata->runMode, + Status::Active, + partitionKey: $partitionKey, + ); + } + + /** @param MetadataSubscriberAccessor $subscriberAccessor */ + private function batch(MetadataSubscriberAccessor $subscriberAccessor, string $subscriptionId): SubscriberBatch|null + { + $batchMetadata = $subscriberAccessor->metadata()->batch; + + if ($batchMetadata === null) { + return null; + } + + return $this->batches[$subscriptionId] ??= SubscriberBatch::begin( + $subscriberAccessor->subscriber(), + $batchMetadata, + ); + } + + /** @param MetadataSubscriberAccessor $subscriberAccessor */ + private function resolveArgument( + MetadataSubscriberAccessor $subscriberAccessor, + SubscribeMethodMetadata $subscribeMethod, + ArgumentMetadata $argument, + ArgumentResolverContext $context, + SubscriberBatch|null $batch, + ): mixed { + if ($batch !== null && $argument->hasAttribute(BatchState::class)) { + return $batch->state; + } + + foreach ($this->argumentResolvers as $argumentResolver) { + if ($argumentResolver->support($argument, $context->message->event()::class)) { + return $argumentResolver->resolve($argument, $context); + } + } + + throw new NoSuitableResolver($subscriberAccessor->subscriber()::class, $subscribeMethod->name, $argument->name); + } } diff --git a/src/Test/TestError.php b/src/Test/TestError.php new file mode 100644 index 0000000..3c215be --- /dev/null +++ b/src/Test/TestError.php @@ -0,0 +1,11 @@ + $context */ + public function normalize(mixed $value, array $context): string { if (!$value instanceof Email) { throw new InvalidArgumentException(); @@ -23,7 +24,8 @@ public function normalize(mixed $value): string return $value->toString(); } - public function denormalize(mixed $value): Email|null + /** @param array $context */ + public function denormalize(mixed $value, array $context): Email|null { if ($value === null) { return null; diff --git a/tests/Unit/Fixture/Hotel/CheckIn.php b/tests/Unit/Fixture/Hotel/CheckIn.php new file mode 100644 index 0000000..8135ee3 --- /dev/null +++ b/tests/Unit/Fixture/Hotel/CheckIn.php @@ -0,0 +1,14 @@ +read(new HotelExists($command->hotelId))) { + throw new HotelError('Hotel does not exist'); + } + + if ($decision->read(new GuestAlreadyCheckedIn($command->hotelId, $command->guestName))) { + throw new HotelError(sprintf('Guest "%s" already checked in', $command->guestName)); + } + + $decision->append([new GuestIsCheckedIn($command->hotelId, $command->guestName)]); + + $notifier?->notify(); + } +} diff --git a/tests/Unit/Fixture/Hotel/CheckInWithFactoryHandler.php b/tests/Unit/Fixture/Hotel/CheckInWithFactoryHandler.php new file mode 100644 index 0000000..abb5411 --- /dev/null +++ b/tests/Unit/Fixture/Hotel/CheckInWithFactoryHandler.php @@ -0,0 +1,26 @@ +decisionFactory->begin(); + + if (!$decision->read(new HotelExists($command->hotelId))) { + throw new HotelError('Hotel does not exist'); + } + + $decision->append([new GuestIsCheckedIn($command->hotelId, $command->guestName)]); + } +} diff --git a/tests/Unit/Fixture/Hotel/GuestAlreadyCheckedIn.php b/tests/Unit/Fixture/Hotel/GuestAlreadyCheckedIn.php new file mode 100644 index 0000000..3313101 --- /dev/null +++ b/tests/Unit/Fixture/Hotel/GuestAlreadyCheckedIn.php @@ -0,0 +1,35 @@ + */ +final class GuestAlreadyCheckedIn extends BasicProjection +{ + public function __construct( + private readonly HotelId $hotelId, + private readonly string $guestName, + ) { + } + + public function initialState(): bool + { + return false; + } + + /** @return list */ + protected function tagFilter(): array + { + return ['hotel:' . $this->hotelId->toString(), 'guest:' . $this->guestName]; + } + + #[Apply] + public function applyGuestIsCheckedIn(bool $state, GuestIsCheckedIn $event): bool + { + return true; + } +} diff --git a/tests/Unit/Fixture/Hotel/GuestIsCheckedIn.php b/tests/Unit/Fixture/Hotel/GuestIsCheckedIn.php new file mode 100644 index 0000000..580036b --- /dev/null +++ b/tests/Unit/Fixture/Hotel/GuestIsCheckedIn.php @@ -0,0 +1,20 @@ +> */ +final class GuestNames extends BasicProjection +{ + public function __construct( + private readonly HotelId $hotelId, + ) { + } + + /** @return list */ + public function initialState(): array + { + return []; + } + + /** @return list */ + protected function tagFilter(): array + { + return ['hotel:' . $this->hotelId->toString()]; + } + + /** + * @param list $state + * + * @return list + */ + #[Apply] + public function applyGuestIsCheckedIn(array $state, GuestIsCheckedIn $event): array + { + return [...$state, $event->guestName]; + } +} diff --git a/tests/Unit/Fixture/Hotel/HotelCreated.php b/tests/Unit/Fixture/Hotel/HotelCreated.php new file mode 100644 index 0000000..ee200f2 --- /dev/null +++ b/tests/Unit/Fixture/Hotel/HotelCreated.php @@ -0,0 +1,18 @@ + */ +final class HotelExists extends BasicProjection +{ + public function __construct( + private readonly HotelId $hotelId, + ) { + } + + public function initialState(): bool + { + return false; + } + + /** @return list */ + protected function tagFilter(): array + { + return ['hotel:' . $this->hotelId->toString()]; + } + + #[Apply] + public function applyHotelCreated(bool $state, HotelCreated $event): bool + { + return true; + } +} diff --git a/tests/Unit/Fixture/Hotel/HotelExistsInStream.php b/tests/Unit/Fixture/Hotel/HotelExistsInStream.php new file mode 100644 index 0000000..c89b663 --- /dev/null +++ b/tests/Unit/Fixture/Hotel/HotelExistsInStream.php @@ -0,0 +1,40 @@ + */ +final class HotelExistsInStream extends BasicProjection +{ + public function __construct( + private readonly HotelId $hotelId, + private readonly string $stream, + ) { + } + + public function initialState(): bool + { + return false; + } + + /** @return list */ + protected function tagFilter(): array + { + return ['hotel:' . $this->hotelId->toString()]; + } + + protected function streamName(): string + { + return $this->stream; + } + + #[Apply] + public function applyHotelCreated(bool $state, HotelCreated $event): bool + { + return true; + } +} diff --git a/tests/Unit/Fixture/Hotel/HotelId.php b/tests/Unit/Fixture/Hotel/HotelId.php new file mode 100644 index 0000000..9e5bba5 --- /dev/null +++ b/tests/Unit/Fixture/Hotel/HotelId.php @@ -0,0 +1,13 @@ +> */ + public array $flushed = []; + + /** @var list> */ + public array $rolledBack = []; + + /** @return ArrayObject */ + #[BatchBegin] + public function begin(): ArrayObject + { + $this->begun++; + + return new ArrayObject(); + } + + /** @param ArrayObject $batch */ + #[Subscribe(ProfileCreated::class)] + public function run( + ProfileCreated $event, + #[BatchState] + ArrayObject $batch, + ): void { + if ($event->profileId->toString() === 'fail') { + throw new ProfileError('failed'); + } + + $batch->append($event->profileId->toString()); + } + + /** @param ArrayObject $batch */ + #[BatchFlush] + public function flush(ArrayObject $batch): void + { + $this->flushed[] = array_values($batch->getArrayCopy()); + } + + /** @param ArrayObject $batch */ + #[BatchRollback] + public function rollback(ArrayObject $batch): void + { + $this->rolledBack[] = array_values($batch->getArrayCopy()); + } +} diff --git a/tests/Unit/Fixture/ProfileId.php b/tests/Unit/Fixture/ProfileId.php index fe57344..804c105 100644 --- a/tests/Unit/Fixture/ProfileId.php +++ b/tests/Unit/Fixture/ProfileId.php @@ -4,16 +4,16 @@ namespace Patchlevel\EventSourcing\PhpUnit\Tests\Unit\Fixture; -use Patchlevel\EventSourcing\Aggregate\AggregateRootId; +use Patchlevel\EventSourcing\Identifier\Identifier; -final class ProfileId implements AggregateRootId +final class ProfileId implements Identifier { private function __construct( private string $id, ) { } - public static function fromString(string $id): self + public static function fromString(string $id): static { return new self($id); } diff --git a/tests/Unit/Test/DecisionTestCaseTest.php b/tests/Unit/Test/DecisionTestCaseTest.php new file mode 100644 index 0000000..f54461c --- /dev/null +++ b/tests/Unit/Test/DecisionTestCaseTest.php @@ -0,0 +1,569 @@ +hotelId = new HotelId('1'); + $this->otherHotelId = new HotelId('2'); + } + + public function testCommandIsHandledWithDecision(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(new CheckIn($this->hotelId, 'David')) + ->then(new GuestIsCheckedIn($this->hotelId, 'David')); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testGivenReplacesPreviousGiven(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->otherHotelId)) + ->given(new HotelCreated($this->hotelId)) + ->when(new CheckIn($this->hotelId, 'David')) + ->then(new GuestIsCheckedIn($this->hotelId, 'David')); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testGivenEventsAreTagged(): void + { + $test = $this->tester(); + + $test + ->given( + new HotelCreated($this->hotelId), + new GuestIsCheckedIn($this->hotelId, 'David'), + ) + ->when(new CheckIn($this->hotelId, 'David')) + ->expectsException(HotelError::class) + ->expectsExceptionMessage('Guest "David" already checked in'); + + $test->assert(); + self::assertSame(2, $test::getCount()); + } + + public function testGivenEventsOfAnotherBoundaryAreIgnored(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->otherHotelId)) + ->when(new CheckIn($this->hotelId, 'David')) + ->expectsExceptionMessage('Hotel does not exist'); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testGivenAcceptsMessagesWithCustomTagsAndStream(): void + { + $test = $this->tester(); + + $test + ->given( + Message::createWithHeaders(new HotelCreated($this->otherHotelId), [ + new TagsHeader(['hotel:1']), + new StreamNameHeader('hotels'), + ]), + ) + ->when(static function (Decision $decision): void { + self::assertTrue($decision->read(new HotelExists(new HotelId('1')))); + self::assertTrue($decision->read(new HotelExistsInStream(new HotelId('1'), 'hotels'))); + self::assertFalse($decision->read(new HotelExistsInStream(new HotelId('1'), 'main'))); + }) + ->then(); + + $test->assert(); + } + + public function testGivenEventsAreStoredInTheMainStream(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(function (Decision $decision): void { + self::assertTrue($decision->read(new HotelExistsInStream($this->hotelId, 'main'))); + }); + + $test->assert(); + } + + public function testAllMessagesOfAnAppendAreRecorded(): void + { + $test = $this->tester(); + + $test + ->when(function (Decision $decision): void { + $decision->append([new HotelCreated($this->hotelId), new HotelCreated($this->otherHotelId)]); + }) + ->then(new HotelCreated($this->hotelId), new HotelCreated($this->otherHotelId)); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testGivenMessagesGetDefaultStreamAndTags(): void + { + $test = $this->tester(); + + $test + ->given(Message::create(new HotelCreated($this->hotelId))) + ->when(new CheckIn($this->hotelId, 'David')) + ->then(new GuestIsCheckedIn($this->hotelId, 'David')); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testAppendedMessagesContainHeaders(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(new CheckIn($this->hotelId, 'David')); + + $messages = $test->appendedMessages(); + + self::assertCount(1, $messages); + self::assertEquals(new GuestIsCheckedIn($this->hotelId, 'David'), $messages[0]->event()); + self::assertSame('main', $messages[0]->header(StreamNameHeader::class)->streamName); + self::assertSame(['hotel:1', 'guest:David'], $messages[0]->header(TagsHeader::class)->tags); + + $test->then(new GuestIsCheckedIn($this->hotelId, 'David'))->assert(); + } + + public function testAppendedMessagesUseTheStreamNameOfTheDecision(): void + { + $test = $this->tester(); + + $test->when(function (Decision $decision): void { + $decision->append([new HotelCreated($this->hotelId)], 'hotels'); + }); + + self::assertSame('hotels', $test->appendedMessages()[0]->header(StreamNameHeader::class)->streamName); + $test->then(new HotelCreated($this->hotelId))->assert(); + } + + public function testExtraParametersArePassedToTheHandler(): void + { + $notifier = $this->createMock(Notifier::class); + $notifier->expects(self::once())->method('notify'); + + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(new CheckIn($this->hotelId, 'David'), $notifier) + ->then(new GuestIsCheckedIn($this->hotelId, 'David')); + + $test->assert(); + } + + public function testEveryDecisionParameterGetsANewDecision(): void + { + $test = new class ($this->name()) extends DecisionTestCase { + /** @return iterable */ + protected function handlers(): iterable + { + return [ + new class { + #[Handle] + public function __invoke(CheckIn $command, Decision $first, string $token, Decision $second): void + { + self::assertNotSame($first, $second); + $first->append([new GuestIsCheckedIn($command->hotelId, $token)]); + } + + private static function assertNotSame(object $first, object $second): void + { + TestCase::assertNotSame($first, $second); + } + }, + ]; + } + }; + + $test + ->when(new CheckIn($this->hotelId, 'David'), 'a-token') + ->then(new GuestIsCheckedIn($this->hotelId, 'a-token')); + + $test->assert(); + } + + public function testMissingExtraParameterFailsWithArgumentCountError(): void + { + $test = new class ($this->name()) extends DecisionTestCase { + /** @return iterable */ + protected function handlers(): iterable + { + return [ + new class { + #[Handle] + public function __invoke(CheckIn $command, string $token): void + { + } + }, + ]; + } + }; + + $test + ->when(new CheckIn($this->hotelId, 'David')) + ->expectsExceptionMessage('Too few arguments'); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testCommandWithoutHandler(): void + { + $test = new class ($this->name()) extends DecisionTestCase { + }; + + $test + ->when(new CheckIn($this->hotelId, 'David')) + ->expectsException(HandlerNotFound::class); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testClosureReceivesDecision(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(fn (Decision $decision) => (new CheckInHandler())(new CheckIn($this->hotelId, 'David'), $decision)) + ->then(new GuestIsCheckedIn($this->hotelId, 'David')); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testHandlerWithInjectedDecisionFactory(): void + { + $test = $this->tester(); + $handler = new CheckInWithFactoryHandler($test->decisionFactory()); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(fn () => $handler(new CheckIn($this->hotelId, 'David'))) + ->then(new GuestIsCheckedIn($this->hotelId, 'David')); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testNothingAppendedWhenNoThenGiven(): void + { + $test = $this->tester(); + + $test->when(static fn () => null); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testUnexpectedAppendFails(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(new CheckIn($this->hotelId, 'David')); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('The appended events doesn\'t match the expected events.'); + + $test->assert(); + } + + public function testGivenAndConcurrentEventsAreNotPartOfTheAppendedEvents(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->concurrently(new HotelCreated($this->otherHotelId)) + ->when(new CheckIn($this->hotelId, 'David')) + ->then(new GuestIsCheckedIn($this->hotelId, 'David')); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testConflictWithConcurrentEventInsideTheBoundary(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->concurrently(new GuestIsCheckedIn($this->hotelId, 'David')) + ->when(new CheckIn($this->hotelId, 'David')) + ->expectsConflict(); + + $test->assert(); + self::assertSame(1, $test::getCount()); + self::assertSame([], $test->appendedMessages()); + } + + public function testNoConflictWithConcurrentEventOutsideTheBoundary(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->concurrently(new GuestIsCheckedIn($this->hotelId, 'Eve')) + ->when(new CheckIn($this->hotelId, 'David')) + ->expectsConflict(); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage(AppendConditionNotMet::class); + + $test->assert(); + } + + public function testConcurrentMessagesAreTagged(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->concurrently(Message::create(new GuestIsCheckedIn($this->hotelId, 'David'))) + ->when(new CheckIn($this->hotelId, 'David')) + ->expectsConflict(); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testConcurrentEventsAreAppendedOnlyOnce(): void + { + $test = $this->tester(); + + $test + ->concurrently(new HotelCreated($this->hotelId)) + ->when(static function (Decision $decision) use ($test): void { + $decision->append([new HotelCreated(new HotelId('3'))]); + $test->decisionFactory()->begin()->append([new HotelCreated(new HotelId('4'))]); + }) + ->then( + new HotelCreated(new HotelId('3')), + new HotelCreated(new HotelId('4')), + static fn (Decision $decision) => self::assertTrue($decision->read(new HotelExists(new HotelId('1')))), + ); + + $test->assert(); + self::assertSame(2, $test::getCount()); + } + + public function testThenCallbackReadsTheStateAfterTheAppend(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(new CheckIn($this->hotelId, 'David')) + ->then( + fn (Decision $decision) => self::assertTrue($decision->read(new GuestAlreadyCheckedIn($this->hotelId, 'David'))), + new GuestIsCheckedIn($this->hotelId, 'David'), + fn (Decision $decision) => self::assertFalse($decision->read(new GuestAlreadyCheckedIn($this->hotelId, 'Eve'))), + ); + + $test->assert(); + self::assertSame(3, $test::getCount()); + } + + public function testThenCallbackFailureNamesTheCallback(): void + { + $test = $this->tester(); + + $test + ->when(static fn () => null) + ->then(static function (): void { + throw new HotelError('callback failed'); + }); + + try { + $test->assert(); + } catch (AssertionFailedError $error) { + self::assertStringContainsString('then() callback defined in ' . __FILE__, $error->getMessage()); + self::assertStringContainsString('failed: callback failed', $error->getMessage()); + + return; + } + + self::fail('The callback failure was not reported.'); + } + + public function testUnexpectedExceptionIsThrown(): void + { + $test = $this->tester(); + + $test->when(new CheckIn($this->hotelId, 'David')); + + $this->expectException(HotelError::class); + $this->expectExceptionMessage('Hotel does not exist'); + + $test->assert(); + } + + public function testExpectedExceptionNotThrown(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(new CheckIn($this->hotelId, 'David')) + ->expectsException(HotelError::class); + + $this->expectException(AssertionFailedError::class); + + $test->assert(); + } + + public function testNoWhenProvided(): void + { + $test = $this->tester(); + + $this->expectException(NoWhenProvided::class); + + $test->assert(); + } + + public function testGivenAfterWhenFails(): void + { + $test = $this->tester(); + $test->when(static fn () => null); + + $this->expectException(WhenAlreadyCalled::class); + + $test->given(new HotelCreated($this->hotelId)); + } + + public function testConcurrentlyAfterWhenFails(): void + { + $test = $this->tester(); + $test->when(static fn () => null); + + $this->expectException(WhenAlreadyCalled::class); + + $test->concurrently(new HotelCreated($this->hotelId)); + } + + public function testWhenTwiceFails(): void + { + $test = $this->tester(); + $test->when(static fn () => null); + + $this->expectException(WhenAlreadyCalled::class); + + $test->when(static fn () => null); + } + + public function testResetStartsWithAnEmptyStore(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->concurrently(new GuestIsCheckedIn($this->hotelId, 'David')) + ->when(new CheckIn($this->hotelId, 'David')) + ->then(new GuestIsCheckedIn($this->hotelId, 'Wrong')) + ->expectsExceptionMessage('never thrown') + ->expectsConflict(); + + $test->reset(); + + self::assertSame([], $test->appendedMessages()); + + $test + ->when(static function (Decision $decision): void { + self::assertFalse($decision->read(new HotelExists(new HotelId('1')))); + }); + + $test->assert(); + } + + public function testResetClearsGivenAndConcurrentEvents(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->concurrently(new HotelCreated($this->otherHotelId)); + + $test->reset(); + + $test->when(function (Decision $decision): void { + self::assertFalse($decision->read(new HotelExists($this->hotelId))); + $decision->append([new GuestIsCheckedIn($this->hotelId, 'David')]); + })->then( + new GuestIsCheckedIn($this->hotelId, 'David'), + fn (Decision $decision) => self::assertFalse($decision->read(new HotelExists($this->otherHotelId))), + ); + + $test->assert(); + } + + private function tester(): DecisionTestCase + { + return new class ($this->name()) extends DecisionTestCase { + /** @return iterable */ + protected function handlers(): iterable + { + return [new CheckInHandler()]; + } + }; + } +} diff --git a/tests/Unit/Test/NoThenProvidedTest.php b/tests/Unit/Test/NoThenProvidedTest.php new file mode 100644 index 0000000..7ae3778 --- /dev/null +++ b/tests/Unit/Test/NoThenProvidedTest.php @@ -0,0 +1,22 @@ +getMessage(), + ); + } +} diff --git a/tests/Unit/Test/ProjectionTestCaseTest.php b/tests/Unit/Test/ProjectionTestCaseTest.php new file mode 100644 index 0000000..72b4eec --- /dev/null +++ b/tests/Unit/Test/ProjectionTestCaseTest.php @@ -0,0 +1,346 @@ +hotelId = new HotelId('1'); + $this->otherHotelId = new HotelId('2'); + } + + public function testInitialState(): void + { + $test = $this->tester(); + + $test + ->when(new HotelExists($this->hotelId)) + ->then(false); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testAppliesGivenEvents(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(new HotelExists($this->hotelId)) + ->then(true); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testEventsOutsideTheTagFilterAreIgnored(): void + { + $test = $this->tester(); + + $test + ->given( + new GuestIsCheckedIn($this->hotelId, 'David'), + new GuestIsCheckedIn($this->otherHotelId, 'Eve'), + new GuestIsCheckedIn($this->hotelId, 'Daniel'), + ) + ->when(new GuestNames($this->hotelId)) + ->then(['David', 'Daniel']); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testAcceptsMessages(): void + { + $test = $this->tester(); + + $test + ->given(Message::createWithHeaders(new HotelCreated($this->otherHotelId), [new TagsHeader(['hotel:1'])])) + ->when(new HotelExists($this->hotelId)) + ->then(true); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testSeveralProjectionsAtOnce(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when([ + 'exists' => new HotelExists($this->hotelId), + 'guest' => new GuestAlreadyCheckedIn($this->hotelId, 'David'), + ]) + ->then(['exists' => true, 'guest' => false]); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testScalarStateIsComparedStrictly(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(new HotelExists($this->hotelId)) + ->then(1); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('The state doesn\'t match the expected state.'); + + $test->assert(); + } + + public function testObjectStateIsComparedByValue(): void + { + $projection = new class implements Projection { + public function initialState(): HotelId + { + return new HotelId('1'); + } + + public function apply(mixed $state, StoredMessage $message): mixed + { + return $state; + } + }; + + $test = $this->tester(); + + $test + ->when($projection) + ->then(new HotelId('1')); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testWrongArrayStateFails(): void + { + $test = $this->tester(); + + $test + ->given(new GuestIsCheckedIn($this->hotelId, 'David')) + ->when(new GuestNames($this->hotelId)) + ->then(['Eve']); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('The state doesn\'t match the expected state.'); + + $test->assert(); + } + + public function testThenCallbackReceivesState(): void + { + $test = $this->tester(); + + $test + ->given(new GuestIsCheckedIn($this->hotelId, 'David')) + ->when(new GuestNames($this->hotelId)) + ->then(static fn (array $state) => self::assertSame(['David'], $state)); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testThenNull(): void + { + $projection = new class implements Projection { + public function initialState(): mixed + { + return null; + } + + public function apply(mixed $state, StoredMessage $message): mixed + { + return $state; + } + }; + + $test = $this->tester(); + + $test->when($projection)->then(null); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testExceptionIsExpected(): void + { + $test = $this->tester(); + + $test + ->when($this->failingProjection()) + ->expectsException(HotelError::class); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + public function testUnexpectedExceptionIsThrown(): void + { + $test = $this->tester(); + + $test + ->when($this->failingProjection()) + ->then(null); + + $this->expectException(HotelError::class); + + $test->assert(); + } + + public function testExpectedExceptionNotThrown(): void + { + $test = $this->tester(); + + $test + ->when(new HotelExists($this->hotelId)) + ->expectsException(HotelError::class); + + $this->expectException(AssertionFailedError::class); + + $test->assert(); + } + + public function testNoWhenProvided(): void + { + $test = $this->tester(); + + $this->expectException(NoWhenProvided::class); + + $test->assert(); + } + + public function testNoThenProvided(): void + { + $test = $this->tester(); + $test->when(new HotelExists($this->hotelId)); + + $this->expectException(NoThenProvided::class); + + $test->assert(); + } + + public function testGivenAfterWhenFails(): void + { + $test = $this->tester(); + $test->when(new HotelExists($this->hotelId)); + + $this->expectException(WhenAlreadyCalled::class); + + $test->given(new HotelCreated($this->hotelId)); + } + + public function testWhenTwiceFails(): void + { + $test = $this->tester(); + $test->when(new HotelExists($this->hotelId)); + + $this->expectException(WhenAlreadyCalled::class); + + $test->when(new HotelExists($this->hotelId)); + } + + public function testReset(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when(new HotelExists($this->hotelId)) + ->then(true) + ->expectsException(HotelError::class) + ->expectsExceptionMessage('never thrown'); + + $test->reset(); + + $this->expectException(NoWhenProvided::class); + + $test->assert(); + } + + public function testResetClearsGivenEventsAndExpectations(): void + { + $test = $this->tester(); + + $test + ->given(new HotelCreated($this->hotelId)) + ->when($this->failingProjection()) + ->then(true) + ->expectsException(HotelError::class) + ->expectsExceptionMessage('never thrown'); + + $test->reset(); + + $test->when(new HotelExists($this->hotelId)); + + $this->expectException(NoThenProvided::class); + + $test->assert(); + } + + public function testResetClearsTheStateOfThePreviousRun(): void + { + $test = $this->tester(); + + $test->when(new HotelExists($this->hotelId))->then(false); + $test->reset(); + $test->given(new HotelCreated($this->hotelId))->when(new HotelExists($this->hotelId))->then(true); + + $test->assert(); + self::assertSame(1, $test::getCount()); + } + + /** @return Projection */ + private function failingProjection(): Projection + { + return new class implements Projection { + public function initialState(): mixed + { + throw new HotelError('failed'); + } + + public function apply(mixed $state, StoredMessage $message): mixed + { + return $state; + } + }; + } + + private function tester(): ProjectionTestCase + { + return new class ($this->name()) extends ProjectionTestCase { + }; + } +} diff --git a/tests/Unit/Test/SubscriberUtilitiesTest.php b/tests/Unit/Test/SubscriberUtilitiesTest.php index a56678b..6488bb3 100644 --- a/tests/Unit/Test/SubscriberUtilitiesTest.php +++ b/tests/Unit/Test/SubscriberUtilitiesTest.php @@ -4,21 +4,46 @@ namespace Patchlevel\EventSourcing\PhpUnit\Tests\Unit\Test; +use ArrayObject; use DateTimeImmutable; +use Patchlevel\EventSourcing\Attribute\BatchBegin; +use Patchlevel\EventSourcing\Attribute\BatchFlush; +use Patchlevel\EventSourcing\Attribute\BatchShouldFlush; +use Patchlevel\EventSourcing\Attribute\BatchState; +use Patchlevel\EventSourcing\Attribute\Partition; +use Patchlevel\EventSourcing\Attribute\PartitionKey; use Patchlevel\EventSourcing\Attribute\Projector; use Patchlevel\EventSourcing\Attribute\Setup; use Patchlevel\EventSourcing\Attribute\Subscribe; use Patchlevel\EventSourcing\Attribute\Teardown; use Patchlevel\EventSourcing\Message\Message; +use Patchlevel\EventSourcing\Metadata\Subscriber\ArgumentMetadata; +use Patchlevel\EventSourcing\PhpUnit\Test\SubscriberBatch; use Patchlevel\EventSourcing\PhpUnit\Test\SubscriberUtilities; use Patchlevel\EventSourcing\PhpUnit\Tests\Unit\Fixture\Email; +use Patchlevel\EventSourcing\PhpUnit\Tests\Unit\Fixture\Notifier; +use Patchlevel\EventSourcing\PhpUnit\Tests\Unit\Fixture\ProfileBatchSubscriber; use Patchlevel\EventSourcing\PhpUnit\Tests\Unit\Fixture\ProfileCreated; +use Patchlevel\EventSourcing\PhpUnit\Tests\Unit\Fixture\ProfileError; use Patchlevel\EventSourcing\PhpUnit\Tests\Unit\Fixture\ProfileId; +use Patchlevel\EventSourcing\PhpUnit\Tests\Unit\Fixture\ProfileVisited; use Patchlevel\EventSourcing\Store\Header\RecordedOnHeader; +use Patchlevel\EventSourcing\Store\Header\StreamNameHeader; +use Patchlevel\EventSourcing\Store\InMemoryStore; +use Patchlevel\EventSourcing\Subscription\Partitioner\StreamPartitioner; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\ArgumentResolver; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\ArgumentResolverContext; +use Patchlevel\EventSourcing\Subscription\Subscriber\ArgumentResolver\EventEmitterResolver; +use Patchlevel\EventSourcing\Subscription\Subscriber\EventEmitter\EventEmitter; +use Patchlevel\EventSourcing\Subscription\Subscriber\NoSuitableResolver; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +use stdClass; + +use function array_values; #[CoversClass(SubscriberUtilities::class)] +#[CoversClass(SubscriberBatch::class)] final class SubscriberUtilitiesTest extends TestCase { public function testRun(): void @@ -275,4 +300,389 @@ public function run(): void self::assertSame(0, $subscriber->called); self::assertSame(1, $subscriber2->called); } + + public function testRunStopsAtUnresolvableArgument(): void + { + $subscriber = new #[Projector('test')] + class { + #[Subscribe(ProfileCreated::class)] + public function run(Notifier $notifier): void + { + } + }; + + $util = new SubscriberUtilities($subscriber); + + $this->expectException(NoSuitableResolver::class); + + $util->executeRun($this->profileCreated('1')); + } + + public function testCustomArgumentResolverIsUsedFirst(): void + { + $subscriber = new #[Projector('test')] + class { + public ProfileCreated|null $received = null; + + #[Subscribe(ProfileCreated::class)] + public function run(ProfileCreated $event): void + { + $this->received = $event; + } + }; + + $replaced = $this->profileCreated('replaced'); + + $resolver = new class ($replaced) implements ArgumentResolver { + public function __construct( + private readonly object $event, + ) { + } + + public function resolve(ArgumentMetadata $argument, ArgumentResolverContext $context): object + { + return $this->event; + } + + public function support(ArgumentMetadata $argument, string $eventClass): bool + { + return true; + } + }; + + $util = new SubscriberUtilities($subscriber, argumentResolvers: [$resolver]); + $util->executeRun($this->profileCreated('1')); + + self::assertSame($replaced, $subscriber->received); + } + + public function testEventEmitterCanBeResolvedWithTheResolverOfTheLibrary(): void + { + $subscriber = new #[Projector('test')] + class { + #[Subscribe(ProfileCreated::class)] + public function run(ProfileCreated $event, EventEmitter $eventEmitter): void + { + $eventEmitter->emit([new ProfileVisited($event->profileId)]); + } + }; + + $store = new InMemoryStore(); + + $util = new SubscriberUtilities($subscriber, argumentResolvers: [new EventEmitterResolver($store)]); + $util->executeRun($this->profileCreated('1')); + + $message = $store->load()->current(); + + self::assertNotNull($message); + self::assertEquals(new ProfileVisited(ProfileId::fromString('1')), $message->event()); + self::assertSame('subscription_test', $message->header(StreamNameHeader::class)->streamName); + } + + public function testBatchIsFlushedAtTheEndOfTheRun(): void + { + $subscriber = new ProfileBatchSubscriber(); + + $util = new SubscriberUtilities($subscriber); + $util->executeRun($this->profileCreated('1'), $this->profileCreated('2')); + + self::assertSame(1, $subscriber->begun); + self::assertSame([['1', '2']], $subscriber->flushed); + + $util->executeRun($this->profileCreated('3')); + + self::assertSame(2, $subscriber->begun); + self::assertSame([['1', '2'], ['3']], $subscriber->flushed); + } + + public function testBatchIgnoresEventsWithoutSubscribeMethod(): void + { + $subscriber = new ProfileBatchSubscriber(); + + $util = new SubscriberUtilities($subscriber); + $util->executeRun(new ProfileVisited(ProfileId::fromString('1'))); + + self::assertSame(0, $subscriber->begun); + self::assertSame([], $subscriber->flushed); + } + + public function testBatchIsRolledBackAndTheExceptionRethrown(): void + { + $subscriber = new ProfileBatchSubscriber(); + + $util = new SubscriberUtilities($subscriber); + + try { + $util->executeRun($this->profileCreated('1'), $this->profileCreated('fail')); + self::fail('The exception was not rethrown.'); + } catch (ProfileError) { + self::assertSame([['1']], $subscriber->rolledBack); + self::assertSame([], $subscriber->flushed); + } + + $util->executeRun($this->profileCreated('2')); + + self::assertSame(2, $subscriber->begun); + self::assertSame([['2']], $subscriber->flushed); + } + + public function testBatchWithoutRollbackMethodRethrowsTheException(): void + { + $subscriber = new #[Projector('test')] + class { + #[Subscribe(ProfileCreated::class)] + public function run(): void + { + throw new ProfileError('failed'); + } + + #[BatchFlush] + public function flush(): void + { + } + }; + + $util = new SubscriberUtilities($subscriber); + + $this->expectException(ProfileError::class); + + $util->executeRun($this->profileCreated('1')); + } + + public function testBatchIsFlushedAfterMessages(): void + { + $subscriber = new #[Projector('test')] + class { + /** @var list */ + public array $flushed = []; + + /** @return ArrayObject */ + #[BatchBegin] + public function begin(): ArrayObject + { + return new ArrayObject(); + } + + /** @param ArrayObject $batch */ + #[Subscribe(ProfileCreated::class)] + public function run( + ProfileCreated $event, + #[BatchState] + ArrayObject $batch, + ): void { + $batch->append($event->profileId->toString()); + } + + /** @param ArrayObject $batch */ + #[BatchFlush(afterMessages: 2)] + public function flush(ArrayObject $batch): void + { + $this->flushed[] = $batch->count(); + } + }; + + $util = new SubscriberUtilities($subscriber); + $util->executeRun( + $this->profileCreated('1'), + $this->profileCreated('2'), + $this->profileCreated('3'), + ); + + self::assertSame([2, 1], $subscriber->flushed); + } + + public function testBatchIsFlushedWhenTheSubscriberAsksForIt(): void + { + $subscriber = new #[Projector('test')] + class { + /** @var list */ + public array $flushed = []; + + /** @return ArrayObject */ + #[BatchBegin] + public function begin(): ArrayObject + { + return new ArrayObject(); + } + + /** @param ArrayObject $batch */ + #[Subscribe(ProfileCreated::class)] + public function run( + ProfileCreated $event, + #[BatchState] + ArrayObject $batch, + ): void { + $batch->append($event->profileId->toString()); + } + + /** @param ArrayObject $batch */ + #[BatchShouldFlush] + public function shouldFlush(ArrayObject $batch): bool + { + return $batch->count() === 1; + } + + /** @param ArrayObject $batch */ + #[BatchFlush] + public function flush(ArrayObject $batch): void + { + $this->flushed[] = $batch->count(); + } + }; + + $util = new SubscriberUtilities($subscriber); + $util->executeRun($this->profileCreated('1'), $this->profileCreated('2')); + + self::assertSame([1, 1], $subscriber->flushed); + } + + public function testBatchWithoutBeginMethodGetsAnEmptyState(): void + { + $subscriber = new #[Projector('test')] + class { + public object|null $state = null; + + #[Subscribe(ProfileCreated::class)] + public function run( + ProfileCreated $event, + #[BatchState] + object $state, + ): void { + $this->state = $state; + } + + #[BatchFlush] + public function flush(object $state): void + { + } + }; + + $util = new SubscriberUtilities($subscriber); + $util->executeRun($this->profileCreated('1')); + + self::assertEquals(new stdClass(), $subscriber->state); + } + + public function testBatchStateIsOnlyPassedToMarkedArguments(): void + { + $subscriber = new #[Projector('test')] + class { + public Message|null $message = null; + + #[Subscribe(ProfileCreated::class)] + public function run(Message $message): void + { + $this->message = $message; + } + + #[BatchFlush] + public function flush(object $state): void + { + } + }; + + $message = Message::create($this->profileCreated('1')); + + $util = new SubscriberUtilities($subscriber); + $util->executeRun($message); + + self::assertSame($message, $subscriber->message); + } + + public function testPartitionKeyIsResolved(): void + { + $subscriber = new #[Projector('test')] + #[Partition(new StreamPartitioner())] + class { + /** @var list */ + public array $keys = []; + + #[Subscribe(ProfileCreated::class)] + public function run( + #[PartitionKey] + string|null $key, + ): void { + $this->keys[] = $key; + } + }; + + $util = new SubscriberUtilities($subscriber); + $util->executeRun( + Message::createWithHeaders($this->profileCreated('1'), [new StreamNameHeader('profile-1')]), + Message::createWithHeaders($this->profileCreated('2'), [new StreamNameHeader('profile-2')]), + ); + + self::assertSame(['profile-1', 'profile-2'], $subscriber->keys); + } + + public function testPartitionerIsNotCalledForEventsWithoutSubscribeMethod(): void + { + $subscriber = new #[Projector('test')] + #[Partition(new StreamPartitioner())] + class { + public int $called = 0; + + #[Subscribe(ProfileCreated::class)] + public function run(): void + { + $this->called++; + } + }; + + $util = new SubscriberUtilities($subscriber); + $util->executeRun(new ProfileVisited(ProfileId::fromString('1'))); + + self::assertSame(0, $subscriber->called); + } + + public function testEveryPartitionHasItsOwnBatch(): void + { + $subscriber = new #[Projector('test')] + #[Partition(new StreamPartitioner())] + class { + /** @var list> */ + public array $flushed = []; + + /** @return ArrayObject */ + #[BatchBegin] + public function begin(): ArrayObject + { + return new ArrayObject(); + } + + /** @param ArrayObject $batch */ + #[Subscribe(ProfileCreated::class)] + public function run( + ProfileCreated $event, + #[BatchState] + ArrayObject $batch, + ): void { + $batch->append($event->profileId->toString()); + } + + /** @param ArrayObject $batch */ + #[BatchFlush] + public function flush(ArrayObject $batch): void + { + $this->flushed[] = array_values($batch->getArrayCopy()); + } + }; + + $util = new SubscriberUtilities($subscriber); + $util->executeRun( + Message::createWithHeaders($this->profileCreated('1'), [new StreamNameHeader('a')]), + Message::createWithHeaders($this->profileCreated('2'), [new StreamNameHeader('b')]), + Message::createWithHeaders($this->profileCreated('3'), [new StreamNameHeader('a')]), + ); + + self::assertSame([['1', '3'], ['2']], $subscriber->flushed); + } + + private function profileCreated(string $id): ProfileCreated + { + return new ProfileCreated( + ProfileId::fromString($id), + Email::fromString('hq@patchlevel.de'), + ); + } } diff --git a/tests/Unit/Test/WhenAlreadyCalledTest.php b/tests/Unit/Test/WhenAlreadyCalledTest.php new file mode 100644 index 0000000..67c26f9 --- /dev/null +++ b/tests/Unit/Test/WhenAlreadyCalledTest.php @@ -0,0 +1,22 @@ +getMessage(), + ); + } +}