shlink/module/Core/test/EventDispatcher/NotifyVisitToWebHooksTest.php

146 lines
5.6 KiB
PHP
Raw Normal View History

2019-12-27 22:12:13 +03:00
<?php
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Core\EventDispatcher;
2019-12-27 22:12:13 +03:00
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Fig\Http\Message\RequestMethodInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\RejectedPromise;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\MockObject\MockObject;
2019-12-27 22:12:13 +03:00
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Shlinkio\Shlink\Core\EventDispatcher\Event\VisitLocated;
2019-12-27 22:12:13 +03:00
use Shlinkio\Shlink\Core\EventDispatcher\NotifyVisitToWebHooks;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Shlinkio\Shlink\Core\Options\WebhookOptions;
use Shlinkio\Shlink\Core\ShortUrl\Entity\ShortUrl;
use Shlinkio\Shlink\Core\ShortUrl\Helper\ShortUrlStringifier;
use Shlinkio\Shlink\Core\ShortUrl\Transformer\ShortUrlDataTransformer;
use Shlinkio\Shlink\Core\Visit\Entity\Visit;
use Shlinkio\Shlink\Core\Visit\Model\Visitor;
2019-12-27 22:12:13 +03:00
use function count;
use function Functional\contains;
class NotifyVisitToWebHooksTest extends TestCase
{
private MockObject $httpClient;
private MockObject $em;
private MockObject $logger;
2019-12-27 22:12:13 +03:00
protected function setUp(): void
2019-12-27 22:12:13 +03:00
{
$this->httpClient = $this->createMock(ClientInterface::class);
$this->em = $this->createMock(EntityManagerInterface::class);
$this->logger = $this->createMock(LoggerInterface::class);
2019-12-27 22:12:13 +03:00
}
/** @test */
public function emptyWebhooksMakeNoFurtherActions(): void
{
$this->em->expects($this->never())->method('find');
2019-12-27 22:12:13 +03:00
$this->createListener([])(new VisitLocated('1'));
2019-12-27 22:12:13 +03:00
}
/** @test */
public function invalidVisitDoesNotPerformAnyRequest(): void
{
$this->em->expects($this->once())->method('find')->with(Visit::class, '1')->willReturn(null);
$this->httpClient->expects($this->never())->method('requestAsync');
$this->logger->expects($this->once())->method('warning')->with(
'Tried to notify webhooks for visit with id "{visitId}", but it does not exist.',
['visitId' => '1'],
2019-12-27 22:12:13 +03:00
);
$this->createListener(['foo', 'bar'])(new VisitLocated('1'));
2019-12-27 22:12:13 +03:00
}
/** @test */
public function orphanVisitDoesNotPerformAnyRequestWhenDisabled(): void
{
$this->em->expects($this->once())->method('find')->with(Visit::class, '1')->willReturn(
Visit::forBasePath(Visitor::emptyInstance()),
);
$this->httpClient->expects($this->never())->method('requestAsync');
$this->logger->expects($this->never())->method('warning');
$this->createListener(['foo', 'bar'], false)(new VisitLocated('1'));
}
/**
* @test
* @dataProvider provideVisits
*/
public function expectedRequestsArePerformedToWebhooks(Visit $visit, array $expectedResponseKeys): void
2019-12-27 22:12:13 +03:00
{
$webhooks = ['foo', 'invalid', 'bar', 'baz'];
$invalidWebhooks = ['invalid', 'baz'];
$this->em->expects($this->once())->method('find')->with(Visit::class, '1')->willReturn($visit);
$this->httpClient->expects($this->exactly(count($webhooks)))->method('requestAsync')->with(
RequestMethodInterface::METHOD_POST,
$this->istype('string'),
$this->callback(function (array $requestOptions) use ($expectedResponseKeys) {
Assert::assertArrayHasKey(RequestOptions::HEADERS, $requestOptions);
Assert::assertArrayHasKey(RequestOptions::JSON, $requestOptions);
Assert::assertArrayHasKey(RequestOptions::TIMEOUT, $requestOptions);
Assert::assertEquals(10, $requestOptions[RequestOptions::TIMEOUT]);
Assert::assertEquals(['User-Agent' => 'Shlink:v1.2.3'], $requestOptions[RequestOptions::HEADERS]);
$json = $requestOptions[RequestOptions::JSON];
Assert::assertCount(count($expectedResponseKeys), $json);
foreach ($expectedResponseKeys as $key) {
Assert::assertArrayHasKey($key, $json);
}
return true;
2020-01-01 22:48:31 +03:00
}),
)->willReturnCallback(function ($_, $webhook) use ($invalidWebhooks) {
$shouldReject = contains($invalidWebhooks, $webhook);
return $shouldReject ? new RejectedPromise(new Exception('')) : new FulfilledPromise('');
2019-12-27 22:12:13 +03:00
});
$this->logger->expects($this->exactly(count($invalidWebhooks)))->method('warning')->with(
'Failed to notify visit with id "{visitId}" to webhook "{webhook}". {e}',
$this->callback(function (array $extra): bool {
Assert::assertArrayHasKey('webhook', $extra);
Assert::assertArrayHasKey('visitId', $extra);
Assert::assertArrayHasKey('e', $extra);
return true;
2020-01-01 22:48:31 +03:00
}),
2019-12-27 22:12:13 +03:00
);
$this->createListener($webhooks)(new VisitLocated('1'));
2019-12-27 22:12:13 +03:00
}
public function provideVisits(): iterable
{
yield 'regular visit' => [
Visit::forValidShortUrl(ShortUrl::createEmpty(), Visitor::emptyInstance()),
['shortUrl', 'visit'],
];
yield 'orphan visit' => [Visit::forBasePath(Visitor::emptyInstance()), ['visit'],];
}
private function createListener(array $webhooks, bool $notifyOrphanVisits = true): NotifyVisitToWebHooks
2019-12-27 22:12:13 +03:00
{
return new NotifyVisitToWebHooks(
$this->httpClient,
$this->em,
$this->logger,
new WebhookOptions(
['webhooks' => $webhooks, 'notify_orphan_visits_to_webhooks' => $notifyOrphanVisits],
),
new ShortUrlDataTransformer(new ShortUrlStringifier([])),
new AppOptions('Shlink', '1.2.3'),
2019-12-27 22:12:13 +03:00
);
}
}