====== Faking requests ======
For testing you may need to fake requests to be able to test the according case.
To do so you can prepare a ServerRequest, it technically only needs a URI, along with a request handler.
The test request handler in BookingEngine looks like so:
/**
* TestRequestHandler
*
* Test request handler for non double pass middleware tests
*/
class TestRequestHandler implements RequestHandlerInterface
{
public $callable;
public function __construct(?callable $callable = null)
{
$this->callable = $callable ?: static function ($request) {
return new Response();
};
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return ($this->callable)($request);
}
}
The request that I prepared for this specific test was this:
$uri = new Uri(new \Laminas\Diactoros\Uri('http://example/helloWorld'), '', '/');
$request = new ServerRequest([
'uri' => $uri,
]);
I used this request to test the Idempotency class in BookingEngine, where I test that the Idempotency key is required for a certain configured path.
Here is the entire test:
/**
* Tests process with a path that needs to be checked
*
* @return void
* @covers ::__construct
* @covers ::checkMustProcessUrlTarget
* @covers ::process
*/
public function testProcessPathWithIdempotency(): void
{
$this->expectException(MissingKeyHeaderException::class);
$this->expectExceptionMessage('Missing required HTTP idempotency key header "Idempotency-Key"');
$uri = new Uri(new \Laminas\Diactoros\Uri('http://example/helloWorld'), '', '/');
$request = new ServerRequest([
'uri' => $uri,
]);
$request = $request->withMethod('POST');
$requestHandler = new TestRequestHandler();
// Set require key always false to reach mustn't check URL target
$idempotency = new Idempotency([
'processRegardlessOfMethod' => true,
'requireKeyAlways' => false,
'requireKeyForTargets' => ['/helloWorld' => true],
]);
$response = $idempotency->process($request, $requestHandler);
self::assertEquals(200, $response->getStatusCode());
self::assertEmpty($response->getHeader('X-Idempotency-Replay'));
}