Skip to content

[Notifier] Introduce PHPUnit constraints and assertions for the Notifier #46895

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 24, 2022
Merged
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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
6.2
---

* Add `NotificationAssertionsTrait`
* Add option `framework.catch_all_throwables` to allow `Symfony\Component\HttpKernel\HttpKernel` to catch all kinds of `Throwable`
* Make `AbstractController::render()` able to deal with forms and deprecate `renderForm()`
* Deprecate the `Symfony\Component\Serializer\Normalizer\ObjectNormalizer` and
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
abstract class KernelTestCase extends TestCase
{
use MailerAssertionsTrait;
use NotificationAssertionsTrait;

protected static $class;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Test;

use PHPUnit\Framework\Constraint\LogicalNot;
use Symfony\Component\Notifier\Event\MessageEvent;
use Symfony\Component\Notifier\Event\NotificationEvents;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Test\Constraint as NotifierConstraint;

/*
* @author Smaïne Milianni <smaine.milianni@gmail.com>
*/
trait NotificationAssertionsTrait
{
public static function assertNotificationCount(int $count, string $transport = null, string $message = ''): void
{
self::assertThat(self::getNotificationEvents(), new NotifierConstraint\NotificationCount($count, $transport), $message);
}

public static function assertQueuedNotificationCount(int $count, string $transport = null, string $message = ''): void
{
self::assertThat(self::getMessageMailerEvents(), new NotifierConstraint\NotificationCount($count, $transport, true), $message);
}

public static function assertNotificationIsQueued(MessageEvent $event, string $message = ''): void
{
self::assertThat($event, new NotifierConstraint\NotificationIsQueued(), $message);
}

public static function assertNotificationIsNotQueued(MessageEvent $event, string $message = ''): void
{
self::assertThat($event, new LogicalNot(new NotifierConstraint\NotificationIsQueued()), $message);
}

public static function assertNotificationSubjectContains(MessageInterface $messageObject, string $text, string $message = ''): void
{
self::assertThat($messageObject, new NotifierConstraint\NotificationSubjectContains($text), $message);
}

public static function assertNotificationSubjectNotContains(MessageInterface $messageObject, string $text, string $message = ''): void
{
self::assertThat($messageObject, new LogicalNot(new NotifierConstraint\NotificationSubjectContains($text)), $message);
}

public static function assertNotificationTransportIsEqual(MessageInterface $messageObject, string $text, string $message = ''): void
{
self::assertThat($messageObject, new NotifierConstraint\NotificationTransportIsEqual($text), $message);
}

public static function assertNotificationTransportIsNotEqual(MessageInterface $messageObject, string $text, string $message = ''): void
{
self::assertThat($messageObject, new LogicalNot(new NotifierConstraint\NotificationTransportIsEqual($text)), $message);
}

/**
* @return MessageEvent[]
*/
public static function getNotifierEvents(string $transport = null): array
{
return self::getNotificationEvents()->getEvents($transport);
}

public static function getNotifierEvent(int $index = 0, string $transport = null): ?MessageEvent
{
return self::getNotifierEvents($transport)[$index] ?? null;
}

/**
* @return MessageInterface[]
*/
public static function getNotifierMessages(string $transport = null): array
{
return self::getNotificationEvents()->getMessages($transport);
}

public static function getNotifierMessage(int $index = 0, string $transport = null): ?MessageInterface
{
return self::getNotifierMessages($transport)[$index] ?? null;
}

public static function getNotificationEvents(): NotificationEvents
{
$container = static::getContainer();
if ($container->has('notifier.logger_notification_listener')) {
return $container->get('notifier.logger_notification_listener')->getEvents();
}

static::fail('A client must have Notifier enabled to make notifications assertions. Did you forget to require symfony/notifier?');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Notifier\Notification\Notification;
use Symfony\Component\Notifier\NotifierInterface;

final class NotificationController
{
public function indexAction(NotifierInterface $notifier)
{
$firstNotification = new Notification('Hello World!', ['chat/slack']);
$firstNotification->content('Symfony is awesome!');

$notifier->send($firstNotification);

$secondNotification = (new Notification('New urgent notification'))
->importance(Notification::IMPORTANCE_URGENT)
;
$notifier->send($secondNotification);

return new Response();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,7 @@ send_email:
uid:
resource: "../../Controller/UidController.php"
type: "annotation"

send_notification:
path: /send_notification
defaults: { _controller: Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\NotificationController::indexAction }
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;

final class NotificationTest extends AbstractWebTestCase
{
public function testNotifierAssertion()
{
$client = $this->createClient(['test_case' => 'Notifier', 'root_config' => 'config.yml', 'debug' => true]);
$client->request('GET', '/send_notification');

$this->assertNotificationCount(2);
$first = 0;
$second = 1;
$this->assertNotificationIsNotQueued($this->getNotifierEvent($first));
$this->assertNotificationIsNotQueued($this->getNotifierEvent($second));

$notification = $this->getNotifierMessage($first);
$this->assertNotificationSubjectContains($notification, 'Hello World!');
$this->assertNotificationSubjectNotContains($notification, 'New urgent notification');
$this->assertNotificationTransportIsEqual($notification, 'slack');
$this->assertNotificationTransportIsNotEqual($notification, 'mercure');

$notification = $this->getNotifierMessage($second);
$this->assertNotificationSubjectContains($notification, 'New urgent notification');
$this->assertNotificationSubjectNotContains($notification, 'Hello World!');
$this->assertNotificationTransportIsEqual($notification, 'mercure');
$this->assertNotificationTransportIsNotEqual($notification, 'slack');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\TestBundle;
use Symfony\Bundle\MercureBundle\MercureBundle;

return [
new FrameworkBundle(),
new TestBundle(),
new MercureBundle(),
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
imports:
- { resource: ../config/default.yml }
- { resource: services.yml }

framework:
mailer:
dsn: 'null://null'
notifier:
chatter_transports:
slack: 'null://null'
mercure: 'null://null'
channel_policy:
urgent: ['chat/mercure']
admin_recipients:
- { email: admin@example.com }
profiler: ~

mercure:
hubs:
default:
url: 'null://null'
jwt:
secret: '!ChangeMe!'
publish: [ 'foo', 'https://example.com/foo' ]
subscribe: [ 'bar', 'https://example.com/bar' ]
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
_notifiertest_bundle:
resource: '@TestBundle/Resources/config/routing.yml'
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
services:
_defaults:
public: true

Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\NotificationController:
tags: ['controller.service_arguments']

5 changes: 5 additions & 0 deletions src/Symfony/Component/Notifier/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

6.2
---

* Add PHPUnit constraints

6.1
---

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Notifier\Test\Constraint;

use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\Notifier\Event\NotificationEvents;

/**
* @author Smaïne Milianni <smaine.milianni@gmail.com>
*/
final class NotificationCount extends Constraint
{
private $expectedValue;
private $transport;
private $queued;

public function __construct(int $expectedValue, string $transport = null, bool $queued = false)
{
$this->expectedValue = $expectedValue;
$this->transport = $transport;
$this->queued = $queued;
}

/**
* {@inheritdoc}
*/
public function toString(): string
{
return sprintf('%shas %s "%d" emails', $this->transport ? $this->transport.' ' : '', $this->queued ? 'queued' : 'sent', $this->expectedValue);
}

/**
* @param NotificationEvents $events
*
* {@inheritdoc}
*/
protected function matches($events): bool
{
return $this->expectedValue === $this->countNotifications($events);
}

/**
* @param NotificationEvents $events
*
* {@inheritdoc}
*/
protected function failureDescription($events): string
{
return sprintf('the Transport %s (%d %s)', $this->toString(), $this->countNotifications($events), $this->queued ? 'queued' : 'sent');
}

private function countNotifications(NotificationEvents $events): int
{
$count = 0;
foreach ($events->getEvents($this->transport) as $event) {
if (
($this->queued && $event->isQueued())
||
(!$this->queued && !$event->isQueued())
) {
++$count;
}
}

return $count;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Notifier\Test\Constraint;

use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\Notifier\Event\MessageEvent;

/**
* @author Smaïne Milianni <smaine.milianni@gmail.com>
*/
final class NotificationIsQueued extends Constraint
{
/**
* {@inheritdoc}
*/
public function toString(): string
{
return 'is queued';
}

/**
* @param MessageEvent $event
*
* {@inheritdoc}
*/
protected function matches($event): bool
{
return $event->isQueued();
}

/**
* @param MessageEvent $event
*
* {@inheritdoc}
*/
protected function failureDescription($event): string
{
return 'the Notification '.$this->toString();
}
}
Loading