-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssertable_Json_String.php
More file actions
457 lines (389 loc) · 11.5 KB
/
Copy pathAssertable_Json_String.php
File metadata and controls
457 lines (389 loc) · 11.5 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
<?php
/**
* Assertable_Json_String class file
*
* phpcs:disable WordPress.WP.AlternativeFunctions.json_encode_json_encode
*
* @package Mantle
*/
namespace Mantle\Testing;
use ArrayAccess;
use Countable;
use JsonSerializable;
use Mantle\Contracts\Support\Jsonable;
use Mantle\Support\Arr;
use Mantle\Support\Str;
use PHPUnit\Framework\Assert as PHPUnit;
use function Mantle\Support\Helpers\data_get;
/**
* Assertions that can be made against a JSON string.
*/
class Assertable_Json_String implements ArrayAccess, Countable {
/**
* The decoded JSON contents.
*/
protected array $decoded;
/**
* Constructor.
*
* @param string|array|Jsonable|JsonSerializable $json The original encoded JSON.
*/
public function __construct( public string|array|Jsonable|JsonSerializable $json ) {
if ( $this->json instanceof JsonSerializable ) {
$this->decoded = $this->json->jsonSerialize();
} elseif ( $this->json instanceof Jsonable ) {
$this->decoded = json_decode( $this->json->to_json(), true );
} elseif ( is_array( $this->json ) ) {
$this->decoded = $this->json;
} else {
$decoded = json_decode( $this->json, true );
if ( JSON_ERROR_NONE !== json_last_error() ) {
PHPUnit::fail( 'Invalid JSON was returned from the response: ' . json_last_error_msg() );
}
if ( is_array( $decoded ) ) {
$this->decoded = $decoded;
}
}
if ( ! isset( $this->decoded ) ) {
PHPUnit::fail( 'Invalid JSON was returned from the response.' );
}
}
/**
* Retrieve the decoded JSON.
*/
public function get_decoded(): ?array {
return $this->decoded;
}
/**
* Validate and return the decoded response JSON.
*
* @param string|null $key Key to retrieve, optional.
*/
public function json( string|array|int|null $key = null ): mixed {
return data_get( $this->decoded, $key );
}
/**
* Assert that the expected value and type exists at the given path in the response.
*
* @param string $path
* @param mixed $expect
* @param string $message Optional message on failure.
*/
public function assertPath( string $path, mixed $expect, string $message = '' ): static {
PHPUnit::assertSame( $expect, $this->json( $path ), $message );
return $this;
}
/**
* Assert that the value at the given path in the response matches the given regular expression.
*
* @param string $path Path to check.
* @param string $regex Regular expression to match against.
* @param string $message Optional message on failure.
*/
public function assertPathMatches( string $path, string $regex, string $message = '' ): static {
PHPUnit::assertMatchesRegularExpression( $regex, (string) $this->json( $path ), $message );
return $this;
}
/**
* Assert that a specific path does not match the given regular expression pattern in the response.
*
* @param string $path Path to check.
* @param string $pattern Regular expression pattern to match.
* @param string $message Optional message on failure.
*/
public function assertPathNotMatches( string $path, string $pattern, string $message = '' ): static {
PHPUnit::assertDoesNotMatchRegularExpression( $pattern, (string) $this->json( $path ), $message );
return $this;
}
/**
* Assert that a specific path exists in the response.
*
* @param string $path Path to check.
* @param string $message Optional message on failure.
*/
public function assertPathExists( string $path, string $message = '' ): static {
PHPUnit::assertNotNull( $this->json( $path ), $message );
return $this;
}
/**
* Assert that a specific path does not exist in the response.
*
* @param string $path Path to check.
* @param string $message Optional message on failure.
*/
public function assertPathMissing( string $path, string $message = '' ): static {
PHPUnit::assertNull( $this->json( $path ), $message );
return $this;
}
/**
* Assert that a specific path is empty in the response.
*
* @param string $path Path to check.
* @param string $message Optional message on failure.
*/
public function assertPathEmpty( string $path, string $message = '' ): static {
PHPUnit::assertEmpty( $this->json( $path ), $message );
return $this;
}
/**
* Assert that a specific path is not empty in the response.
*
* @param string $path Path to check.
* @param string $message Optional message on failure.
*/
public function assertPathNotEmpty( string $path, string $message = '' ): static {
PHPUnit::assertNotEmpty( $this->json( $path ), $message );
return $this;
}
/**
* Assert that a specific path contains the given string value in the response.
*
* @param string $path Path to check.
* @param string $needle Value to check for.
* @param string $message Optional message on failure.
*/
public function assertPathContains( string $path, string $needle, string $message = '' ): static {
PHPUnit::assertStringContainsString(
$needle,
(string) $this->json( $path ),
$message,
);
return $this;
}
/**
* Assert that a specific path does not contain the given string value in the response.
*
* @param string $path Path to check.
* @param string $needle Value to check for.
* @param string $message Optional message on failure.
*/
public function assertPathNotContains( string $path, string $needle, string $message = '' ): static {
PHPUnit::assertStringNotContainsString(
$needle,
(string) $this->json( $path ),
$message,
);
return $this;
}
/**
* Assert that the value at the given path in the response passes the given truth test.
*
* @param string $path Path to check.
* @param callable $callback Callback that receives the value and returns true if it passes.
* @param string $message Optional message on failure.
*
* @phpstan-param (callable(mixed): bool) $callback
*/
public function assertPathCallback( string $path, callable $callback, string $message = '' ): static {
$value = $this->json( $path );
if ( empty( $message ) ) {
$message = "The value at path [{$path}] did not pass the given truth test.";
}
PHPUnit::assertTrue( (bool) $callback( $value ), $message );
return $this;
}
/**
* Assert that the response has the similar JSON as given.
*
* @param array $data
*/
public function assertSimilar( array $data ): static {
$actual = json_encode( Arr::sort_recursive(
$this->decoded
) );
PHPUnit::assertEquals( json_encode( Arr::sort_recursive( $data ) ), $actual );
return $this;
}
/**
* Assert that the response has a given JSON structure.
*
* @param array|null $structure
* @param array|null $response_data
* @return static
*/
public function assertStructure( ?array $structure = null, $response_data = null ) {
if ( is_null( $structure ) ) {
return $this->assertSimilar( $this->decoded );
}
if ( ! is_null( $response_data ) ) {
return ( new static( $response_data ) )->assertStructure( $structure );
}
foreach ( $structure as $key => $value ) {
if ( is_array( $value ) && '*' === $key ) {
PHPUnit::assertIsArray( $this->decoded ); // @phpstan-ignore-line
foreach ( $this->decoded as $item ) {
$this->assertStructure( $structure['*'], $item );
}
} elseif ( is_array( $value ) ) {
PHPUnit::assertArrayHasKey( $key, $this->decoded );
$this->assertStructure( $structure[ $key ], $this->decoded[ $key ] );
} else {
PHPUnit::assertArrayHasKey( $value, $this->decoded );
}
}
return $this;
}
/**
* Assert that the response has the exact given JSON.
*
* @param array $data
*/
public function assertExact( array $data ): static {
$actual = wp_json_encode(
Arr::sort_recursive(
(array) $this->json()
)
);
PHPUnit::assertEquals( wp_json_encode( Arr::sort_recursive( $data ) ), $actual );
return $this;
}
/**
* Assert that the response contains the given JSON fragment.
*
* @param array $data Data to compare.
*/
public function assertFragment( array $data ): static {
$actual = (string) wp_json_encode(
Arr::sort_recursive(
(array) $this->json()
)
);
foreach ( Arr::sort_recursive( $data ) as $key => $value ) {
$expected = $this->json_search_strings( $key, $value );
PHPUnit::assertTrue(
Str::contains( $actual, $expected ),
'Unable to find JSON fragment: ' . PHP_EOL . PHP_EOL .
'[' . wp_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 array $data Data to compare.
* @param bool $exact Flag for exact match, defaults to false.
*/
public function assertMissing( array $data, $exact = false ): static {
if ( $exact ) {
return $this->assertMissingExact( $data );
}
$actual = (string) wp_json_encode(
Arr::sort_recursive(
(array) $this->json()
)
);
foreach ( Arr::sort_recursive( $data ) as $key => $value ) {
$unexpected = $this->json_search_strings( $key, $value );
PHPUnit::assertFalse(
Str::contains( $actual, $unexpected ),
'Found unexpected JSON fragment: ' . PHP_EOL . PHP_EOL .
'[' . wp_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.
*
* @param array $data
*/
public function assertMissingExact( array $data ): static {
$actual = (string) wp_json_encode(
Arr::sort_recursive(
(array) $this->json()
)
);
foreach ( Arr::sort_recursive( $data ) as $key => $value ) {
$unexpected = $this->json_search_strings( $key, $value );
if ( ! Str::contains( $actual, $unexpected ) ) {
return $this;
}
}
PHPUnit::fail(
'Found unexpected JSON fragment: ' . PHP_EOL . PHP_EOL .
'[' . wp_json_encode( $data ) . ']' . PHP_EOL . PHP_EOL .
'within' . PHP_EOL . PHP_EOL .
"[{$actual}]."
);
}
/**
* Assert that the response JSON has the expected count of items at the given key.
*
* @param int $count
* @param string|null $key
*/
public function assertCount( int $count, $key = null ): static {
if ( ! is_null( $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;
}
/**
* Get the strings we need to search for when examining the JSON.
*
* @param string $key
* @param string $value
*/
protected function json_search_strings( $key, $value ): array {
$needle = substr( (string) wp_json_encode( [ $key => $value ] ), 1, -1 );
return [
$needle . ']',
$needle . '}',
$needle . ',',
];
}
/**
* Get the total number of items in the underlying JSON array.
*/
public function count(): int {
return count( $this->decoded );
}
/**
* Determine whether an offset exists.
*
* @param mixed $offset
*/
public function offsetExists( $offset ): bool {
return isset( $this->decoded[ $offset ] );
}
/**
* Get the value at the given offset.
*
* @param string $offset
*/
public function offsetGet( $offset ): mixed {
return $this->decoded[ $offset ];
}
/**
* Set the value at the given offset.
*
* @param string $offset
* @param mixed $value
*/
public function offsetSet( $offset, $value ): void {
$this->decoded[ $offset ] = $value;
}
/**
* Unset the value at the given offset.
*
* @param string $offset
*/
public function offsetUnset( $offset ): void {
unset( $this->decoded[ $offset ] );
}
}