-
-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathResponseTest.php
More file actions
601 lines (439 loc) · 20.5 KB
/
Copy pathResponseTest.php
File metadata and controls
601 lines (439 loc) · 20.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
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
<?php
declare(strict_types=1);
use GuzzleHttp\Psr7\Utils;
use GuzzleHttp\Psr7\Response;
use Saloon\Http\PendingRequest;
use Saloon\Contracts\ArrayStore;
use Illuminate\Support\Collection;
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\DomCrawler\Crawler;
use Saloon\Http\Response as SaloonResponse;
use Saloon\Exceptions\Request\RequestException;
use Saloon\Tests\Fixtures\Requests\UserRequest;
use Saloon\Tests\Fixtures\Connectors\TestConnector;
use Saloon\Tests\Fixtures\Requests\CustomEndpointRequest;
test('you can get the original pending request', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);
$response = connector()->send(new UserRequest, $mockClient);
$pendingRequest = $response->getPendingRequest();
expect($pendingRequest)->toBeInstanceOf(PendingRequest::class);
expect($pendingRequest->getRequest())->toBeInstanceOf(UserRequest::class);
});
test('you can get the connector', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);
$request = new UserRequest;
$connector = new TestConnector;
$response = $connector->send($request, $mockClient);
expect($response->getConnector())->toBe($connector);
});
test('you can get the original request', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);
$request = new UserRequest;
$response = connector()->send($request, $mockClient);
expect($response->getRequest())->toBe($request);
});
test('you can get the psr-7 request', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);
$request = new UserRequest;
$response = connector()->send($request, $mockClient);
expect($response->getPsrRequest())->toBeInstanceOf(RequestInterface::class);
});
test('it will throw an exception when you use the throw method', function () {
$mockClient = new MockClient([
MockResponse::make([], 500),
]);
$response = connector()->send(new UserRequest, $mockClient);
$this->expectException(RequestException::class);
$response->throw();
});
test('it wont throw an exception if the request did not fail', function () {
$mockClient = new MockClient([
MockResponse::make([], 200),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response)->throw()->toBe($response);
});
test('to exception will return a saloon request exception', function () {
$mockClient = new MockClient([
MockResponse::make([], 500),
]);
$response = connector()->send(new UserRequest, $mockClient);
$exception = $response->toException();
expect($exception)->toBeInstanceOf(RequestException::class);
});
test('to exception wont return anything if the request did not fail', function () {
$mockClient = new MockClient([
MockResponse::make([], 200),
]);
$response = connector()->send(new UserRequest, $mockClient);
$exception = $response->toException();
expect($exception)->toBeNull();
});
test('the onError method will run a custom closure', function () {
$mockClient = new MockClient([
MockResponse::make([], 500),
]);
$response = connector()->send(new UserRequest, $mockClient);
$count = 0;
$response->onError(function () use (&$count) {
$count++;
});
expect($count)->toBe(1);
});
test('the object method will return an object', function () {
$data = ['name' => 'Sam', 'work' => 'Codepotato'];
$mockClient = new MockClient([
MockResponse::make($data, 500),
]);
$response = connector()->send(new UserRequest, $mockClient);
$dataAsObject = (object)$data;
expect($response)->object()->toEqual($dataAsObject);
});
test('the object method with a dot notation key value will return a nested string', function () {
$data = [
'contacts' => [
['name' => 'Sam', 'work' => 'Codepotato'],
['name' => 'Braunson', 'work' => 'Geekybeaver'],
],
];
$mockClient = new MockClient([
MockResponse::make($data, 500),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response)->object('contacts.1.name')->toEqual('Braunson');
});
test('the collect method will return a collection', function () {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam', 'work' => 'Codepotato'], 500),
]);
$response = connector()->send(new UserRequest, $mockClient);
$collection = $response->collect();
expect($collection)->toBeInstanceOf(Collection::class);
expect($collection)->toHaveCount(2);
expect($collection['name'])->toEqual('Sam');
expect($collection['work'])->toEqual('Codepotato');
expect($response->collect('name'))->toArray()->toEqual(['Sam']);
expect($response->collect('age'))->toBeEmpty();
});
test('the json method will return empty array if body is empty', function () {
$mockClient = new MockClient([
MockResponse::make('', 404),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->json())->toBe([]);
});
test('the toPsrResponse method will return a guzzle response', function () {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam', 'work' => 'Codepotato'], 500),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response)->getPsrResponse()->toBeInstanceOf(Response::class);
});
test('you can get an individual header from the response', function () {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam', 'work' => 'Codepotato'], 200, ['X-Greeting' => 'Howdy']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response)->header('X-Greeting')->toEqual('Howdy');
expect($response)->header('X-Missing')->toBeEmpty();
});
test('it will convert the body to string if the cast is used', function () {
$data = ['name' => 'Sam', 'work' => 'Codepotato'];
$mockClient = new MockClient([
MockResponse::make($data, 200, ['X-Greeting' => 'Howdy']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect((string)$response)->toEqual(json_encode($data));
});
test('it checks statuses correctly', function () {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam', 'work' => 'Codepotato'], 200, ['X-Greeting' => 'Howdy']),
MockResponse::make(['name' => 'Sam', 'work' => 'Codepotato'], 500, ['X-Greeting' => 'Howdy']),
MockResponse::make(['name' => 'Sam', 'work' => 'Codepotato'], 302, ['X-Greeting' => 'Howdy']),
]);
$responseA = connector()->send(new UserRequest, $mockClient);
expect($responseA)->successful()->toBeTrue();
expect($responseA)->ok()->toBeTrue();
expect($responseA)->redirect()->toBeFalse();
expect($responseA)->failed()->toBeFalse();
expect($responseA)->serverError()->toBeFalse();
$responseB = connector()->send(new UserRequest, $mockClient);
expect($responseB)->successful()->toBeFalse();
expect($responseB)->ok()->toBeFalse();
expect($responseB)->redirect()->toBeFalse();
expect($responseB)->failed()->toBeTrue();
expect($responseB)->serverError()->toBeTrue();
$responseC = connector()->send(new UserRequest, $mockClient);
expect($responseC)->successful()->toBeFalse();
expect($responseC)->ok()->toBeFalse();
expect($responseC)->redirect()->toBeTrue();
expect($responseC)->failed()->toBeFalse();
expect($responseC)->serverError()->toBeFalse();
});
test('the xml method will return xml as an array', function () {
$mockClient = new MockClient([
new MockResponse('<SaveContactResponse xmlns="http://schemas.datacontract.org/2004/07/SmashFly.WebServices.ContactManagerService.v2"><ContactId>1168255</ContactId><Errors nil="true" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/><HasErrors>false</HasErrors></SaveContactResponse>', 200),
]);
$response = connector()->send(new UserRequest, $mockClient);
$simpleXml = $response->xml();
expect($simpleXml)->toBeInstanceOf(SimpleXMLElement::class);
});
test('the xmlReader method will return an XmlReader instance', function () {
$mockClient = new MockClient([
MockResponse::fixture('xml'),
]);
$request = new CustomEndpointRequest;
$request->setEndpoint('/breakfast-menu');
$response = connector()->send($request, $mockClient);
$reader = $response->xmlReader();
expect($reader->value('food.2.name')->sole())->toBe('Berry-Berry Belgian Waffles');
});
test('the headers method returns an array store', function () {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam', 'work' => 'Codepotato'], 200, ['X-Greeting' => 'Howdy']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->headers())->toBeInstanceOf(ArrayStore::class);
});
test('headers with a single value will have just the string value but headers with multiple values will be an array', function () {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam', 'work' => 'Codepotato'], 200, ['X-Greeting' => 'Howdy', 'X-Farewell' => ['Goodbye', 'Sam']]),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->headers()->get('X-Greeting'))->toEqual('Howdy');
expect($response->headers()->get('X-Farewell'))->toEqual(['Goodbye', 'Sam']);
expect($response->header('X-Greeting'))->toEqual('Howdy');
expect($response->header('X-Farewell'))->toEqual(['Goodbye', 'Sam']);
});
test('the dom method will return a crawler instance', function () {
$dom = '<p>Howdy <i>Partner</i></p>';
$mockClient = new MockClient([
new MockResponse($dom),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->dom())->toBeInstanceOf(Crawler::class);
expect($response->dom())->toEqual(new Crawler($dom));
});
test('when using the body methods the stream is rewound back to the start', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->json())->toEqual(['foo' => 'bar']);
expect($response->array())->toEqual(['foo' => 'bar']);
expect($response->body())->toEqual('{"foo":"bar"}');
expect(stream_get_contents($response->getRawStream()))->toEqual('{"foo":"bar"}');
expect($response->object())->toEqual((object)['foo' => 'bar']);
});
test('it can convert the response to a data url', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['Content-Type' => 'application/json;encoding=utf-8']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->dataUrl())->toEqual('data:application/json;encoding=utf-8;base64,eyJmb28iOiJiYXIifQ==');
});
test('if a response is changed through middleware the new instance is used', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);
$connector = new TestConnector;
$connector->middleware()->onResponse(function (SaloonResponse $response) {
// Let's modify the body while sending!
$psrResponse = $response->getPsrResponse();
$newPsrResponse = $psrResponse->withBody(Utils::streamFor('Hello World!'));
return $response::fromPsrResponse($newPsrResponse, $response->getPendingRequest(), $response->getPsrRequest());
});
$response = $connector->send(new UserRequest, $mockClient);
expect($response->body())->toEqual('Hello World!');
expect($response->headers()->all())->toEqual(['X-Custom-Header' => 'Howdy']);
});
test('you can get the response stream as a raw resource', function () {
$response = connector()->send(new UserRequest);
$resource = $response->getRawStream();
expect($resource)->toBeResource();
expect(stream_get_contents($resource))->toEqual('{"name":"Sammyjo20","actual_name":"Sam","twitter":"@carre_sam"}');
});
test('you can get the response stream as a raw resource with a mock response', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);
$response = connector()->send(new UserRequest, $mockClient);
$resource = $response->getRawStream();
expect($resource)->toBeResource();
expect(stream_get_contents($resource))->toEqual('{"foo":"bar"}');
});
test('you can get save the response to a file', function (mixed $resourceOrPath) {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);
$response = connector()->send(new UserRequest, $mockClient);
$response->saveBodyToFile($resourceOrPath);
if (is_string($resourceOrPath)) {
$path = 'tests/Fixtures/Saloon/Testing/streamToFile1.json';
} else {
$path = 'tests/Fixtures/Saloon/Testing/streamToFile2.json';
}
expect(file_get_contents($path))->toEqual('{"foo":"bar"}');
})->with([
'tests/Fixtures/Saloon/Testing/streamToFile1.json',
fn () => fopen('tests/Fixtures/Saloon/Testing/streamToFile2.json', 'wb+'),
]);
test('saveBodyToFile is backwards compatible when validatePath is disabled', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar']),
]);
$response = connector()->send(new UserRequest, $mockClient);
$path = sys_get_temp_dir().'/saloon_bc_'.uniqid('', true).'.json';
$response->saveBodyToFile($path);
expect(file_get_contents($path))->toEqual('{"foo":"bar"}');
unlink($path);
});
test('saveBodyToFile does not validate paths when validatePath is disabled', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect(fn () => $response->saveBodyToFile('../unvalidated-path.json'))
->not->toThrow(\InvalidArgumentException::class);
});
test('saveBodyToFile saves to a safe path when validatePath is enabled', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar']),
]);
$response = connector()->send(new UserRequest, $mockClient);
$path = sys_get_temp_dir().'/saloon_safe_'.uniqid('', true).'.json';
$response->saveBodyToFile($path, true, true);
expect(file_get_contents($path))->toEqual('{"foo":"bar"}');
unlink($path);
});
test('saveBodyToFile rejects path traversal when validatePath is enabled', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar']),
]);
$response = connector()->send(new UserRequest, $mockClient);
$path = sys_get_temp_dir().'/../../../etc/passwd';
expect(fn () => $response->saveBodyToFile($path, true, true))
->toThrow(InvalidArgumentException::class, 'Path traversal detected.');
});
test('saveBodyToFile rejects stream wrappers when validatePath is enabled', function (string $path, string $message) {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect(fn () => $response->saveBodyToFile($path, true, true))
->toThrow(InvalidArgumentException::class, $message);
})->with([
['phar://malicious.phar/payload.php', 'Stream wrappers are not allowed.'],
['php://filter/read=convert.base64-encode/resource=index.php', 'Stream wrappers are not allowed.'],
['data://text/plain,test', 'Stream wrappers are not allowed.'],
]);
test('getRawStream remains backwards compatible when validatePath is disabled', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar']),
]);
$response = connector()->send(new UserRequest, $mockClient);
$resource = $response->getRawStream();
expect($resource)->toBeResource();
expect(stream_get_contents($resource))->toEqual('{"foo":"bar"}');
});
test('getRawStream works when validatePath is enabled', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar']),
]);
$response = connector()->send(new UserRequest, $mockClient);
$resource = $response->getRawStream(validatePath: true);
expect($resource)->toBeResource();
expect(stream_get_contents($resource))->toEqual('{"foo":"bar"}');
});
test('the response is macroable', function () {
SaloonResponse::macro('yee', fn () => 'haw');
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->yee())->toEqual('haw');
});
test('can determine if response is JSON', function () {
$mockClient = new MockClient([
// JSON content type
MockResponse::make(['foo' => 'bar'], 200, ['Content-Type' => 'application/json']),
// JSON with charset
MockResponse::make(['foo' => 'bar'], 200, ['Content-Type' => 'application/json; charset=utf-8']),
// JSON with lowercase header (e.g. FastAPI, HTTP/2)
MockResponse::make(['foo' => 'bar'], 200, ['content-type' => 'application/json']),
// Non-JSON content type
MockResponse::make('plain text', 200, ['Content-Type' => 'text/plain']),
// No content type
MockResponse::make('no content type', 200, []),
]);
$connector = connector();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isJson())->toBeTrue();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isJson())->toBeTrue();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isJson())->toBeTrue();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isJson())->toBeFalse();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isJson())->toBeFalse();
});
test('can determine if response is XML', function () {
$mockClient = new MockClient([
// XML content type
MockResponse::make('<?xml version="1.0"?><root></root>', 200, ['Content-Type' => 'application/xml']),
// XML with charset
MockResponse::make('<?xml version="1.0"?><root></root>', 200, ['Content-Type' => 'text/xml; charset=utf-8']),
// XML with lowercase header (e.g. FastAPI, HTTP/2)
MockResponse::make('<?xml version="1.0"?><root></root>', 200, ['content-type' => 'application/xml']),
// Non-XML content type
MockResponse::make('plain text', 200, ['Content-Type' => 'text/plain']),
// No content type
MockResponse::make('no content type', 200, []),
]);
$connector = connector();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isXml())->toBeTrue();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isXml())->toBeTrue();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isXml())->toBeTrue();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isXml())->toBeFalse();
$response = $connector->send(new UserRequest, $mockClient);
expect($response->isXml())->toBeFalse();
});
test('header lookup is case-insensitive per HTTP RFC', function () {
$mockClient = new MockClient([
MockResponse::make([], 200, ['x-my-custom-header' => 'custom-value']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->header('X-My-Custom-Header'))->toEqual('custom-value');
expect($response->header('x-my-custom-header'))->toEqual('custom-value');
});
test('isJson lookup can use case insensitive headers', function () {
$mockClient = new MockClient([
MockResponse::make([], 200, ['content-type' => 'application/JSON']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->isJson())->toBeTrue();
expect($response->isXml())->toBeFalse();
});
test('isXml lookup can use case insensitive headers', function () {
$mockClient = new MockClient([
MockResponse::make([], 200, ['content-type' => 'text/xml']),
]);
$response = connector()->send(new UserRequest, $mockClient);
expect($response->isXml())->toBeTrue();
expect($response->isJson())->toBeFalse();
});