From e9e85816ac229e9c0e82a8544c6c3feae02defa1 Mon Sep 17 00:00:00 2001 From: Pascal CESCON - Amoifr Date: Thu, 5 Nov 2026 11:15:46 +0100 Subject: [PATCH 1/2] Record the updates in the test environment and add MercureAssertionsTrait --- CHANGELOG.md | 5 + .../CompilerPass/RecordUpdatesPass.php | 65 +++++++++++ src/MercureBundle.php | 2 + src/Test/MercureAssertionsTrait.php | 70 ++++++++++++ src/Test/RecordingHub.php | 82 ++++++++++++++ src/Test/UpdateRecorder.php | 71 ++++++++++++ .../CompilerPass/RecordUpdatesPassTest.php | 99 +++++++++++++++++ tests/Test/MercureAssertionsTraitTest.php | 102 ++++++++++++++++++ 8 files changed, 496 insertions(+) create mode 100644 src/DependencyInjection/CompilerPass/RecordUpdatesPass.php create mode 100644 src/Test/MercureAssertionsTrait.php create mode 100644 src/Test/RecordingHub.php create mode 100644 src/Test/UpdateRecorder.php create mode 100644 tests/DependencyInjection/CompilerPass/RecordUpdatesPassTest.php create mode 100644 tests/Test/MercureAssertionsTraitTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index e2f6759..2a43049 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +0.8.0 +----- + +* Record the updates instead of publishing them when `framework.test` is enabled, and add `MercureAssertionsTrait` (`assertMercureUpdateCount()`, `assertMercureUpdatePublished()`, `getMercureUpdates()`, `getMercureUpdate()`) to test them from a `KernelTestCase` or a `WebTestCase` (#138) + 0.7.0 ----- diff --git a/src/DependencyInjection/CompilerPass/RecordUpdatesPass.php b/src/DependencyInjection/CompilerPass/RecordUpdatesPass.php new file mode 100644 index 0000000..2edc8e4 --- /dev/null +++ b/src/DependencyInjection/CompilerPass/RecordUpdatesPass.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Symfony\Bundle\MercureBundle\DependencyInjection\CompilerPass; + +use Symfony\Bundle\MercureBundle\Test\RecordingHub; +use Symfony\Bundle\MercureBundle\Test\UpdateRecorder; +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; + +/** + * Records the updates instead of publishing them when "framework.test" is enabled. + * + * @author Pascal Cescon + * + * @internal + */ +final class RecordUpdatesPass implements CompilerPassInterface +{ + public function process(ContainerBuilder $container): void + { + // registered by FrameworkBundle when "framework.test" is enabled + if (!$container->hasDefinition('test.service_container')) { + return; + } + + $hubs = []; + foreach ($container->findTaggedServiceIds('mercure.hub') as $hubId => $tags) { + if (!str_starts_with($hubId, 'mercure.hub.')) { + continue; + } + + $name = substr($hubId, \strlen('mercure.hub.')); + $hubs[] = $name; + + $container->register("$hubId.recording", RecordingHub::class) + // before the profiler's TraceableHub (priority 0), so that it still lists the updates + ->setDecoratedService($hubId, null, 1) + ->addArgument(new Reference("$hubId.recording.inner")) + ->addArgument(new Reference('mercure.test.update_recorder')) + ->addArgument($name); + } + + if (!$hubs) { + return; + } + + $container->register('mercure.test.update_recorder', UpdateRecorder::class) + // public, as the private services of the test container are only available once instantiated + ->setPublic(true) + ->addArgument($hubs) + ->addTag('kernel.reset', ['method' => 'reset']); + } +} diff --git a/src/MercureBundle.php b/src/MercureBundle.php index 9ef2b6d..b69bb81 100644 --- a/src/MercureBundle.php +++ b/src/MercureBundle.php @@ -13,6 +13,7 @@ namespace Symfony\Bundle\MercureBundle; +use Symfony\Bundle\MercureBundle\DependencyInjection\CompilerPass\RecordUpdatesPass; use Symfony\Bundle\MercureBundle\DependencyInjection\CompilerPass\StimulusHelperPass; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Compiler\PassConfig; @@ -30,6 +31,7 @@ public function build(ContainerBuilder $container): void parent::build($container); $container->addCompilerPass(new StimulusHelperPass()); + $container->addCompilerPass(new RecordUpdatesPass()); $container->addCompilerPass(new class implements CompilerPassInterface { public function process(ContainerBuilder $container): void diff --git a/src/Test/MercureAssertionsTrait.php b/src/Test/MercureAssertionsTrait.php new file mode 100644 index 0000000..53ad418 --- /dev/null +++ b/src/Test/MercureAssertionsTrait.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Symfony\Bundle\MercureBundle\Test; + +use Symfony\Component\Mercure\Update; + +/** + * Assertions on the Mercure updates published during a test, for KernelTestCase and WebTestCase. + * + * The updates are only recorded, never sent, when "framework.test" is enabled. + * + * @author Pascal Cescon + */ +trait MercureAssertionsTrait +{ + /** + * @param string|null $hub the name of the hub, null for all the hubs + */ + public static function assertMercureUpdateCount(int $count, ?string $hub = null, string $message = ''): void + { + self::assertCount($count, self::getMercureUpdates($hub), $message); + } + + /** + * @param string|null $hub the name of the hub, null for all the hubs + */ + public static function assertMercureUpdatePublished(string $topic, ?string $hub = null, string $message = ''): void + { + $topics = []; + foreach (self::getMercureUpdates($hub) as $update) { + array_push($topics, ...$update->getTopics()); + } + + self::assertContains($topic, $topics, $message); + } + + /** + * @param string|null $hub the name of the hub, null for all the hubs + * + * @return list in publishing order + */ + public static function getMercureUpdates(?string $hub = null): array + { + $container = static::getContainer(); + if (!$container->has('mercure.test.update_recorder')) { + static::fail('Mercure updates are only recorded when "framework.test" is enabled and at least one hub is configured.'); + } + + return $container->get('mercure.test.update_recorder')->getUpdates($hub); + } + + /** + * @param string|null $hub the name of the hub, null for all the hubs + */ + public static function getMercureUpdate(int $index = 0, ?string $hub = null): ?Update + { + return self::getMercureUpdates($hub)[$index] ?? null; + } +} diff --git a/src/Test/RecordingHub.php b/src/Test/RecordingHub.php new file mode 100644 index 0000000..a46f83b --- /dev/null +++ b/src/Test/RecordingHub.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Symfony\Bundle\MercureBundle\Test; + +use Symfony\Component\Mercure\HubInterface; +use Symfony\Component\Mercure\Jwt\TokenFactoryInterface; +use Symfony\Component\Mercure\ProtocolVersion; +use Symfony\Component\Mercure\RemoteHubInterface; +use Symfony\Component\Mercure\Update; + +/** + * Records the published updates instead of sending them to the hub. + * + * @author Pascal Cescon + * + * @internal + */ +final class RecordingHub implements RemoteHubInterface +{ + public function __construct( + private readonly HubInterface $hub, + private readonly UpdateRecorder $recorder, + private readonly string $name, + ) { + } + + public function getUrl(): string + { + if ($this->hub instanceof RemoteHubInterface) { + return $this->hub->getUrl(); + } + + throw new \LogicException(\sprintf('The "%s" Mercure hub is not a remote hub.', $this->name)); + } + + public function getPublicUrl(): string + { + return $this->hub->getPublicUrl(); + } + + public function getFactory(): ?TokenFactoryInterface + { + return $this->hub->getFactory(); + } + + public function getProtocolVersion(): ProtocolVersion + { + return $this->hub->getProtocolVersion(); + } + + public function getCookieName(): string + { + return $this->hub->getCookieName(); + } + + public function publish(Update $update): string + { + $this->recorder->record($this->name, $update); + + return $update->getId() ?? 'urn:uuid:'.self::uuid4(); + } + + private static function uuid4(): string + { + $bytes = random_bytes(16); + $bytes[6] = \chr(\ord($bytes[6]) & 0x0F | 0x40); + $bytes[8] = \chr(\ord($bytes[8]) & 0x3F | 0x80); + + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4)); + } +} diff --git a/src/Test/UpdateRecorder.php b/src/Test/UpdateRecorder.php new file mode 100644 index 0000000..d0b1373 --- /dev/null +++ b/src/Test/UpdateRecorder.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Symfony\Bundle\MercureBundle\Test; + +use Symfony\Component\Mercure\Update; +use Symfony\Contracts\Service\ResetInterface; + +/** + * Keeps the updates published to every hub when "framework.test" is enabled. + * + * @author Pascal Cescon + * + * @internal + */ +final class UpdateRecorder implements ResetInterface +{ + /** + * @var list + */ + private array $updates = []; + + /** + * @param list $hubs + */ + public function __construct( + private readonly array $hubs, + ) { + } + + public function record(string $hub, Update $update): void + { + $this->updates[] = [$hub, $update]; + } + + /** + * @throws \InvalidArgumentException when the hub is not defined + * + * @return list the updates of the given hub, or of all the hubs when null, in publishing order + */ + public function getUpdates(?string $hub = null): array + { + if (null !== $hub && !\in_array($hub, $this->hubs, true)) { + throw new \InvalidArgumentException(\sprintf('The "%s" Mercure hub is not defined. Defined hubs: "%s".', $hub, implode('", "', $this->hubs))); + } + + $updates = []; + foreach ($this->updates as [$name, $update]) { + if (null === $hub || $name === $hub) { + $updates[] = $update; + } + } + + return $updates; + } + + public function reset(): void + { + $this->updates = []; + } +} diff --git a/tests/DependencyInjection/CompilerPass/RecordUpdatesPassTest.php b/tests/DependencyInjection/CompilerPass/RecordUpdatesPassTest.php new file mode 100644 index 0000000..8b55381 --- /dev/null +++ b/tests/DependencyInjection/CompilerPass/RecordUpdatesPassTest.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Symfony\Bundle\MercureBundle\Tests\DependencyInjection\CompilerPass; + +use PHPUnit\Framework\TestCase; +use Symfony\Bundle\MercureBundle\DependencyInjection\CompilerPass\RecordUpdatesPass; +use Symfony\Bundle\MercureBundle\DependencyInjection\MercureExtension; +use Symfony\Bundle\MercureBundle\Test\RecordingHub; +use Symfony\Bundle\MercureBundle\Test\UpdateRecorder; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\Mercure\Debug\TraceableHub; +use Symfony\Component\Mercure\HubInterface; +use Symfony\Component\Mercure\RemoteHubInterface; +use Symfony\Component\Mercure\Update; +use Symfony\Component\Stopwatch\Stopwatch; + +final class RecordUpdatesPassTest extends TestCase +{ + public function testHubsAreLeftAloneWithoutFrameworkTest() + { + $container = $this->createContainer(false, false); + $container->compile(); + + $this->assertFalse($container->has('mercure.test.update_recorder')); + $this->assertNotInstanceOf(RecordingHub::class, $container->get('mercure.hub.default')); + } + + public function testUpdatesAreRecordedInsteadOfPublished() + { + $container = $this->createContainer(true, false); + $container->compile(); + + $hub = $container->get('mercure.hub.default'); + $this->assertInstanceOf(RecordingHub::class, $hub); + $this->assertInstanceOf(RemoteHubInterface::class, $container->get(RemoteHubInterface::class)); + $this->assertSame('https://demo.mercure.rocks/hub', $hub->getUrl()); + + $this->assertSame('urn:uuid:custom', $hub->publish(new Update('https://example.com/books/1', '{}', id: 'urn:uuid:custom'))); + $this->assertMatchesRegularExpression('/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $container->get('mercure.hub.other')->publish(new Update('https://example.com/books/2'))); + + $recorder = $container->get('mercure.test.update_recorder'); + $this->assertInstanceOf(UpdateRecorder::class, $recorder); + $this->assertSame(['https://example.com/books/1', 'https://example.com/books/2'], array_map(static fn (Update $update): string => $update->getTopics()[0], $recorder->getUpdates())); + $this->assertSame(['https://example.com/books/2'], $recorder->getUpdates('other')[0]->getTopics()); + $this->assertSame([['method' => 'reset']], $container->findDefinition('mercure.test.update_recorder')->getTag('kernel.reset')); + } + + public function testTheProfilerStillListsTheRecordedUpdates() + { + $container = $this->createContainer(true, true); + $container->compile(); + + $hub = $container->get('mercure.hub.default'); + $this->assertInstanceOf(TraceableHub::class, $hub); + $hub->publish(new Update('https://example.com/books/1')); + + $this->assertSame(1, $hub->count()); + $this->assertCount(1, $container->get('mercure.test.update_recorder')->getUpdates('default')); + } + + private function createContainer(bool $test, bool $debug): ContainerBuilder + { + $container = new ContainerBuilder(new ParameterBag(['kernel.debug' => $debug])); + (new MercureExtension())->load(['mercure' => ['hubs' => [ + 'default' => ['url' => 'https://demo.mercure.rocks/hub', 'jwt' => 'token'], + 'other' => ['url' => 'https://other.example.com/hub', 'jwt' => 'token'], + ]]], $container); + + // any request would fail the test: nothing must reach the hub + $container->register('http_client', MockHttpClient::class) + ->addArgument(static fn () => throw new \LogicException('No update must be sent to the hub.')); + if ($debug) { + $container->register('debug.stopwatch', Stopwatch::class); + } + if ($test) { + $container->register('test.service_container', \stdClass::class); + } + + $container->addCompilerPass(new RecordUpdatesPass()); + foreach ([HubInterface::class, RemoteHubInterface::class, 'mercure.hub.default', 'mercure.hub.other'] as $id) { + $container->hasAlias($id) ? $container->getAlias($id)->setPublic(true) : $container->getDefinition($id)->setPublic(true); + } + + return $container; + } +} diff --git a/tests/Test/MercureAssertionsTraitTest.php b/tests/Test/MercureAssertionsTraitTest.php new file mode 100644 index 0000000..73d56c4 --- /dev/null +++ b/tests/Test/MercureAssertionsTraitTest.php @@ -0,0 +1,102 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Symfony\Bundle\MercureBundle\Tests\Test; + +use PHPUnit\Framework\AssertionFailedError; +use PHPUnit\Framework\TestCase; +use Symfony\Bundle\MercureBundle\Test\MercureAssertionsTrait; +use Symfony\Bundle\MercureBundle\Test\UpdateRecorder; +use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\Mercure\Update; + +final class MercureAssertionsTraitTest extends TestCase +{ + use MercureAssertionsTrait; + + private static ?Container $container = null; + + protected function setUp(): void + { + $recorder = new UpdateRecorder(['default', 'other']); + $recorder->record('default', new Update('https://example.com/books/1', '{"title":"Dune"}')); + $recorder->record('other', new Update(['https://example.com/books/2', 'https://example.com/authors/1'])); + + self::$container = new Container(); + self::$container->set('mercure.test.update_recorder', $recorder); + } + + protected function tearDown(): void + { + self::$container = null; + } + + protected static function getContainer(): ContainerInterface + { + return self::$container; + } + + public function testAssertMercureUpdateCount() + { + self::assertMercureUpdateCount(2); + self::assertMercureUpdateCount(1, 'default'); + self::assertMercureUpdateCount(1, 'other'); + + $this->expectException(AssertionFailedError::class); + self::assertMercureUpdateCount(2, 'default'); + } + + public function testAssertMercureUpdatePublished() + { + self::assertMercureUpdatePublished('https://example.com/books/1'); + self::assertMercureUpdatePublished('https://example.com/authors/1', 'other'); + + $this->expectException(AssertionFailedError::class); + self::assertMercureUpdatePublished('https://example.com/books/1', 'other'); + } + + public function testGetMercureUpdate() + { + $this->assertSame('{"title":"Dune"}', self::getMercureUpdate()->getData()); + $this->assertSame(['https://example.com/books/2', 'https://example.com/authors/1'], self::getMercureUpdate(1)->getTopics()); + $this->assertSame(['https://example.com/books/2', 'https://example.com/authors/1'], self::getMercureUpdate(0, 'other')->getTopics()); + $this->assertNull(self::getMercureUpdate(2)); + $this->assertNull(self::getMercureUpdate(-1)); + } + + public function testUnknownHubThrows() + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "unknown" Mercure hub is not defined. Defined hubs: "default", "other".'); + + self::getMercureUpdates('unknown'); + } + + public function testFailsWithoutRecorder() + { + self::$container = new Container(); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('Mercure updates are only recorded when "framework.test" is enabled'); + + self::getMercureUpdates(); + } + + public function testResetForgetsTheUpdates() + { + self::getContainer()->get('mercure.test.update_recorder')->reset(); + + self::assertMercureUpdateCount(0); + } +} From 69d80c75a8ba817222d20f2903e5329d80ddfb83 Mon Sep 17 00:00:00 2001 From: Pascal CESCON - Amoifr Date: Thu, 5 Nov 2026 11:45:28 +0100 Subject: [PATCH 2/2] Add the record_updates_in_test hub option, for end-to-end tests that need a real hub --- CHANGELOG.md | 2 +- .../CompilerPass/RecordUpdatesPass.php | 2 +- src/DependencyInjection/Configuration.php | 4 +++ src/DependencyInjection/MercureExtension.php | 2 +- src/Test/MercureAssertionsTrait.php | 2 +- src/Test/UpdateRecorder.php | 4 +-- .../CompilerPass/RecordUpdatesPassTest.php | 32 +++++++++++++++++-- .../DependencyInjection/ConfigurationTest.php | 1 + tests/Test/MercureAssertionsTraitTest.php | 2 +- 9 files changed, 41 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a43049..74b8585 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ CHANGELOG 0.8.0 ----- -* Record the updates instead of publishing them when `framework.test` is enabled, and add `MercureAssertionsTrait` (`assertMercureUpdateCount()`, `assertMercureUpdatePublished()`, `getMercureUpdates()`, `getMercureUpdate()`) to test them from a `KernelTestCase` or a `WebTestCase` (#138) +* Record the updates instead of publishing them when `framework.test` is enabled, and add `MercureAssertionsTrait` (`assertMercureUpdateCount()`, `assertMercureUpdatePublished()`, `getMercureUpdates()`, `getMercureUpdate()`) to test them from a `KernelTestCase` or a `WebTestCase` (#138). **Behavior change:** end-to-end tests that need a real hub in the test environment, e.g. with Symfony Panther, must set the new `record_updates_in_test` hub option to `false` 0.7.0 ----- diff --git a/src/DependencyInjection/CompilerPass/RecordUpdatesPass.php b/src/DependencyInjection/CompilerPass/RecordUpdatesPass.php index 2edc8e4..3bff63c 100644 --- a/src/DependencyInjection/CompilerPass/RecordUpdatesPass.php +++ b/src/DependencyInjection/CompilerPass/RecordUpdatesPass.php @@ -37,7 +37,7 @@ public function process(ContainerBuilder $container): void $hubs = []; foreach ($container->findTaggedServiceIds('mercure.hub') as $hubId => $tags) { - if (!str_starts_with($hubId, 'mercure.hub.')) { + if (!str_starts_with($hubId, 'mercure.hub.') || !($tags[0]['record_updates_in_test'] ?? true)) { continue; } diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 304eb35..229b808 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -56,6 +56,10 @@ public function getConfigTreeBuilder(): TreeBuilder ->scalarNode('cookie_name') ->defaultNull() ->info('Name of the subscriber authorization cookie. Defaults to a value computed from "protocol_version" when not set: "__Secure-mercure_access_token" for "1.0" ("mercure_access_token" in debug mode, matching the hub\'s "playground" mode), "mercureAuthorization" for "0.x".') + ->end() + ->booleanNode('record_updates_in_test') + ->defaultTrue() + ->info('Record the updates instead of publishing them when "framework.test" is enabled, to test them with MercureAssertionsTrait. Disable it for end-to-end tests that need a real hub, e.g. with Symfony Panther.') ->end() ->end() // "jwt", "publisher" and "subscriber" validate their own options diff --git a/src/DependencyInjection/MercureExtension.php b/src/DependencyInjection/MercureExtension.php index 78d6ad2..ef7104b 100644 --- a/src/DependencyInjection/MercureExtension.php +++ b/src/DependencyInjection/MercureExtension.php @@ -157,7 +157,7 @@ public function load(array $configs, ContainerBuilder $container): void ->addArgument(isset($hub['http_client']) ? new Reference($hub['http_client']) : new Reference('http_client', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)) ->addArgument($cookieName) ->addArgument($protocolVersion) - ->addTag('mercure.hub'); + ->addTag('mercure.hub', ['record_updates_in_test' => $hub['record_updates_in_test']]); $container->registerAliasForArgument($hubId, HubInterface::class, "{$name}Hub"); $container->registerAliasForArgument($hubId, HubInterface::class, $name); diff --git a/src/Test/MercureAssertionsTrait.php b/src/Test/MercureAssertionsTrait.php index 53ad418..eb07730 100644 --- a/src/Test/MercureAssertionsTrait.php +++ b/src/Test/MercureAssertionsTrait.php @@ -54,7 +54,7 @@ public static function getMercureUpdates(?string $hub = null): array { $container = static::getContainer(); if (!$container->has('mercure.test.update_recorder')) { - static::fail('Mercure updates are only recorded when "framework.test" is enabled and at least one hub is configured.'); + static::fail('Mercure updates are only recorded when "framework.test" is enabled and at least one hub has its "record_updates_in_test" option enabled.'); } return $container->get('mercure.test.update_recorder')->getUpdates($hub); diff --git a/src/Test/UpdateRecorder.php b/src/Test/UpdateRecorder.php index d0b1373..7285129 100644 --- a/src/Test/UpdateRecorder.php +++ b/src/Test/UpdateRecorder.php @@ -44,14 +44,14 @@ public function record(string $hub, Update $update): void } /** - * @throws \InvalidArgumentException when the hub is not defined + * @throws \InvalidArgumentException when the hub doesn't record its updates * * @return list the updates of the given hub, or of all the hubs when null, in publishing order */ public function getUpdates(?string $hub = null): array { if (null !== $hub && !\in_array($hub, $this->hubs, true)) { - throw new \InvalidArgumentException(\sprintf('The "%s" Mercure hub is not defined. Defined hubs: "%s".', $hub, implode('", "', $this->hubs))); + throw new \InvalidArgumentException(\sprintf('The "%s" Mercure hub does not record its updates: it is not defined or its "record_updates_in_test" option is disabled. Recording hubs: "%s".', $hub, implode('", "', $this->hubs))); } $updates = []; diff --git a/tests/DependencyInjection/CompilerPass/RecordUpdatesPassTest.php b/tests/DependencyInjection/CompilerPass/RecordUpdatesPassTest.php index 8b55381..61d4d79 100644 --- a/tests/DependencyInjection/CompilerPass/RecordUpdatesPassTest.php +++ b/tests/DependencyInjection/CompilerPass/RecordUpdatesPassTest.php @@ -71,12 +71,38 @@ public function testTheProfilerStillListsTheRecordedUpdates() $this->assertCount(1, $container->get('mercure.test.update_recorder')->getUpdates('default')); } - private function createContainer(bool $test, bool $debug): ContainerBuilder + public function testHubsCanOptOut() + { + $container = $this->createContainer(true, false, ['record_updates_in_test' => false]); + $container->compile(); + + $this->assertInstanceOf(RecordingHub::class, $container->get('mercure.hub.default')); + $this->assertNotInstanceOf(RecordingHub::class, $container->get('mercure.hub.other')); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Recording hubs: "default".'); + $container->get('mercure.test.update_recorder')->getUpdates('other'); + } + + public function testNoRecorderWhenEveryHubOptsOut() + { + $container = $this->createContainer(true, false, ['record_updates_in_test' => false], ['record_updates_in_test' => false]); + $container->compile(); + + $this->assertFalse($container->has('mercure.test.update_recorder')); + $this->assertNotInstanceOf(RecordingHub::class, $container->get('mercure.hub.default')); + } + + /** + * @param array $otherHub + * @param array $defaultHub + */ + private function createContainer(bool $test, bool $debug, array $otherHub = [], array $defaultHub = []): ContainerBuilder { $container = new ContainerBuilder(new ParameterBag(['kernel.debug' => $debug])); (new MercureExtension())->load(['mercure' => ['hubs' => [ - 'default' => ['url' => 'https://demo.mercure.rocks/hub', 'jwt' => 'token'], - 'other' => ['url' => 'https://other.example.com/hub', 'jwt' => 'token'], + 'default' => ['url' => 'https://demo.mercure.rocks/hub', 'jwt' => 'token'] + $defaultHub, + 'other' => ['url' => 'https://other.example.com/hub', 'jwt' => 'token'] + $otherHub, ]]], $container); // any request would fail the test: nothing must reach the hub diff --git a/tests/DependencyInjection/ConfigurationTest.php b/tests/DependencyInjection/ConfigurationTest.php index aaa3b10..148166a 100644 --- a/tests/DependencyInjection/ConfigurationTest.php +++ b/tests/DependencyInjection/ConfigurationTest.php @@ -64,6 +64,7 @@ public function testProtocolVersionDefaultsToV1Value() $this->assertSame(ProtocolVersion::V1, $config['hubs']['default']['protocol_version']); $this->assertNull($config['hubs']['default']['cookie_name']); + $this->assertTrue($config['hubs']['default']['record_updates_in_test']); } public function testProtocolVersionAcceptsExplicit10() diff --git a/tests/Test/MercureAssertionsTraitTest.php b/tests/Test/MercureAssertionsTraitTest.php index 73d56c4..70732a3 100644 --- a/tests/Test/MercureAssertionsTraitTest.php +++ b/tests/Test/MercureAssertionsTraitTest.php @@ -78,7 +78,7 @@ public function testGetMercureUpdate() public function testUnknownHubThrows() { $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "unknown" Mercure hub is not defined. Defined hubs: "default", "other".'); + $this->expectExceptionMessage('The "unknown" Mercure hub does not record its updates: it is not defined or its "record_updates_in_test" option is disabled. Recording hubs: "default", "other".'); self::getMercureUpdates('unknown'); }