Migrated NotifyVisitToRabbitMqTest to use PHPUnit mocks

This commit is contained in:
Alejandro Celaya 2022-10-22 19:05:34 +02:00
parent a15e9c29c8
commit 739433ba8b

View File

@ -8,10 +8,8 @@ use Doctrine\ORM\EntityManagerInterface;
use DomainException; use DomainException;
use Exception; use Exception;
use PHPUnit\Framework\Assert; use PHPUnit\Framework\Assert;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Prophecy\Prophecy\ObjectProphecy;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use RuntimeException; use RuntimeException;
use Shlinkio\Shlink\Common\UpdatePublishing\PublishingHelperInterface; use Shlinkio\Shlink\Common\UpdatePublishing\PublishingHelperInterface;
@ -33,48 +31,46 @@ use function Functional\noop;
class NotifyVisitToRabbitMqTest extends TestCase class NotifyVisitToRabbitMqTest extends TestCase
{ {
use ProphecyTrait; private MockObject $helper;
private MockObject $updatesGenerator;
private ObjectProphecy $helper; private MockObject $em;
private ObjectProphecy $updatesGenerator; private MockObject $logger;
private ObjectProphecy $em;
private ObjectProphecy $logger;
protected function setUp(): void protected function setUp(): void
{ {
$this->helper = $this->prophesize(PublishingHelperInterface::class); $this->helper = $this->createMock(PublishingHelperInterface::class);
$this->updatesGenerator = $this->prophesize(PublishingUpdatesGeneratorInterface::class); $this->updatesGenerator = $this->createMock(PublishingUpdatesGeneratorInterface::class);
$this->em = $this->prophesize(EntityManagerInterface::class); $this->em = $this->createMock(EntityManagerInterface::class);
$this->logger = $this->prophesize(LoggerInterface::class); $this->logger = $this->createMock(LoggerInterface::class);
} }
/** @test */ /** @test */
public function doesNothingWhenTheFeatureIsNotEnabled(): void public function doesNothingWhenTheFeatureIsNotEnabled(): void
{ {
($this->listener(new RabbitMqOptions(enabled: false)))(new VisitLocated('123')); $this->helper->expects($this->never())->method('publishUpdate');
$this->em->expects($this->never())->method('find');
$this->logger->expects($this->never())->method('warning');
$this->logger->expects($this->never())->method('debug');
$this->em->find(Argument::cetera())->shouldNotHaveBeenCalled(); ($this->listener(new RabbitMqOptions(enabled: false)))(new VisitLocated('123'));
$this->logger->warning(Argument::cetera())->shouldNotHaveBeenCalled();
$this->logger->debug(Argument::cetera())->shouldNotHaveBeenCalled();
$this->helper->publishUpdate(Argument::cetera())->shouldNotHaveBeenCalled();
} }
/** @test */ /** @test */
public function notificationsAreNotSentWhenVisitCannotBeFound(): void public function notificationsAreNotSentWhenVisitCannotBeFound(): void
{ {
$visitId = '123'; $visitId = '123';
$findVisit = $this->em->find(Visit::class, $visitId)->willReturn(null); $this->em->expects($this->once())->method('find')->with(
$logWarning = $this->logger->warning( $this->equalTo(Visit::class),
'Tried to notify {name} for visit with id "{visitId}", but it does not exist.', $this->equalTo($visitId),
['visitId' => $visitId, 'name' => 'RabbitMQ'], )->willReturn(null);
$this->logger->expects($this->once())->method('warning')->with(
$this->equalTo('Tried to notify {name} for visit with id "{visitId}", but it does not exist.'),
$this->equalTo(['visitId' => $visitId, 'name' => 'RabbitMQ']),
); );
$this->logger->expects($this->never())->method('debug');
$this->helper->expects($this->never())->method('publishUpdate');
($this->listener())(new VisitLocated($visitId)); ($this->listener())(new VisitLocated($visitId));
$findVisit->shouldHaveBeenCalledOnce();
$logWarning->shouldHaveBeenCalledOnce();
$this->logger->debug(Argument::cetera())->shouldNotHaveBeenCalled();
$this->helper->publishUpdate(Argument::cetera())->shouldNotHaveBeenCalled();
} }
/** /**
@ -84,20 +80,21 @@ class NotifyVisitToRabbitMqTest extends TestCase
public function expectedChannelsAreNotifiedBasedOnTheVisitType(Visit $visit, array $expectedChannels): void public function expectedChannelsAreNotifiedBasedOnTheVisitType(Visit $visit, array $expectedChannels): void
{ {
$visitId = '123'; $visitId = '123';
$findVisit = $this->em->find(Visit::class, $visitId)->willReturn($visit); $this->em->expects($this->once())->method('find')->with(
$this->equalTo(Visit::class),
$this->equalTo($visitId),
)->willReturn($visit);
each($expectedChannels, function (string $method): void { each($expectedChannels, function (string $method): void {
$this->updatesGenerator->{$method}(Argument::type(Visit::class))->willReturn( $this->updatesGenerator->expects($this->once())->method($method)->with(
Update::forTopicAndPayload('', []), $this->isInstanceOf(Visit::class),
)->shouldBeCalledOnce(); )->willReturn(Update::forTopicAndPayload('', []));
}); });
$this->helper->expects($this->exactly(count($expectedChannels)))->method('publishUpdate')->with(
$this->isInstanceOf(Update::class),
);
$this->logger->expects($this->never())->method('debug');
($this->listener())(new VisitLocated($visitId)); ($this->listener())(new VisitLocated($visitId));
$findVisit->shouldHaveBeenCalledOnce();
$this->helper->publishUpdate(Argument::type(Update::class))->shouldHaveBeenCalledTimes(
count($expectedChannels),
);
$this->logger->debug(Argument::cetera())->shouldNotHaveBeenCalled();
} }
public function provideVisits(): iterable public function provideVisits(): iterable
@ -124,21 +121,20 @@ class NotifyVisitToRabbitMqTest extends TestCase
public function printsDebugMessageInCaseOfError(Throwable $e): void public function printsDebugMessageInCaseOfError(Throwable $e): void
{ {
$visitId = '123'; $visitId = '123';
$findVisit = $this->em->find(Visit::class, $visitId)->willReturn(Visit::forBasePath(Visitor::emptyInstance())); $this->em->expects($this->once())->method('find')->with(
$generateUpdate = $this->updatesGenerator->newOrphanVisitUpdate(Argument::type(Visit::class))->willReturn( $this->equalTo(Visit::class),
Update::forTopicAndPayload('', []), $this->equalTo($visitId),
)->willReturn(Visit::forBasePath(Visitor::emptyInstance()));
$this->updatesGenerator->expects($this->once())->method('newOrphanVisitUpdate')->with(
$this->isInstanceOf(Visit::class),
)->willReturn(Update::forTopicAndPayload('', []));
$this->helper->expects($this->once())->method('publishUpdate')->withAnyParameters()->willThrowException($e);
$this->logger->expects($this->once())->method('debug')->with(
$this->equalTo('Error while trying to notify {name} with new visit. {e}'),
$this->equalTo(['e' => $e, 'name' => 'RabbitMQ']),
); );
$publish = $this->helper->publishUpdate(Argument::cetera())->willThrow($e);
($this->listener())(new VisitLocated($visitId)); ($this->listener())(new VisitLocated($visitId));
$this->logger->debug(
'Error while trying to notify {name} with new visit. {e}',
['e' => $e, 'name' => 'RabbitMQ'],
)->shouldHaveBeenCalledOnce();
$findVisit->shouldHaveBeenCalledOnce();
$generateUpdate->shouldHaveBeenCalledOnce();
$publish->shouldHaveBeenCalledOnce();
} }
public function provideExceptions(): iterable public function provideExceptions(): iterable
@ -155,17 +151,18 @@ class NotifyVisitToRabbitMqTest extends TestCase
public function expectedPayloadIsPublishedDependingOnConfig( public function expectedPayloadIsPublishedDependingOnConfig(
bool $legacy, bool $legacy,
Visit $visit, Visit $visit,
callable $assert,
callable $setup, callable $setup,
callable $expect,
): void { ): void {
$visitId = '123'; $visitId = '123';
$findVisit = $this->em->find(Visit::class, $visitId)->willReturn($visit); $this->em->expects($this->once())->method('find')->with(
$this->equalTo(Visit::class),
$this->equalTo($visitId),
)->willReturn($visit);
$setup($this->updatesGenerator); $setup($this->updatesGenerator);
$expect($this->helper, $this->updatesGenerator);
($this->listener(new RabbitMqOptions(true, $legacy)))(new VisitLocated($visitId)); ($this->listener(new RabbitMqOptions(true, $legacy)))(new VisitLocated($visitId));
$findVisit->shouldHaveBeenCalledOnce();
$assert($this->helper, $this->updatesGenerator);
} }
public function provideLegacyPayloads(): iterable public function provideLegacyPayloads(): iterable
@ -173,8 +170,9 @@ class NotifyVisitToRabbitMqTest extends TestCase
yield 'legacy non-orphan visit' => [ yield 'legacy non-orphan visit' => [
true, true,
$visit = Visit::forValidShortUrl(ShortUrl::withLongUrl(''), Visitor::emptyInstance()), $visit = Visit::forValidShortUrl(ShortUrl::withLongUrl(''), Visitor::emptyInstance()),
function (ObjectProphecy|PublishingHelperInterface $helper) use ($visit): void { noop(...),
$helper->publishUpdate(Argument::that(function (Update $update) use ($visit): bool { function (MockObject & PublishingHelperInterface $helper) use ($visit): void {
$helper->method('publishUpdate')->with($this->callback(function (Update $update) use ($visit): bool {
$payload = $update->payload; $payload = $update->payload;
Assert::assertEquals($payload, $visit->jsonSerialize()); Assert::assertEquals($payload, $visit->jsonSerialize());
Assert::assertArrayNotHasKey('visitedUrl', $payload); Assert::assertArrayNotHasKey('visitedUrl', $payload);
@ -185,13 +183,13 @@ class NotifyVisitToRabbitMqTest extends TestCase
return true; return true;
})); }));
}, },
noop(...),
]; ];
yield 'legacy orphan visit' => [ yield 'legacy orphan visit' => [
true, true,
Visit::forBasePath(Visitor::emptyInstance()), Visit::forBasePath(Visitor::emptyInstance()),
function (ObjectProphecy|PublishingHelperInterface $helper): void { noop(...),
$helper->publishUpdate(Argument::that(function (Update $update): bool { function (MockObject & PublishingHelperInterface $helper): void {
$helper->method('publishUpdate')->with($this->callback(function (Update $update): bool {
$payload = $update->payload; $payload = $update->payload;
Assert::assertArrayHasKey('visitedUrl', $payload); Assert::assertArrayHasKey('visitedUrl', $payload);
Assert::assertArrayHasKey('type', $payload); Assert::assertArrayHasKey('type', $payload);
@ -199,35 +197,33 @@ class NotifyVisitToRabbitMqTest extends TestCase
return true; return true;
})); }));
}, },
noop(...),
]; ];
yield 'non-legacy non-orphan visit' => [ yield 'non-legacy non-orphan visit' => [
false, false,
Visit::forValidShortUrl(ShortUrl::withLongUrl(''), Visitor::emptyInstance()), Visit::forValidShortUrl(ShortUrl::withLongUrl(''), Visitor::emptyInstance()),
function (ObjectProphecy|PublishingHelperInterface $helper): void { function (MockObject & PublishingUpdatesGeneratorInterface $updatesGenerator): void {
$helper->publishUpdate(Argument::type(Update::class))->shouldHaveBeenCalledTimes(2);
},
function (ObjectProphecy|PublishingUpdatesGeneratorInterface $updatesGenerator): void {
$update = Update::forTopicAndPayload('', []); $update = Update::forTopicAndPayload('', []);
$updatesGenerator->newOrphanVisitUpdate(Argument::cetera())->shouldNotBeCalled(); $updatesGenerator->expects($this->never())->method('newOrphanVisitUpdate');
$updatesGenerator->newVisitUpdate(Argument::cetera())->willReturn($update) $updatesGenerator->expects($this->once())->method('newVisitUpdate')->withAnyParameters()->willReturn(
->shouldBeCalledOnce(); $update,
$updatesGenerator->newShortUrlVisitUpdate(Argument::cetera())->willReturn($update) );
->shouldBeCalledOnce(); $updatesGenerator->expects($this->once())->method('newShortUrlVisitUpdate')->willReturn($update);
},
function (MockObject & PublishingHelperInterface $helper): void {
$helper->expects($this->exactly(2))->method('publishUpdate')->with($this->isInstanceOf(Update::class));
}, },
]; ];
yield 'non-legacy orphan visit' => [ yield 'non-legacy orphan visit' => [
false, false,
Visit::forBasePath(Visitor::emptyInstance()), Visit::forBasePath(Visitor::emptyInstance()),
function (ObjectProphecy|PublishingHelperInterface $helper): void { function (MockObject & PublishingUpdatesGeneratorInterface $updatesGenerator): void {
$helper->publishUpdate(Argument::type(Update::class))->shouldHaveBeenCalledOnce();
},
function (ObjectProphecy|PublishingUpdatesGeneratorInterface $updatesGenerator): void {
$update = Update::forTopicAndPayload('', []); $update = Update::forTopicAndPayload('', []);
$updatesGenerator->newOrphanVisitUpdate(Argument::cetera())->willReturn($update) $updatesGenerator->expects($this->once())->method('newOrphanVisitUpdate')->willReturn($update);
->shouldBeCalledOnce(); $updatesGenerator->expects($this->never())->method('newVisitUpdate');
$updatesGenerator->newVisitUpdate(Argument::cetera())->shouldNotBeCalled(); $updatesGenerator->expects($this->never())->method('newShortUrlVisitUpdate');
$updatesGenerator->newShortUrlVisitUpdate(Argument::cetera())->shouldNotBeCalled(); },
function (MockObject & PublishingHelperInterface $helper): void {
$helper->expects($this->once())->method('publishUpdate')->with($this->isInstanceOf(Update::class));
}, },
]; ];
} }
@ -235,10 +231,10 @@ class NotifyVisitToRabbitMqTest extends TestCase
private function listener(?RabbitMqOptions $options = null): NotifyVisitToRabbitMq private function listener(?RabbitMqOptions $options = null): NotifyVisitToRabbitMq
{ {
return new NotifyVisitToRabbitMq( return new NotifyVisitToRabbitMq(
$this->helper->reveal(), $this->helper,
$this->updatesGenerator->reveal(), $this->updatesGenerator,
$this->em->reveal(), $this->em,
$this->logger->reveal(), $this->logger,
new OrphanVisitDataTransformer(), new OrphanVisitDataTransformer(),
$options ?? new RabbitMqOptions(enabled: true, legacyVisitsPublishing: false), $options ?? new RabbitMqOptions(enabled: true, legacyVisitsPublishing: false),
); );