-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathApiContext.php
More file actions
494 lines (414 loc) · 15.3 KB
/
Copy pathApiContext.php
File metadata and controls
494 lines (414 loc) · 15.3 KB
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<?php
declare(strict_types=1);
namespace BehatApiContext\Context;
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use BehatApiContext\Service\ResetManager\ResetManagerInterface;
use BehatApiContext\Service\StringManager;
use RuntimeException;
use SimilarArrays\SimilarArray;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
use Symfony\Component\Routing\RouterInterface;
use Throwable;
class ApiContext implements Context
{
private SimilarArray $similarArrayManager;
private StringManager $stringManager;
private RouterInterface $router;
private RequestStack $requestStack;
private Response $response;
private KernelInterface $kernel;
/**
* @var list<ResetManagerInterface>
*/
private array $resetManagers = [];
/**
* @var array<string,string> $headers
*/
protected array $headers = [];
/**
* @var array<string,string> $serverParams
*/
protected array $serverParams = [];
/**
* @var array<string, mixed> $requestParams
*/
protected array $requestParams = [];
/**
* @var array<string, string|list<string>> $savedValues
*/
protected array $savedValues = [];
public function __construct(
RouterInterface $router,
RequestStack $requestStack,
KernelInterface $kernel
) {
$this->router = $router;
$this->requestStack = $requestStack;
$this->kernel = $kernel;
$this->similarArrayManager = new SimilarArray();
$this->stringManager = new StringManager();
}
public function addKernelResetManager(ResetManagerInterface $resetManager): void
{
$this->resetManagers[] = $resetManager;
}
/**
* @BeforeScenario
*/
public function beforeScenario(): void
{
$this->savedValues = [];
$this->resetRequestOptions();
}
/**
* Sets a request header. Header name and value must be double-quoted so names like
* Content-Type and values like application/json match reliably (Turnip placeholders do not
* capture hyphens or slashes in unquoted tokens).
*
* @Given #^the "(?P<header>[^"]+)" request header contains "(?P<value>[^"]*)"$#
*/
public function theRequestHeaderContains(string $header, string $value): void
{
$processedHeader = $this->stringManager->substituteValues(
$this->savedValues,
trim($value)
);
$this->headers[$header] = $processedHeader;
}
/**
* @Given #^the "(?P<header>[^"]+)" request header contains multiline value:$#
*/
public function theRequestHeaderContainsMultiline(string $header, PyStringNode $params): void
{
$processedParams = $this->stringManager->substituteValues($this->savedValues, trim($params->getRaw()));
$this->headers[$header] = $processedParams;
}
/**
* Sets Content-Type to application/json so POST, PUT, and PATCH requests JSON-encode
* requestParams in iSendRequestToRoute().
*
* @Given the request JSON content type is used
*/
public function theRequestJsonContentTypeIsUsed(): void
{
$this->headers['Content-Type'] = 'application/json';
}
/**
* @Given the request ip is :ip
*/
public function theRequestIpIs(string $ip): void
{
$this->serverParams['REMOTE_ADDR'] = $ip;
}
/**
* @Given the request contains params:
*/
public function theRequestContainsParams(PyStringNode $params): void
{
$processedParams = $this->stringManager->substituteValues(
$this->savedValues,
trim($params->getRaw())
);
$newRequestParams = (array) json_decode($processedParams, true, 512, JSON_THROW_ON_ERROR);
$newRequestParams = $this->convertRunnableCodeParams($newRequestParams);
/** @var array<string, mixed> $requestParams */
$requestParams = array_merge($this->requestParams, $newRequestParams);
$this->requestParams = $requestParams;
/** @var array<string, mixed> $savedValues */
$savedValues = array_merge($this->savedValues, $newRequestParams);
$this->savedValues = $savedValues;
}
/**
* For POST, PUT, and PATCH, the body is JSON-encoded when Content-Type contains
* application/json (set via a quoted header step or Given the request JSON content type is used).
* Otherwise parameters are sent as form fields.
*
* @When I send :method request to :route route
*/
public function iSendRequestToRoute(
string $method,
string $route
): void {
$routeParams = $this->popRouteAttributesFromRequestParams($route, $this->requestParams);
$postFields = [];
$queryString = '';
$content = null;
$url = $this->router->generate($route, $routeParams);
$url = preg_replace('|^/app[^.]*\.php|', '', $url);
if (Request::METHOD_GET === $method) {
$queryString = http_build_query($this->requestParams);
}
if (in_array($method, [Request::METHOD_POST, Request::METHOD_PATCH, Request::METHOD_PUT], true)) {
$isJsonRequest = array_key_exists('Content-Type', $this->headers) &&
str_contains(strtolower($this->headers['Content-Type']), 'application/json');
if ($isJsonRequest) {
$content = json_encode($this->requestParams, JSON_THROW_ON_ERROR);
} else {
$postFields = $this->requestParams;
}
}
$request = Request::create(
uri: $url . '?' . $queryString,
method: $method,
parameters: $postFields,
content: $content
);
$request->headers->add($this->headers);
$request->server->add($this->serverParams);
$this->response = $this->handleRequestWithKernel($request);
$this->resetRequestOptions();
}
private function handleRequestWithKernel(Request $request): Response
{
$request->headers->add($this->headers);
$request->server->add($this->serverParams);
$response = $this->kernel->handle($request);
$this->requestStack->pop();
if ($this->kernel instanceof TerminableInterface) {
$this->kernel->terminate($request, $response);
}
foreach ($this->resetManagers as $resetManager) {
if ($resetManager->needsReset($request->getMethod())) {
$resetManager->reset($this->kernel);
}
}
return $response;
}
/**
* @param array<string, mixed> $requestParams
*
* @return array<string, mixed>
*/
private function popRouteAttributesFromRequestParams(string $route, array &$requestParams): array
{
$routeParams = [];
$routeDecl = $this->router->getRouteCollection()->get($route);
if ($routeDecl !== null) {
/** @var array<string, string> $requirements */
$requirements = $routeDecl->getRequirements();
foreach ($requirements as $attribute => $requirement) {
if (isset($requestParams[$attribute]) && !str_starts_with($attribute, '_')) {
$routeParams[$attribute] = $requestParams[$attribute];
unset($requestParams[$attribute]);
}
}
}
return $routeParams;
}
/**
* @Then response status code should be :httpStatus
*/
public function responseStatusCodeShouldBe(string $httpStatus): void
{
$response = $this->getResponse();
if ((string) $response->getStatusCode() !== $httpStatus) {
$message = sprintf(
'HTTP code does not match %s (actual: %s). Response: %s',
$httpStatus,
$response->getStatusCode(),
$response->sendContent()
);
throw new RuntimeException($message);
}
}
/**
* @Then response is JSON
*/
public function responseIsJson(): void
{
$response = $this->getResponse();
$body = $this->getResponseBody($response);
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if (empty($data)) {
throw new RuntimeException("Response was not JSON\n" . $body);
}
}
/**
* @Then response should be empty
*/
public function responseEmpty(): void
{
if ($this->getResponseBody($this->getResponse()) !== '') {
throw new RuntimeException('Content not empty');
}
}
/**
* @param PyStringNode $string
*
* @Then response should be JSON:
*/
public function responseShouldBeJson(PyStringNode $string): void
{
$expectedResponse = json_decode(trim($string->getRaw()), true, 512, JSON_THROW_ON_ERROR);
$actualResponse = json_decode($this->getResponseBody($this->getResponse()), true, 512, JSON_THROW_ON_ERROR);
if ($expectedResponse !== $actualResponse) {
$prettyJSON = json_encode($actualResponse, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT, 512);
$message = sprintf("Expected JSON does not match actual JSON:\n%s\n", $prettyJSON);
throw new RuntimeException($message);
}
}
/**
* @When I save :paramPath param from json response as :valueKey
*/
public function iGetParamFromJsonResponse(string $paramPath, string $valueKey): void
{
$actualResponse = json_decode($this->getResponseBody($this->getResponse()), true, 512, JSON_THROW_ON_ERROR);
$pathKeys = explode('.', $paramPath);
foreach ($pathKeys as $key) {
if (!isset($actualResponse[$key])) {
throw new RuntimeException(sprintf('Response does not contain param "%s"', $paramPath));
}
$actualResponse = $actualResponse[$key];
}
$this->savedValues[$valueKey] = $actualResponse;
}
/**
* phpcs:disable SlevomatCodingStandard.Namespaces.UnusedUses.MismatchingCaseSensitivity
* @Then response should be JSON with variable fields :variableFields:
* phpcs:enable
*/
public function responseShouldBeJsonWithVariableFields(string $variableFields, PyStringNode $string): void
{
$this->compareStructureResponse($variableFields, $string, $this->getResponseBody($this->getResponse()));
}
protected function compareStructureResponse(
string $variableFieldsString,
PyStringNode $string,
string $actualJSON
): void {
if ($actualJSON === '') {
throw new RuntimeException('Response is not JSON');
}
$expectedResponse = json_decode(trim($string->getRaw()), true, 512, JSON_THROW_ON_ERROR);
$actualResponse = json_decode($actualJSON, true, 512, JSON_THROW_ON_ERROR);
$variableFields = $variableFieldsString
? array_map('trim', explode(',', $variableFieldsString))
: [];
if (!$this->similarArrayManager->isArraysSimilar($expectedResponse, $actualResponse, $variableFields)) {
$prettyJSON = json_encode($actualResponse, JSON_PRETTY_PRINT);
$message = sprintf(
"Expected JSON is not similar to the actual JSON with variable fields:\n%s\n",
$prettyJSON
);
throw new RuntimeException($message);
}
}
/**
* @Then #^the "(?P<headerName>[^"]+)" response headers contains "(?P<headerValue>[^"]*)"$#
*/
public function theResponseHeadersContains(string $headerName, string $headerValue): void
{
$this->checkResponseHeader($headerName, $headerValue);
}
/**
* @And #^the "(?P<headerName>[^"]+)" response headers contains "(?P<headerValue>[^"]*)"$#
*/
public function theAndResponseHeadersContains(string $headerName, string $headerValue): void
{
$this->checkResponseHeader($headerName, $headerValue);
}
protected function checkResponseHeader(string $headerName, string $headerValue): void
{
$givenHeaderName = $this->stringManager->substituteValues(
$this->savedValues,
trim($headerName),
);
$givenHeaderValue = $this->stringManager->substituteValues(
$this->savedValues,
trim($headerValue),
);
$response = $this->getResponse();
if (!$response->headers->has($givenHeaderName)) {
$message = sprintf(
'Response header %s does not exists',
$givenHeaderName,
);
throw new RuntimeException($message);
}
$responseHeaderValue = $response->headers->get($givenHeaderName);
if (null === $responseHeaderValue || substr_count($responseHeaderValue, $givenHeaderValue) < 1) {
$message = sprintf(
'Response header %s does not match. Expected: %s, given value: %s',
$givenHeaderName,
$givenHeaderValue,
$responseHeaderValue,
);
throw new RuntimeException($message);
}
}
/**
* @param array<string, mixed> $requestParams
*
* @return array<string, mixed>
*/
protected function convertRunnableCodeParams(array $requestParams): array
{
foreach ($requestParams as $key => $value) {
if (is_array($value)) {
$requestParams[$key] = $this->convertRunnableCodeParams($value);
continue;
}
if (!is_string($value)) {
continue;
}
$pregMatchValue = preg_match('/^<.*>$/', trim($value));
if ($pregMatchValue === 0 || $pregMatchValue === false) {
continue;
}
$command = substr(trim($value), 1, -1);
try {
// phpcs:disable
$resultValue = eval('return ' . $command . ';');
// phpcs:enable
} catch (Throwable $exception) {
throw new RuntimeException(
sprintf(
'Failed run your code %s, error message: %s',
$value,
$exception->getMessage()
)
);
}
if (is_null($resultValue)) {
throw new \RuntimeException(
sprintf(
'Running code: %s - should not return the null',
$command
)
);
}
$requestParams[$key] = $resultValue;
}
return $requestParams;
}
private function resetRequestOptions(): void
{
$this->headers = [];
$this->serverParams = [];
$this->requestParams = [];
}
protected function getResponse(): Response
{
return $this->response;
}
/**
* @return array<string, mixed>
*/
public function geRequestParams(): array
{
return $this->requestParams;
}
private function getResponseBody(Response $response): string
{
$content = $response->getContent();
if ($content === false) {
throw new RuntimeException('The response body is not available.');
}
return $content;
}
}