forked from pionl/laravel-swagger-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LaravelRequester.php
221 lines (194 loc) · 7.15 KB
/
LaravelRequester.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
<?php
namespace RouxtAccess\OpenApi\Testing\Laravel;
use ByJG\ApiTools\AbstractRequester;
use ByJG\ApiTools\Exception\DefinitionNotFoundException;
use ByJG\ApiTools\Exception\GenericSwaggerException;
use ByJG\ApiTools\Exception\HttpMethodNotFoundException;
use ByJG\ApiTools\Exception\InvalidDefinitionException;
use ByJG\ApiTools\Exception\InvalidRequestException;
use ByJG\ApiTools\Exception\NotMatchedException;
use ByJG\ApiTools\Exception\PathNotFoundException;
use ByJG\ApiTools\Exception\StatusCodeNotMatchedException;
use ByJG\Util\Helper\RequestJson;
use ByJG\Util\Psr7\MessageException;
use ByJG\Util\Uri;
use Illuminate\Support\Str;
use JsonException;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;
class LaravelRequester extends AbstractRequester
{
protected Response $response;
protected TestCase $testCase;
/**
* @noinspection PhpMissingParentConstructorInspection
* @noinspection MagicMethodsValidityInspection
* @param TestCase $testCase
* @throws MessageException
*/
public function __construct(TestCase $testCase)
{
$this->withPsr7Request(RequestJson::build(new Uri("/"), 'get', "[]"));
$this->testCase = $testCase;
}
/**
* @param RequestInterface $request
* @return Response
* @throws JsonException
*/
protected function handleRequest(RequestInterface $request) : Response
{
$testResponse = $this->testCase->json(
$request->getMethod(),
(string) $request->getUri(),
json_decode($request->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR),
$this->getServerHeaders($request),
);
return $testResponse->baseResponse;
}
/**
* @param RequestInterface $request
* @return array
*/
protected function getServerHeaders(RequestInterface $request) : array
{
// Convert headers to server headers
return collect($request->getHeaders())->mapWithKeys(function ($value, $name) {
return $this->formatServerHeader($name, $value);
})->all();
}
/**
* Format the header key/val for the server array
* @param $name
* @param $value
* @return array
*/
protected function formatServerHeader($name, $value) : array
{
$name = str_replace('-', '_', strtoupper($name));
$name = $this->formatServerHeaderKey($name);
if($name === "HTTP_AUTHORIZATION")
{
$value = array_shift($value);
}
return [$name => $value];
}
/**
* Format the header name for the server array.
*
* @param string $name
*
* @return string
*/
protected function formatServerHeaderKey($name): string
{
if ($name !== 'CONTENT_TYPE' && $name !== 'REMOTE_ADDR' && !Str::startsWith($name, 'HTTP_')) {
return 'HTTP_'.$name;
}
return $name;
}
/**
* @return Response
* @throws JsonException
*/
public function send() : Response
{
// Process URI based on the OpenAPI schema
$uriSchema = new Uri($this->schema->getServerUrl());
if (empty($uriSchema->getScheme())) {
$uriSchema = $uriSchema->withScheme($this->psr7Request->getUri()->getScheme());
}
if (empty($uriSchema->getHost())) {
$uriSchema = $uriSchema->withHost($this->psr7Request->getUri()->getHost());
}
$uri = $this->psr7Request->getUri()
->withScheme($uriSchema->getScheme())
->withHost($uriSchema->getHost())
->withPort($uriSchema->getPort())
->withPath($uriSchema->getPath() . $this->psr7Request->getUri()->getPath());
if (!preg_match("~^{$this->schema->getBasePath()}~", $uri->getPath())) {
$uri = $uri->withPath($this->schema->getBasePath() . $uri->getPath());
}
$this->psr7Request = $this->psr7Request->withUri($uri);
// Handle Request
$this->response = $this->handleRequest($this->psr7Request);
return $this->response;
}
/**
* @return bool
* @throws InvalidRequestException
* @throws JsonException
* @throws HttpMethodNotFoundException
* @throws PathNotFoundException
*/
public function validateRequest(): bool
{
// Prepare Body to Match Against Specification
$requestBody = $this->psr7Request->getBody();
if ($requestBody !== null) {
$requestBody = $requestBody->getContents();
$contentType = $this->psr7Request->getHeaderLine("content-type");
if (empty($contentType) || strpos($contentType, "application/json") !== false) {
$requestBody = json_decode($requestBody, true, 512, JSON_THROW_ON_ERROR);
} elseif (strpos($contentType, "multipart/") !== false) {
$requestBody = $this->parseMultiPartForm($contentType, $requestBody);
} else {
throw new InvalidRequestException("Cannot handle Content Type '{$contentType}'");
}
}
// Check if the body is the expected before request
$bodyRequestDef = $this->schema->getRequestParameters($this->psr7Request->getUri()->getPath(), $this->psr7Request->getMethod());
$bodyRequestDef->match($requestBody);
return true;
}
/**
* @param Response $response
* @param null $status
* @return bool
* @throws JsonException
* @throws NotMatchedException
* @throws StatusCodeNotMatchedException
* @throws DefinitionNotFoundException
* @throws GenericSwaggerException
* @throws HttpMethodNotFoundException
* @throws InvalidDefinitionException
* @throws PathNotFoundException
*/
public function validateResponse(Response $response, $status = null): bool
{
$responseHeaderBag = $response->headers;
$responseBodyStr = (string) $response->getContent();
$responseBody = json_decode($responseBodyStr, true, 512, JSON_THROW_ON_ERROR);
$statusReturned = $response->getStatusCode();
// Assert results
if ($status !== $statusReturned) {
throw new StatusCodeNotMatchedException(
"Status code not matched: Expected {$status}, got {$statusReturned}",
$responseBody
);
}
$bodyResponseDef = $this->schema->getResponseParameters(
$this->psr7Request->getUri()->getPath(),
$this->psr7Request->getMethod(),
$status
);
$bodyResponseDef->match($responseBody);
foreach ($this->assertHeader as $key => $value) {
if ($responseHeaderBag->get($key)) {
throw new NotMatchedException(
"Does not exists header '$key' with value '$value'",
$responseHeaderBag->all(),
);
}
}
if (!empty($responseBodyStr)) {
foreach ($this->assertBody as $item) {
if (strpos($responseBodyStr, $item) === false) {
throw new NotMatchedException("Body does not contain '{$item}'");
}
}
}
return true;
}
}