-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathClientTest.php
More file actions
826 lines (746 loc) · 25.5 KB
/
ClientTest.php
File metadata and controls
826 lines (746 loc) · 25.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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
<?php
namespace Utopia\Fetch;
use PHPUnit\Framework\TestCase;
use Utopia\Fetch\Adapter\Curl;
use Utopia\Fetch\Adapter\Swoole;
final class ClientTest extends TestCase
{
/**
* Test that Client uses Curl adapter by default
*/
public function testDefaultAdapter(): void
{
$client = new Client();
$response = $client->fetch('127.0.0.1:8000', Client::METHOD_GET);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame(200, $response->getStatusCode());
}
/**
* Test that Client can use a custom adapter
*/
public function testCustomAdapter(): void
{
$client = new Client(new Curl());
$response = $client->fetch('127.0.0.1:8000', Client::METHOD_GET);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame(200, $response->getStatusCode());
}
/**
* Test that Client works with Swoole adapter if available
*/
public function testSwooleAdapter(): void
{
if (!class_exists('Swoole\Coroutine\Http\Client')) {
$this->markTestSkipped('Swoole extension is not installed');
}
$client = new Client(new Swoole());
$response = $client->fetch('127.0.0.1:8000', Client::METHOD_GET);
$this->assertInstanceOf(Response::class, $response);
$this->assertSame(200, $response->getStatusCode());
}
/**
* End to end test for Client::fetch
* Uses the PHP inbuilt server to test the Client::fetch method
* @runInSeparateProcess
* @dataProvider dataSet
* @param string $url
* @param string $method
* @param array<string, mixed>|string|null $body
* @param array<string, string> $headers
* @param array<string, mixed> $query
* @return void
*/
public function testFetch(
$url,
$method,
$body = [],
$headers = [],
$query = []
): void {
$resp = null;
try {
$client = new Client();
foreach ($headers as $key => $value) {
$client->addHeader($key, $value);
}
$resp = $client->fetch(
url: $url,
method: $method,
body: $body,
query: $query
);
} catch (Exception $e) {
echo $e;
return;
}
if ($resp->getStatusCode() === 200) { // If the response is OK
$respData = $resp->json(); // Convert body to array
$this->assertIsArray($respData);
$this->assertSame($respData['method'], $method); // Assert that the method is equal to the response's method
if ($method != Client::METHOD_GET) {
if (empty($body)) { // if body is empty then response body should be an empty string
$this->assertSame($respData['body'], '');
} else {
if ($headers['content-type'] != "application/x-www-form-urlencoded") {
$this->assertSame( // Assert that the body is equal to the response's body
$respData['body'],
is_string($body) ? $body : json_encode($body) // Converting the body to JSON string
);
}
}
}
$this->assertSame($respData['url'], $url); // Assert that the url is equal to the response's url
$this->assertSame(
json_encode($respData['query']), // Converting the query to JSON string
json_encode($query) // Converting the query to JSON string
); // Assert that the args are equal to the response's args
$this->assertIsString($respData['headers']);
$respHeaders = json_decode($respData['headers'], true); // Converting the headers to array
$this->assertIsArray($respHeaders);
$host = $respHeaders['Host'];
$this->assertSame($host, $url); // Assert that the host is equal to the response's host
// Check content-type only when headers were provided or body was sent
if (!empty($headers) || !empty($body)) {
if (array_key_exists('Content-Type', $respHeaders)) {
$contentType = $respHeaders['Content-Type'];
} else {
$contentType = $respHeaders['content-type'] ?? null;
}
if ($contentType !== null) {
$this->assertIsString($contentType);
$contentType = explode(';', $contentType)[0];
if (!empty($headers)) {
$this->assertSame($contentType, $headers['content-type']); // Assert that the content-type is equal to the response's content-type
} else {
$this->assertSame($contentType, 'application/json');
}
}
}
} else { // If the response is not OK
echo "Please configure your PHP inbuilt SERVER";
}
}
/**
* Test for sending a file in the request body
* @dataProvider sendFileDataSet
* @return void
*/
public function testSendFile(
string $path,
string $contentType,
string $fileName
): void {
$resp = null;
try {
$client = new Client();
$client->addHeader('Content-type', 'multipart/form-data');
$resp = $client->fetch(
url: '127.0.0.1:8000',
method: Client::METHOD_POST,
body: [
'file' => new \CURLFile(strval(realpath($path)), $contentType, $fileName)
],
query: []
);
} catch (Exception $e) {
echo $e;
return;
}
if ($resp->getStatusCode() === 200) { // If the response is OK
$respData = $resp->json(); // Convert body to array
$this->assertIsArray($respData);
if (isset($respData['method'])) {
$this->assertSame($respData['method'], Client::METHOD_POST);
} // Assert that the method is equal to the response's method
$this->assertSame($respData['url'], '127.0.0.1:8000'); // Assert that the url is equal to the response's url
$this->assertSame(
json_encode($respData['query']), // Converting the query to JSON string
json_encode([]) // Converting the query to JSON string
); // Assert that the args are equal to the response's args
$files = [ // Expected files array from response
'file' => [
'name' => $fileName,
'full_path' => $fileName,
'type' => $contentType,
'error' => 0
]
];
$this->assertIsString($respData['files']);
$resp_files = json_decode($respData['files'], true);
$this->assertIsArray($resp_files);
$this->assertSame($files['file']['name'], $resp_files['file']['name']);
$this->assertSame($files['file']['full_path'], $resp_files['file']['full_path']);
$this->assertSame($files['file']['type'], $resp_files['file']['type']);
$this->assertSame($files['file']['error'], $resp_files['file']['error']);
} else { // If the response is not OK
echo "Please configure your PHP inbuilt SERVER";
}
}
/**
* Test for getting a file as a response
* @dataProvider getFileDataSet
* @return void
*/
public function testGetFile(
string $path,
string $type
): void {
$resp = null;
try {
$client = new Client();
$resp = $client->fetch(
url: '127.0.0.1:8000/' . $type,
method: Client::METHOD_GET,
body: [],
query: []
);
} catch (Exception $e) {
echo $e;
return;
}
if ($resp->getStatusCode() === 200) { // If the response is OK
$data = fopen($path, 'rb');
$size = filesize($path);
if ($data && $size) {
$contents = fread($data, $size);
fclose($data);
$this->assertSame($resp->getBody(), $contents); // Assert that the body is equal to the expected file contents
} else {
echo "Invalid file path in testcase";
}
} else { // If the response is not OK
echo "Please configure your PHP inbuilt SERVER";
}
}
/**
* Test for redirect
* @return void
*/
public function testRedirect(): void
{
$resp = null;
try {
$client = new Client();
$resp = $client->fetch(
url: '127.0.0.1:8000/redirect',
method: Client::METHOD_GET,
body: [],
query: []
);
} catch (Exception $e) {
echo $e;
return;
}
if ($resp->getStatusCode() === 200) { // If the response is OK
$respData = $resp->json(); // Convert body to array
$this->assertIsArray($respData);
$this->assertSame($respData['page'], "redirectedPage"); // Assert that the page is the redirected page
} else { // If the response is not OK
echo "Please configure your PHP inbuilt SERVER";
}
}
/**
* Test setting and getting the timeout.
* @return void
*/
public function testSetGetTimeout(): void
{
$client = new Client();
$timeout = 10;
$client->setTimeout($timeout);
$this->assertSame($timeout, $client->getTimeout());
}
/**
* Test setting and getting the allowRedirects flag.
* @return void
*/
public function testSetGetAllowRedirects(): void
{
$client = new Client();
$allowRedirects = true;
$client->setAllowRedirects($allowRedirects);
$this->assertSame($allowRedirects, $client->getAllowRedirects());
}
/**
* Test setting and getting the maxRedirects.
* @return void
*/
public function testSetGetMaxRedirects(): void
{
$client = new Client();
$maxRedirects = 5;
$client->setMaxRedirects($maxRedirects);
$this->assertSame($maxRedirects, $client->getMaxRedirects());
}
/**
* Test setting and getting the connectTimeout.
* @return void
*/
public function testSetGetConnectTimeout(): void
{
$client = new Client();
$connectTimeout = 5;
$client->setConnectTimeout($connectTimeout);
$this->assertSame($connectTimeout, $client->getConnectTimeout());
}
/**
* Test setting and getting the userAgent.
* @return void
*/
public function testSetGetUserAgent(): void
{
$client = new Client();
$userAgent = "MyCustomUserAgent/1.0";
$client->setUserAgent($userAgent);
$this->assertSame($userAgent, $client->getUserAgent());
}
/**
* Test setting and getting the base URL.
* @return void
*/
public function testSetGetBaseUrl(): void
{
$client = new Client();
$baseUrl = "http://localhost:8000";
$client->setBaseUrl($baseUrl);
$this->assertEquals($baseUrl, $client->getBaseUrl());
}
/**
* Test base URL prepending to relative URLs.
* @return void
*/
public function testBaseUrlWithRelativePath(): void
{
$client = new Client();
$client->setBaseUrl('http://localhost:8000');
$resp = $client->fetch(
url: '',
method: Client::METHOD_GET
);
if ($resp->getStatusCode() === 200) {
/** @var array<string, mixed> $respData */
$respData = $resp->json();
$this->assertEquals($respData['method'], Client::METHOD_GET);
$this->assertEquals($respData['url'], 'localhost:8000');
} else {
echo "Please configure your PHP inbuilt SERVER";
}
}
/**
* Test base URL with path appending.
* @return void
*/
public function testBaseUrlWithPath(): void
{
$client = new Client();
$client->setBaseUrl('http://localhost:8000');
$resp = $client->fetch(
url: 'redirect',
method: Client::METHOD_GET
);
if ($resp->getStatusCode() === 200) {
/** @var array<string, mixed> $respData */
$respData = $resp->json();
$this->assertEquals($respData['page'], "redirectedPage");
} else {
echo "Please configure your PHP inbuilt SERVER";
}
}
/**
* Test base URL doesn't interfere with absolute URLs.
* @return void
*/
public function testBaseUrlWithAbsoluteUrl(): void
{
$client = new Client();
$client->setBaseUrl('http://example.com');
$resp = $client->fetch(
url: 'http://localhost:8000',
method: Client::METHOD_GET
);
if ($resp->getStatusCode() === 200) {
/** @var array<string, mixed> $respData */
$respData = $resp->json();
$this->assertEquals($respData['method'], Client::METHOD_GET);
$this->assertEquals($respData['url'], 'localhost:8000');
} else {
echo "Please configure your PHP inbuilt SERVER";
}
}
/**
* Test base URL with query parameters.
* @return void
*/
public function testBaseUrlWithQuery(): void
{
$client = new Client();
$client->setBaseUrl('http://localhost:8000');
$resp = $client->fetch(
url: '',
method: Client::METHOD_GET,
query: [
'name' => 'John Doe',
'age' => '30',
]
);
if ($resp->getStatusCode() === 200) {
/** @var array<string, mixed> $respData */
$respData = $resp->json();
$this->assertEquals($respData['method'], Client::METHOD_GET);
$this->assertEquals(
json_encode($respData['query']),
json_encode(['name' => 'John Doe', 'age' => '30'])
);
} else {
echo "Please configure your PHP inbuilt SERVER";
}
}
/**
* Test base URL with trailing slash normalization.
* @return void
*/
public function testBaseUrlTrailingSlashNormalization(): void
{
$client = new Client();
// Test with trailing slash in base URL
$client->setBaseUrl('http://localhost:8000/');
$resp = $client->fetch(
url: '/redirect',
method: Client::METHOD_GET
);
if ($resp->getStatusCode() === 200) {
/** @var array<string, mixed> $respData */
$respData = $resp->json();
$this->assertEquals($respData['page'], "redirectedPage");
} else {
echo "Please configure your PHP inbuilt SERVER";
}
}
/**
* Data provider for testFetch
* @return array<string, array<mixed>>
*/
public function dataSet(): array
{
return [
'get' => [
'127.0.0.1:8000',
Client::METHOD_GET
],
'getWithQuery' => [
'127.0.0.1:8000',
Client::METHOD_GET,
[],
[],
[
'name' => 'John Doe',
'age' => '30',
],
],
'postNoBody' => [
'127.0.0.1:8000',
Client::METHOD_POST
],
'postJsonBody' => [
'127.0.0.1:8000',
Client::METHOD_POST,
[
'name' => 'John Doe',
'age' => 30,
],
[
'content-type' => 'application/json'
],
],
'postSingleLineJsonStringBody' => [
'127.0.0.1:8000',
Client::METHOD_POST,
'{"name": "John Doe","age": 30}',
[
'content-type' => 'application/json'
]
],
'postMultiLineJsonStringBody' => [
'127.0.0.1:8000',
Client::METHOD_POST,
'{
"name": "John Doe",
"age": 30
}',
[
'content-type' => 'application/json'
]
],
'postFormDataBody' => [
'127.0.0.1:8000',
Client::METHOD_POST,
[
'name' => 'John Doe',
'age' => 30,
],
[
'content-type' => 'application/x-www-form-urlencoded'
],
]
];
}
/**
* Data provider for testSendFile
* @return array<string, array<mixed>>
*/
public function sendFileDataSet(): array
{
return [
'imageFile' => [
__DIR__ . '/resources/logo.png',
'image/png',
'logo.png'
],
'textFile' => [
__DIR__ . '/resources/test.txt',
'text/plain',
'text.txt'
],
];
}
/**
* Data provider for testGetFile
* @return array<string, array<mixed>>
*/
public function getFileDataset(): array
{
return [
'imageFile' => [
__DIR__ . '/resources/logo.png',
'image'
],
'textFile' => [
__DIR__ . '/resources/test.txt',
'text'
],
];
}
/**
* Test for retry functionality
* @return void
*/
public function testRetry(): void
{
$client = new Client();
$client->setMaxRetries(3);
$client->setRetryDelay(1000);
$this->assertSame(3, $client->getMaxRetries());
$this->assertSame(1000, $client->getRetryDelay());
$res = $client->fetch('127.0.0.1:8000/mock-retry');
$this->assertSame(200, $res->getStatusCode());
unlink(__DIR__ . '/state.json');
// Test if we get a 500 error if we go under the server's max retries
$client->setMaxRetries(1);
$res = $client->fetch('127.0.0.1:8000/mock-retry');
$this->assertSame(503, $res->getStatusCode());
unlink(__DIR__ . '/state.json');
}
/**
* Test if the retry delay is working
* @return void
*/
public function testRetryWithDelay(): void
{
$client = new Client();
$client->setMaxRetries(3);
$client->setRetryDelay(3000);
$now = microtime(true);
$res = $client->fetch('127.0.0.1:8000/mock-retry');
$this->assertGreaterThan($now + 3.0, microtime(true));
$this->assertSame(200, $res->getStatusCode());
unlink(__DIR__ . '/state.json');
}
/**
* Test custom retry status codes
* @return void
*/
public function testCustomRetryStatusCodes(): void
{
$client = new Client();
$client->setMaxRetries(3);
$client->setRetryDelay(3000);
$client->setRetryStatusCodes([401]);
$now = microtime(true);
$res = $client->fetch('127.0.0.1:8000/mock-retry-401');
$this->assertSame(200, $res->getStatusCode());
$this->assertGreaterThan($now + 3.0, microtime(true));
unlink(__DIR__ . '/state.json');
}
/**
* Test for chunk handling
* @return void
*/
public function testChunkHandling(): void
{
$client = new Client();
$chunks = [];
$lastChunk = null;
$response = $client->fetch(
url: '127.0.0.1:8000/chunked',
method: Client::METHOD_GET,
chunks: function (Chunk $chunk) use (&$chunks, &$lastChunk) {
$chunks[] = $chunk;
$lastChunk = $chunk;
}
);
$this->assertGreaterThan(0, count($chunks));
$this->assertSame(200, $response->getStatusCode());
// Test chunk metadata
foreach ($chunks as $index => $chunk) {
$this->assertSame($index, $chunk->getIndex());
$this->assertGreaterThan(0, $chunk->getSize());
$this->assertGreaterThan(0, $chunk->getTimestamp());
$this->assertNotEmpty($chunk->getData());
}
// Verify last chunk exists
$this->assertNotNull($lastChunk);
}
/**
* Test chunk handling with JSON response
* @return void
*/
public function testChunkHandlingWithJson(): void
{
$client = new Client();
$client->addHeader('content-type', 'application/json');
$chunks = [];
$response = $client->fetch(
url: '127.0.0.1:8000/chunked-json',
method: Client::METHOD_POST,
body: ['test' => 'data'],
chunks: function (Chunk $chunk) use (&$chunks) {
$chunks[] = $chunk;
}
);
$this->assertGreaterThan(0, count($chunks));
// Test JSON handling
foreach ($chunks as $chunk) {
$data = $chunk->getData();
$this->assertNotEmpty($data);
// Verify each chunk is valid JSON
$decoded = json_decode($data, true);
$this->assertNotNull($decoded);
$this->assertIsArray($decoded);
$this->assertArrayHasKey('chunk', $decoded);
$this->assertArrayHasKey('data', $decoded);
}
}
/**
* Test chunk handling with error response
* @return void
*/
public function testChunkHandlingWithError(): void
{
$client = new Client();
$errorChunk = null;
$response = $client->fetch(
url: '127.0.0.1:8000/error',
method: Client::METHOD_GET,
chunks: function (Chunk $chunk) use (&$errorChunk) {
if ($errorChunk === null) {
$errorChunk = $chunk;
}
}
);
$this->assertNotNull($errorChunk);
if ($errorChunk !== null) {
$this->assertNotEmpty($errorChunk->getData());
}
$this->assertSame(404, $response->getStatusCode());
}
/**
* Test chunk handling with chunked error response
* @return void
*/
public function testChunkHandlingWithChunkedError(): void
{
$client = new Client();
$client->addHeader('content-type', 'application/json');
$chunks = [];
$errorMessages = [];
$response = $client->fetch(
url: '127.0.0.1:8000/chunked-error',
method: Client::METHOD_GET,
chunks: function (Chunk $chunk) use (&$chunks, &$errorMessages) {
$chunks[] = $chunk;
$data = json_decode($chunk->getData(), true);
if (is_array($data) && isset($data['error'])) {
$errorMessages[] = $data['error'];
}
}
);
// Verify response status code
$this->assertSame(400, $response->getStatusCode());
// Verify we received chunks
$this->assertCount(3, $chunks);
// Verify error messages were received in order
$this->assertSame([
'Validation error',
'Additional details',
'Final error message'
], $errorMessages);
// Test the content of specific chunks
$this->assertArrayHasKey(0, $chunks);
$firstChunk = json_decode($chunks[0]->getData(), true);
$this->assertIsArray($firstChunk);
$this->assertSame('username', $firstChunk['field']);
}
/**
* Test that query parameters are appended correctly when URL has trailing '?'
* @return void
*/
public function testQueryWithTrailingQuestionMark(): void
{
$client = new Client();
$response = $client->fetch(
url: '127.0.0.1:8000?',
method: Client::METHOD_GET,
query: ['foo' => 'bar']
);
$this->assertSame(200, $response->getStatusCode());
$data = $response->json();
$this->assertIsArray($data);
$this->assertSame(['foo' => 'bar'], $data['query']);
}
/**
* Test that query parameters are appended correctly when URL has trailing '&'
* @return void
*/
public function testQueryWithTrailingAmpersand(): void
{
$client = new Client();
$response = $client->fetch(
url: '127.0.0.1:8000?existing=value&',
method: Client::METHOD_GET,
query: ['foo' => 'bar']
);
$this->assertSame(200, $response->getStatusCode());
$data = $response->json();
$this->assertIsArray($data);
$this->assertSame('value', $data['query']['existing']);
$this->assertSame('bar', $data['query']['foo']);
}
/**
* Test that query parameters are appended correctly with existing query string
* @return void
*/
public function testQueryWithExistingParams(): void
{
$client = new Client();
$response = $client->fetch(
url: '127.0.0.1:8000?existing=value',
method: Client::METHOD_GET,
query: ['foo' => 'bar']
);
$this->assertSame(200, $response->getStatusCode());
$data = $response->json();
$this->assertIsArray($data);
$this->assertSame('value', $data['query']['existing']);
$this->assertSame('bar', $data['query']['foo']);
}
}