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

172 lines
6.3 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;
2019-12-27 22:12:13 +03:00
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
2020-11-02 13:50:19 +03:00
use Prophecy\PhpUnit\ProphecyTrait;
2019-12-27 22:12:13 +03:00
use Prophecy\Prophecy\ObjectProphecy;
use Psr\Log\LoggerInterface;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Entity\Visit;
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\Model\Visitor;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Shlinkio\Shlink\Core\Options\WebhookOptions;
use Shlinkio\Shlink\Core\ShortUrl\Helper\ShortUrlStringifier;
use Shlinkio\Shlink\Core\ShortUrl\Transformer\ShortUrlDataTransformer;
2019-12-27 22:12:13 +03:00
use function count;
use function Functional\contains;
class NotifyVisitToWebHooksTest extends TestCase
{
2020-11-02 13:50:19 +03:00
use ProphecyTrait;
private ObjectProphecy $httpClient;
private ObjectProphecy $em;
private ObjectProphecy $logger;
2019-12-27 22:12:13 +03:00
protected function setUp(): void
2019-12-27 22:12:13 +03:00
{
$this->httpClient = $this->prophesize(ClientInterface::class);
$this->em = $this->prophesize(EntityManagerInterface::class);
$this->logger = $this->prophesize(LoggerInterface::class);
}
/** @test */
public function emptyWebhooksMakeNoFurtherActions(): void
{
$find = $this->em->find(Visit::class, '1')->willReturn(null);
$this->createListener([])(new VisitLocated('1'));
2019-12-27 22:12:13 +03:00
$find->shouldNotHaveBeenCalled();
}
/** @test */
public function invalidVisitDoesNotPerformAnyRequest(): void
{
$find = $this->em->find(Visit::class, '1')->willReturn(null);
$requestAsync = $this->httpClient->requestAsync(
RequestMethodInterface::METHOD_POST,
Argument::type('string'),
2020-01-01 22:48:31 +03:00
Argument::type('array'),
2019-12-27 22:12:13 +03:00
)->willReturn(new FulfilledPromise(''));
$logWarning = $this->logger->warning(
'Tried to notify webhooks for visit with id "{visitId}", but it does not exist.',
2020-01-01 22:48:31 +03:00
['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
$find->shouldHaveBeenCalledOnce();
$logWarning->shouldHaveBeenCalledOnce();
$requestAsync->shouldNotHaveBeenCalled();
}
/** @test */
public function orphanVisitDoesNotPerformAnyRequestWhenDisabled(): void
{
$find = $this->em->find(Visit::class, '1')->willReturn(Visit::forBasePath(Visitor::emptyInstance()));
$requestAsync = $this->httpClient->requestAsync(
RequestMethodInterface::METHOD_POST,
Argument::type('string'),
Argument::type('array'),
)->willReturn(new FulfilledPromise(''));
$logWarning = $this->logger->warning(Argument::cetera());
$this->createListener(['foo', 'bar'], false)(new VisitLocated('1'));
$find->shouldHaveBeenCalledOnce();
$logWarning->shouldNotHaveBeenCalled();
$requestAsync->shouldNotHaveBeenCalled();
}
/**
* @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'];
$find = $this->em->find(Visit::class, '1')->willReturn($visit);
2019-12-27 22:12:13 +03:00
$requestAsync = $this->httpClient->requestAsync(
RequestMethodInterface::METHOD_POST,
Argument::type('string'),
Argument::that(function (array $requestOptions) use ($expectedResponseKeys) {
Assert::assertArrayHasKey(RequestOptions::HEADERS, $requestOptions);
Assert::assertArrayHasKey(RequestOptions::JSON, $requestOptions);
Assert::assertArrayHasKey(RequestOptions::TIMEOUT, $requestOptions);
Assert::assertEquals($requestOptions[RequestOptions::TIMEOUT], 10);
Assert::assertEquals($requestOptions[RequestOptions::HEADERS], ['User-Agent' => 'Shlink:v1.2.3']);
$json = $requestOptions[RequestOptions::JSON];
Assert::assertCount(count($expectedResponseKeys), $json);
foreach ($expectedResponseKeys as $key) {
Assert::assertArrayHasKey($key, $json);
}
return $requestOptions;
2020-01-01 22:48:31 +03:00
}),
2019-12-27 22:12:13 +03:00
)->will(function (array $args) use ($invalidWebhooks) {
[, $webhook] = $args;
$shouldReject = contains($invalidWebhooks, $webhook);
2019-12-27 22:12:13 +03:00
return $shouldReject ? new RejectedPromise(new Exception('')) : new FulfilledPromise('');
2019-12-27 22:12:13 +03:00
});
$logWarning = $this->logger->warning(
'Failed to notify visit with id "{visitId}" to webhook "{webhook}". {e}',
Argument::that(function (array $extra) {
Assert::assertArrayHasKey('webhook', $extra);
Assert::assertArrayHasKey('visitId', $extra);
Assert::assertArrayHasKey('e', $extra);
return $extra;
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
$find->shouldHaveBeenCalledOnce();
$requestAsync->shouldHaveBeenCalledTimes(count($webhooks));
$logWarning->shouldHaveBeenCalledTimes(count($invalidWebhooks));
}
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->reveal(),
$this->em->reveal(),
$this->logger->reveal(),
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
);
}
}