Repository navigation
Expand file tree
/
Copy pathHttpResponse.php
More file actions
515 lines (437 loc) · 13 KB
/
Copy pathHttpResponse.php
File metadata and controls
515 lines (437 loc) · 13 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace HyperfTest\Resource;
use Hyperf\Collection\Arr;
use Hyperf\HttpMessage\Server\Response;
use Hyperf\Stringable\Str;
use PHPUnit\Framework\Assert as PHPUnit;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
use function Hyperf\Collection\data_get;
/**
* Class HttpResponse.
*
* @mixin Response
*/
class HttpResponse
{
/**
* The response to delegate to.
*
* @var PsrResponseInterface
*/
public $baseResponse;
/**
* Create a new test response instance.
*
* @param PsrResponseInterface $response
*/
public function __construct($response)
{
$this->baseResponse = $response;
}
/**
* Dynamically access base response parameters.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->baseResponse->{$key};
}
/**
* Proxy isset() checks to the underlying base response.
*
* @param string $key
* @return mixed
*/
public function __isset($key)
{
return isset($this->baseResponse->{$key});
}
/**
* Handle dynamic calls into macros or pass missing methods to the base response.
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call($method, $args)
{
return $this->baseResponse->{$method}(...$args);
}
/**
* Create a new TestResponse from another response.
*
* @param PsrResponseInterface $response
* @return HttpResponse
*/
public static function fromBaseResponse($response)
{
return new static($response);
}
/**
* Assert that the response has a successful status code.
*
* @return $this
*/
public function assertSuccessful()
{
PHPUnit::assertTrue(
$this->isSuccessful(),
'Response status code [' . $this->getStatusCode() . '] is not a successful status code.'
);
return $this;
}
/**
* Assert that the response has a 200 status code.
*
* @return $this
*/
public function assertOk()
{
PHPUnit::assertTrue(
$this->isOk(),
'Response status code [' . $this->getStatusCode() . '] does not match expected 200 status code.'
);
return $this;
}
/**
* Assert that the response has a not found status code.
*
* @return $this
*/
public function assertNotFound()
{
PHPUnit::assertTrue(
$this->isNotFound(),
'Response status code [' . $this->getStatusCode() . '] is not a not found status code.'
);
return $this;
}
/**
* Assert that the response has a forbidden status code.
*
* @return $this
*/
public function assertForbidden()
{
PHPUnit::assertTrue(
$this->isForbidden(),
'Response status code [' . $this->getStatusCode() . '] is not a forbidden status code.'
);
return $this;
}
/**
* Assert that the response has the given status code.
*
* @param int $status
* @return $this
*/
public function assertStatus($status)
{
$actual = $this->getStatusCode();
PHPUnit::assertTrue(
$actual === $status,
"Expected status code {$status} but received {$actual}."
);
return $this;
}
/**
* Assert whether the response is redirecting to a given URI.
*
* @param string $uri
* @return $this
*/
public function assertRedirect($uri = null)
{
PHPUnit::assertTrue(
$this->isRedirect(),
'Response status code [' . $this->getStatusCode() . '] is not a redirect status code.'
);
if (! is_null($uri)) {
$this->assertLocation($uri);
}
return $this;
}
/**
* Assert that the response is a superset of the given JSON.
*
* @param bool $strict
* @return $this
*/
public function assertJson(array $data, $strict = false)
{
if ($strict) {
PHPUnit::assertSame($data, $this->decodeResponseJson());
} else {
PHPUnit::assertEquals($data, $this->decodeResponseJson());
}
return $this;
}
/**
* Assert that the response has the exact given JSON.
*
* @return $this
*/
public function assertExactJson(array $data)
{
$actual = json_encode(Arr::sortRecursive(
(array) $this->decodeResponseJson()
));
PHPUnit::assertEquals(json_encode(Arr::sortRecursive($data)), $actual);
return $this;
}
/**
* Assert that the response contains the given JSON fragment.
*
* @return $this
*/
public function assertJsonFragment(array $data)
{
$actual = json_encode(Arr::sortRecursive(
(array) $this->decodeResponseJson()
));
foreach (Arr::sortRecursive($data) as $key => $value) {
$expected = $this->jsonSearchStrings($key, $value);
PHPUnit::assertTrue(
Str::contains($actual, $expected),
'Unable to find JSON fragment: ' . PHP_EOL . PHP_EOL
. '[' . json_encode([$key => $value]) . ']' . PHP_EOL . PHP_EOL
. 'within' . PHP_EOL . PHP_EOL
. "[{$actual}]."
);
}
return $this;
}
/**
* Assert that the response does not contain the given JSON fragment.
*
* @param bool $exact
* @return $this
*/
public function assertJsonMissing(array $data, $exact = false)
{
if ($exact) {
return $this->assertJsonMissingExact($data);
}
$actual = json_encode(Arr::sortRecursive(
(array) $this->decodeResponseJson()
));
foreach (Arr::sortRecursive($data) as $key => $value) {
$unexpected = $this->jsonSearchStrings($key, $value);
PHPUnit::assertFalse(
Str::contains($actual, $unexpected),
'Found unexpected JSON fragment: ' . PHP_EOL . PHP_EOL
. '[' . json_encode([$key => $value]) . ']' . PHP_EOL . PHP_EOL
. 'within' . PHP_EOL . PHP_EOL
. "[{$actual}]."
);
}
return $this;
}
/**
* Assert that the response does not contain the exact JSON fragment.
*
* @return $this
*/
public function assertJsonMissingExact(array $data)
{
$actual = json_encode(Arr::sortRecursive(
(array) $this->decodeResponseJson()
));
foreach (Arr::sortRecursive($data) as $key => $value) {
$unexpected = $this->jsonSearchStrings($key, $value);
if (! Str::contains($actual, $unexpected)) {
return $this;
}
}
PHPUnit::fail(
'Found unexpected JSON fragment: ' . PHP_EOL . PHP_EOL
. '[' . json_encode($data) . ']' . PHP_EOL . PHP_EOL
. 'within' . PHP_EOL . PHP_EOL
. "[{$actual}]."
);
}
/**
* Assert that the response has a given JSON structure.
*
* @param null|array $responseData
* @return $this
*/
public function assertJsonStructure(?array $structure = null, $responseData = null)
{
if (is_null($structure)) {
return $this->assertExactJson($this->json());
}
if (is_null($responseData)) {
$responseData = $this->decodeResponseJson();
}
foreach ($structure as $key => $value) {
if (is_array($value) && $key === '*') {
PHPUnit::assertInternalType('array', $responseData);
foreach ($responseData as $responseDataItem) {
$this->assertJsonStructure($structure['*'], $responseDataItem);
}
} elseif (is_array($value)) {
PHPUnit::assertArrayHasKey($key, $responseData);
$this->assertJsonStructure($structure[$key], $responseData[$key]);
} else {
PHPUnit::assertArrayHasKey($value, $responseData);
}
}
return $this;
}
/**
* Assert that the response JSON has the expected count of items at the given key.
*
* @param null|string $key
* @return $this
*/
public function assertJsonCount(int $count, $key = null)
{
if ($key) {
PHPUnit::assertCount(
$count,
data_get($this->json(), $key),
"Failed to assert that the response count matched the expected {$count}"
);
return $this;
}
PHPUnit::assertCount(
$count,
$this->json(),
"Failed to assert that the response count matched the expected {$count}"
);
return $this;
}
/**
* Assert that the response has the given JSON validation errors for the given keys.
*
* @param array|string $keys
* @return $this
*/
public function assertJsonValidationErrors($keys)
{
$keys = Arr::wrap($keys);
PHPUnit::assertNotEmpty($keys, 'No keys were provided.');
$errors = $this->json()['errors'] ?? [];
$errorMessage = $errors
? 'Response has the following JSON validation errors:'
. PHP_EOL . PHP_EOL . json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL
: 'Response does not have JSON validation errors.';
foreach ($keys as $key) {
PHPUnit::assertArrayHasKey(
$key,
$errors,
"Failed to find a validation error in the response for key: '{$key}'" . PHP_EOL . PHP_EOL . $errorMessage
);
}
return $this;
}
/**
* Assert that the response has no JSON validation errors for the given keys.
*
* @param array|string $keys
* @return $this
*/
public function assertJsonMissingValidationErrors($keys = null)
{
$json = $this->json();
if (! array_key_exists('errors', $json)) {
PHPUnit::assertArrayNotHasKey('errors', $json);
return $this;
}
$errors = $json['errors'];
if (is_null($keys) && count($errors) > 0) {
PHPUnit::fail(
'Response has unexpected validation errors: ' . PHP_EOL . PHP_EOL
. json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
);
}
foreach (Arr::wrap($keys) as $key) {
PHPUnit::assertFalse(
isset($errors[$key]),
"Found unexpected validation error for key: '{$key}'"
);
}
return $this;
}
/**
* Validate and return the decoded response JSON.
*
* @param null|string $key
* @return mixed
*/
public function decodeResponseJson($key = null)
{
$decodedResponse = json_decode((string) $this->getBody(), true);
if (is_null($decodedResponse) || $decodedResponse === false) {
if ($this->exception) {
throw $this->exception;
}
PHPUnit::fail('Invalid JSON was returned from the route.');
}
return data_get($decodedResponse, $key);
}
/**
* Validate and return the decoded response JSON.
*
* @param null|string $key
* @return mixed
*/
public function json($key = null)
{
return $this->decodeResponseJson($key);
}
/**
* Dump the content from the response.
*/
public function dump()
{
$content = (string) $this->getBody();
$json = json_decode($content);
if (json_last_error() === JSON_ERROR_NONE) {
$content = $json;
}
dd($content);
}
/**
* Get the assertion message for assertJson.
*
* @return string
*/
protected function assertJsonMessage(array $data)
{
$expected = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$actual = json_encode($this->decodeResponseJson(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
return 'Unable to find JSON: ' . PHP_EOL . PHP_EOL
. "[{$expected}]" . PHP_EOL . PHP_EOL
. 'within response JSON:' . PHP_EOL . PHP_EOL
. "[{$actual}]." . PHP_EOL . PHP_EOL;
}
/**
* Get the strings we need to search for when examining the JSON.
*
* @param string $key
* @param string $value
* @return array
*/
protected function jsonSearchStrings($key, $value)
{
$needle = substr(json_encode([$key => $value]), 1, -1);
return [
$needle . ']',
$needle . '}',
$needle . ',',
];
}
}