Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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). **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
-----

Expand Down
65 changes: 65 additions & 0 deletions src/DependencyInjection/CompilerPass/RecordUpdatesPass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

/*
* This file is part of the Mercure Component project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* 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 <pascal.cescon@gmail.com>
*
* @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.') || !($tags[0]['record_updates_in_test'] ?? true)) {
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']);
}
}
4 changes: 4 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/DependencyInjection/MercureExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions src/MercureBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down
70 changes: 70 additions & 0 deletions src/Test/MercureAssertionsTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

/*
* This file is part of the Mercure Component project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* 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 <pascal.cescon@gmail.com>
*/
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<Update> 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 has its "record_updates_in_test" option enabled.');
}

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;
}
}
82 changes: 82 additions & 0 deletions src/Test/RecordingHub.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

/*
* This file is part of the Mercure Component project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* 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 <pascal.cescon@gmail.com>
*
* @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));
}
}
71 changes: 71 additions & 0 deletions src/Test/UpdateRecorder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

/*
* This file is part of the Mercure Component project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* 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 <pascal.cescon@gmail.com>
*
* @internal
*/
final class UpdateRecorder implements ResetInterface
{
/**
* @var list<array{string, Update}>
*/
private array $updates = [];

/**
* @param list<string> $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 doesn't record its updates
*
* @return list<Update> 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 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 = [];
foreach ($this->updates as [$name, $update]) {
if (null === $hub || $name === $hub) {
$updates[] = $update;
}
}

return $updates;
}

public function reset(): void
{
$this->updates = [];
}
}
Loading
Loading