shlink/module/Rest/test/Authentication/Plugin/ApiKeyHeaderPluginTest.php

67 lines
2 KiB
PHP
Raw Normal View History

2018-09-29 09:34:47 +03:00
<?php
2019-10-05 18:26:10 +03:00
2018-09-29 09:34:47 +03:00
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Rest\Authentication\Plugin;
2020-01-01 23:11:53 +03:00
use Laminas\Diactoros\Response;
use Laminas\Diactoros\ServerRequest;
2018-09-29 09:34:47 +03:00
use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\ObjectProphecy;
use Psr\Http\Message\ServerRequestInterface;
use Shlinkio\Shlink\Rest\Authentication\Plugin\ApiKeyHeaderPlugin;
use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
class ApiKeyHeaderPluginTest extends TestCase
{
private ApiKeyHeaderPlugin $plugin;
private ObjectProphecy $apiKeyService;
2018-09-29 09:34:47 +03:00
2019-02-16 12:53:45 +03:00
public function setUp(): void
2018-09-29 09:34:47 +03:00
{
$this->apiKeyService = $this->prophesize(ApiKeyServiceInterface::class);
2018-11-18 18:28:04 +03:00
$this->plugin = new ApiKeyHeaderPlugin($this->apiKeyService->reveal());
2018-09-29 09:34:47 +03:00
}
2019-02-17 22:28:34 +03:00
/** @test */
2020-01-01 22:48:31 +03:00
public function verifyThrowsExceptionWhenApiKeyIsNotValid(): void
2018-09-29 09:34:47 +03:00
{
$apiKey = 'abc-ABC';
$check = $this->apiKeyService->check($apiKey)->willReturn(false);
2018-11-11 15:18:21 +03:00
$check->shouldBeCalledOnce();
2018-09-29 09:34:47 +03:00
$this->expectException(VerifyAuthenticationException::class);
$this->expectExceptionMessage('Provided API key does not exist or is invalid');
$this->plugin->verify($this->createRequest($apiKey));
}
2019-02-17 22:28:34 +03:00
/** @test */
2020-01-01 22:48:31 +03:00
public function verifyDoesNotThrowExceptionWhenApiKeyIsValid(): void
2018-09-29 09:34:47 +03:00
{
$apiKey = 'abc-ABC';
$check = $this->apiKeyService->check($apiKey)->willReturn(true);
$this->plugin->verify($this->createRequest($apiKey));
2018-11-11 15:18:21 +03:00
$check->shouldHaveBeenCalledOnce();
2018-09-29 09:34:47 +03:00
}
2019-02-17 22:28:34 +03:00
/** @test */
2020-01-01 22:48:31 +03:00
public function updateReturnsResponseAsIs(): void
2018-09-29 09:34:47 +03:00
{
$apiKey = 'abc-ABC';
$response = new Response();
$returnedResponse = $this->plugin->update($this->createRequest($apiKey), $response);
$this->assertSame($response, $returnedResponse);
}
private function createRequest(string $apiKey): ServerRequestInterface
{
return (new ServerRequest())->withHeader(ApiKeyHeaderPlugin::HEADER_NAME, $apiKey);
2018-09-29 09:34:47 +03:00
}
}