Improved CheckAuthenticationMiddlewareTest

This commit is contained in:
Alejandro Celaya 2016-07-31 13:01:08 +02:00
parent f904f79c18
commit ef6f4fba66

View file

@ -3,6 +3,7 @@ namespace ShlinkioTest\Shlink\Rest\Middleware;
use PHPUnit_Framework_TestCase as TestCase;
use Prophecy\Prophecy\ObjectProphecy;
use Shlinkio\Shlink\Core\Entity\RestToken;
use Shlinkio\Shlink\Rest\Middleware\CheckAuthenticationMiddleware;
use Shlinkio\Shlink\Rest\Service\RestTokenService;
use Zend\Diactoros\Response;
@ -77,4 +78,57 @@ class CheckAuthenticationMiddlewareTest extends TestCase
});
$this->assertTrue($isCalled);
}
/**
* @test
*/
public function noHeaderReturnsError()
{
$request = ServerRequestFactory::fromGlobals()->withAttribute(
RouteResult::class,
RouteResult::fromRouteMatch('bar', 'foo', [])
);
$response = $this->middleware->__invoke($request, new Response());
$this->assertEquals(401, $response->getStatusCode());
}
/**
* @test
*/
public function provideAnExpiredTokenReturnsError()
{
$authToken = 'ABC-abc';
$request = ServerRequestFactory::fromGlobals()->withAttribute(
RouteResult::class,
RouteResult::fromRouteMatch('bar', 'foo', [])
)->withHeader(CheckAuthenticationMiddleware::AUTH_TOKEN_HEADER, $authToken);
$this->tokenService->getByToken($authToken)->willReturn(
(new RestToken())->setExpirationDate((new \DateTime())->sub(new \DateInterval('P1D')))
)->shouldBeCalledTimes(1);
$response = $this->middleware->__invoke($request, new Response());
$this->assertEquals(401, $response->getStatusCode());
}
/**
* @test
*/
public function provideCorrectTokenUpdatesExpirationAndFallbacksToNextMiddleware()
{
$authToken = 'ABC-abc';
$restToken = (new RestToken())->setExpirationDate((new \DateTime())->add(new \DateInterval('P1D')));
$request = ServerRequestFactory::fromGlobals()->withAttribute(
RouteResult::class,
RouteResult::fromRouteMatch('bar', 'foo', [])
)->withHeader(CheckAuthenticationMiddleware::AUTH_TOKEN_HEADER, $authToken);
$this->tokenService->getByToken($authToken)->willReturn($restToken)->shouldBeCalledTimes(1);
$this->tokenService->updateExpiration($restToken)->shouldBeCalledTimes(1);
$isCalled = false;
$this->assertFalse($isCalled);
$this->middleware->__invoke($request, new Response(), function ($req, $resp) use (&$isCalled) {
$isCalled = true;
});
$this->assertTrue($isCalled);
}
}