Debian Codegraph @

lib/3rdParty/composer/symfony/http-client-contracts/Test/HttpClientTestCase.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Contracts\HttpClient\Test;
13
14 use PHPUnit\Framework\Attributes\RequiresPhpExtension;
15 use PHPUnit\Framework\Attributes\TestWith;
16 use PHPUnit\Framework\TestCase;
17 use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
18 use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
19 use Symfony\Contracts\HttpClient\Exception\TimeoutExceptionInterface;
20 use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
21 use Symfony\Contracts\HttpClient\HttpClientInterface;
22
23 /**
24 * A reference test suite for HttpClientInterface implementations.
25 */
26 abstract class HttpClientTestCase extends TestCase
27 {
28 public static function setUpBeforeClass(): void
29 {
30 if (!\function_exists('ob_gzhandler')) {
31 static::markTestSkipped('The "ob_gzhandler" function is not available.');
32 }
33
34 TestHttpServer::start();
35 }
36
37 public static function tearDownAfterClass(): void
38 {
39 TestHttpServer::stop(8067);
40 TestHttpServer::stop(8077);
41 }
42
43 abstract protected function getHttpClient(string $testCase): HttpClientInterface;
44
45 public function testGetRequest()
46 {
47 $client = $this->getHttpClient(__FUNCTION__);
48 $response = $client->request('GET', 'http://localhost:8057', [
49 'headers' => ['Foo' => 'baR'],
50 'user_data' => $data = new \stdClass(),
51 ]);
52
53 $this->assertSame([], $response->getInfo('response_headers'));
54 $this->assertSame($data, $response->getInfo()['user_data']);
55 $this->assertSame(200, $response->getStatusCode());
56
57 $info = $response->getInfo();
58 $this->assertNull($info['error']);
59 $this->assertSame(0, $info['redirect_count']);
60 $this->assertSame('HTTP/1.1 200 OK', $info['response_headers'][0]);
61 $this->assertSame('Host: localhost:8057', $info['response_headers'][1]);
62 $this->assertSame('http://localhost:8057/', $info['url']);
63
64 $headers = $response->getHeaders();
65
66 $this->assertSame('localhost:8057', $headers['host'][0]);
67 $this->assertSame(['application/json'], $headers['content-type']);
68
69 $body = json_decode($response->getContent(), true);
70 $this->assertSame($body, $response->toArray());
71
72 $this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
73 $this->assertSame('/', $body['REQUEST_URI']);
74 $this->assertSame('GET', $body['REQUEST_METHOD']);
75 $this->assertSame('localhost:8057', $body['HTTP_HOST']);
76 $this->assertSame('baR', $body['HTTP_FOO']);
77
78 $response = $client->request('GET', 'http://localhost:8057/length-broken');
79
80 $this->expectException(TransportExceptionInterface::class);
81 $response->getContent();
82 }
83
84 public function testHeadRequest()
85 {
86 $client = $this->getHttpClient(__FUNCTION__);
87 $response = $client->request('HEAD', 'http://localhost:8057/head', [
88 'headers' => ['Foo' => 'baR'],
89 'user_data' => $data = new \stdClass(),
90 'buffer' => false,
91 ]);
92
93 $this->assertSame([], $response->getInfo('response_headers'));
94 $this->assertSame(200, $response->getStatusCode());
95
96 $info = $response->getInfo();
97 $this->assertSame('HTTP/1.1 200 OK', $info['response_headers'][0]);
98 $this->assertSame('Host: localhost:8057', $info['response_headers'][1]);
99
100 $headers = $response->getHeaders();
101
102 $this->assertSame('localhost:8057', $headers['host'][0]);
103 $this->assertSame(['application/json'], $headers['content-type']);
104 $this->assertTrue(0 < $headers['content-length'][0]);
105
106 $this->assertSame('', $response->getContent());
107 }
108
109 public function testNonBufferedGetRequest()
110 {
111 $client = $this->getHttpClient(__FUNCTION__);
112 $response = $client->request('GET', 'http://localhost:8057', [
113 'buffer' => false,
114 'headers' => ['Foo' => 'baR'],
115 ]);
116
117 $body = $response->toArray();
118 $this->assertSame('baR', $body['HTTP_FOO']);
119
120 $this->expectException(TransportExceptionInterface::class);
121 $response->getContent();
122 }
123
124 public function testBufferSink()
125 {
126 $sink = fopen('php://temp', 'w+');
127 $client = $this->getHttpClient(__FUNCTION__);
128 $response = $client->request('GET', 'http://localhost:8057', [
129 'buffer' => $sink,
130 'headers' => ['Foo' => 'baR'],
131 ]);
132
133 $body = $response->toArray();
134 $this->assertSame('baR', $body['HTTP_FOO']);
135
136 rewind($sink);
137 $sink = stream_get_contents($sink);
138 $this->assertSame($sink, $response->getContent());
139 }
140
141 public function testConditionalBuffering()
142 {
143 $client = $this->getHttpClient(__FUNCTION__);
144 $response = $client->request('GET', 'http://localhost:8057');
145 $firstContent = $response->getContent();
146 $secondContent = $response->getContent();
147
148 $this->assertSame($firstContent, $secondContent);
149
150 $response = $client->request('GET', 'http://localhost:8057', ['buffer' => static fn () => false]);
151 $response->getContent();
152
153 $this->expectException(TransportExceptionInterface::class);
154 $response->getContent();
155 }
156
157 public function testReentrantBufferCallback()
158 {
159 $client = $this->getHttpClient(__FUNCTION__);
160
161 $response = $client->request('GET', 'http://localhost:8057', ['buffer' => static function () use (&$response) {
162 $response->cancel();
163
164 return true;
165 }]);
166
167 $this->assertSame(200, $response->getStatusCode());
168
169 $this->expectException(TransportExceptionInterface::class);
170 $response->getContent();
171 }
172
173 public function testThrowingBufferCallback()
174 {
175 $client = $this->getHttpClient(__FUNCTION__);
176
177 $response = $client->request('GET', 'http://localhost:8057', ['buffer' => static function () {
178 throw new \Exception('Boo.');
179 }]);
180
181 $this->assertSame(200, $response->getStatusCode());
182
183 $this->expectException(TransportExceptionInterface::class);
184 $this->expectExceptionMessage('Boo');
185 $response->getContent();
186 }
187
188 public function testUnsupportedOption()
189 {
190 $client = $this->getHttpClient(__FUNCTION__);
191
192 $this->expectException(\InvalidArgumentException::class);
193 $client->request('GET', 'http://localhost:8057', [
194 'capture_peer_cert' => 1.0,
195 ]);
196 }
197
198 public function testHttpVersion()
199 {
200 $client = $this->getHttpClient(__FUNCTION__);
201 $response = $client->request('GET', 'http://localhost:8057', [
202 'http_version' => 1.0,
203 ]);
204
205 $this->assertSame(200, $response->getStatusCode());
206 $this->assertSame('HTTP/1.0 200 OK', $response->getInfo('response_headers')[0]);
207
208 $body = $response->toArray();
209
210 $this->assertSame('HTTP/1.0', $body['SERVER_PROTOCOL']);
211 $this->assertSame('GET', $body['REQUEST_METHOD']);
212 $this->assertSame('/', $body['REQUEST_URI']);
213 }
214
215 public function testChunkedEncoding()
216 {
217 $client = $this->getHttpClient(__FUNCTION__);
218 $response = $client->request('GET', 'http://localhost:8057/chunked');
219
220 $this->assertSame(['chunked'], $response->getHeaders()['transfer-encoding']);
221 $this->assertSame('Symfony is awesome!', $response->getContent());
222
223 $response = $client->request('GET', 'http://localhost:8057/chunked-broken');
224
225 $this->expectException(TransportExceptionInterface::class);
226 $response->getContent();
227 }
228
229 public function testClientError()
230 {
231 $client = $this->getHttpClient(__FUNCTION__);
232 $response = $client->request('GET', 'http://localhost:8057/404');
233
234 $client->stream($response)->valid();
235
236 $this->assertSame(404, $response->getInfo('http_code'));
237
238 try {
239 $response->getHeaders();
240 $this->fail(ClientExceptionInterface::class.' expected');
241 } catch (ClientExceptionInterface) {
242 }
243
244 try {
245 $response->getContent();
246 $this->fail(ClientExceptionInterface::class.' expected');
247 } catch (ClientExceptionInterface) {
248 }
249
250 $this->assertSame(404, $response->getStatusCode());
251 $this->assertSame(['application/json'], $response->getHeaders(false)['content-type']);
252 $this->assertNotEmpty($response->getContent(false));
253
254 $response = $client->request('GET', 'http://localhost:8057/404');
255
256 try {
257 foreach ($client->stream($response) as $chunk) {
258 $this->assertTrue($chunk->isFirst());
259 }
260 $this->fail(ClientExceptionInterface::class.' expected');
261 } catch (ClientExceptionInterface) {
262 }
263 }
264
265 public function testIgnoreErrors()
266 {
267 $client = $this->getHttpClient(__FUNCTION__);
268 $response = $client->request('GET', 'http://localhost:8057/404');
269
270 $this->assertSame(404, $response->getStatusCode());
271 }
272
273 public function testDnsError()
274 {
275 $client = $this->getHttpClient(__FUNCTION__);
276 $response = $client->request('GET', 'http://localhost:8057/301/bad-tld');
277
278 try {
279 $response->getStatusCode();
280 $this->fail(TransportExceptionInterface::class.' expected');
281 } catch (TransportExceptionInterface) {
282 $this->addToAssertionCount(1);
283 }
284
285 try {
286 $response->getStatusCode();
287 $this->fail(TransportExceptionInterface::class.' still expected');
288 } catch (TransportExceptionInterface) {
289 $this->addToAssertionCount(1);
290 }
291
292 $response = $client->request('GET', 'http://localhost:8057/301/bad-tld');
293
294 try {
295 foreach ($client->stream($response) as $r => $chunk) {
296 }
297 $this->fail(TransportExceptionInterface::class.' expected');
298 } catch (TransportExceptionInterface) {
299 $this->addToAssertionCount(1);
300 }
301
302 $this->assertSame($response, $r);
303 $this->assertNotNull($chunk->getError());
304
305 $this->expectException(TransportExceptionInterface::class);
306 foreach ($client->stream($response) as $chunk) {
307 }
308 }
309
310 public function testInlineAuth()
311 {
312 $client = $this->getHttpClient(__FUNCTION__);
313 $response = $client->request('GET', 'http://foo:bar%3Dbar@localhost:8057');
314
315 $body = $response->toArray();
316
317 $this->assertSame('foo', $body['PHP_AUTH_USER']);
318 $this->assertSame('bar=bar', $body['PHP_AUTH_PW']);
319 }
320
321 public function testBadRequestBody()
322 {
323 $client = $this->getHttpClient(__FUNCTION__);
324
325 $this->expectException(TransportExceptionInterface::class);
326
327 $response = $client->request('POST', 'http://localhost:8057/', [
328 'body' => static function () { yield []; },
329 ]);
330
331 $response->getStatusCode();
332 }
333
334 public function test304()
335 {
336 $client = $this->getHttpClient(__FUNCTION__);
337 $response = $client->request('GET', 'http://localhost:8057/304', [
338 'headers' => ['If-Match' => '"abc"'],
339 'buffer' => false,
340 ]);
341
342 $this->assertSame(304, $response->getStatusCode());
343 $this->assertSame('', $response->getContent(false));
344 }
345
346 /**
347 * @testWith [[]]
348 * [["Content-Length: 7"]]
349 */
350 #[TestWith([[]])]
351 #[TestWith([['Content-Length: 7']])]
352 public function testRedirects(array $headers = [])
353 {
354 $client = $this->getHttpClient(__FUNCTION__);
355 $response = $client->request('POST', 'http://localhost:8057/301', [
356 'auth_basic' => 'foo:bar',
357 'headers' => $headers,
358 'body' => static function () {
359 yield 'foo=bar';
360 },
361 ]);
362
363 $body = $response->toArray();
364 $this->assertSame('GET', $body['REQUEST_METHOD']);
365 $this->assertSame('Basic Zm9vOmJhcg==', $body['HTTP_AUTHORIZATION']);
366 $this->assertSame('http://localhost:8057/', $response->getInfo('url'));
367
368 $this->assertSame(2, $response->getInfo('redirect_count'));
369 $this->assertNull($response->getInfo('redirect_url'));
370
371 $expected = [
372 'HTTP/1.1 301 Moved Permanently',
373 'Location: http://127.0.0.1:8057/302',
374 'Content-Type: application/json',
375 'HTTP/1.1 302 Found',
376 'Location: http://localhost:8057/',
377 'Content-Type: application/json',
378 'HTTP/1.1 200 OK',
379 'Content-Type: application/json',
380 ];
381
382 $filteredHeaders = array_values(array_filter($response->getInfo('response_headers'), static fn ($h) => \in_array(substr($h, 0, 4), ['HTTP', 'Loca', 'Cont'], true) && 'Content-Encoding: gzip' !== $h));
383
384 $this->assertSame($expected, $filteredHeaders);
385 }
386
387 public function testInvalidRedirect()
388 {
389 $client = $this->getHttpClient(__FUNCTION__);
390 $response = $client->request('GET', 'http://localhost:8057/301/invalid');
391
392 $this->assertSame(301, $response->getStatusCode());
393 $this->assertSame(['//?foo=bar'], $response->getHeaders(false)['location']);
394 $this->assertSame(0, $response->getInfo('redirect_count'));
395 $this->assertNull($response->getInfo('redirect_url'));
396
397 $this->expectException(RedirectionExceptionInterface::class);
398 $response->getHeaders();
399 }
400
401 public function testRelativeRedirects()
402 {
403 $client = $this->getHttpClient(__FUNCTION__);
404 $response = $client->request('GET', 'http://localhost:8057/302/relative');
405
406 $body = $response->toArray();
407
408 $this->assertSame('/', $body['REQUEST_URI']);
409 $this->assertNull($response->getInfo('redirect_url'));
410
411 $response = $client->request('GET', 'http://localhost:8057/302/relative', [
412 'max_redirects' => 0,
413 ]);
414
415 $this->assertSame(302, $response->getStatusCode());
416 $this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url'));
417 }
418
419 public function testRedirect307()
420 {
421 $client = $this->getHttpClient(__FUNCTION__);
422
423 $response = $client->request('POST', 'http://localhost:8057/307', [
424 'body' => static function () {
425 yield 'foo=bar';
426 },
427 'max_redirects' => 0,
428 ]);
429
430 $this->assertSame(307, $response->getStatusCode());
431
432 $response = $client->request('POST', 'http://localhost:8057/307', [
433 'body' => 'foo=bar',
434 ]);
435
436 $body = $response->toArray();
437
438 $this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $body);
439 }
440
441 public function testMaxRedirects()
442 {
443 $client = $this->getHttpClient(__FUNCTION__);
444 $response = $client->request('GET', 'http://localhost:8057/301', [
445 'max_redirects' => 1,
446 'auth_basic' => 'foo:bar',
447 ]);
448
449 try {
450 $response->getHeaders();
451 $this->fail(RedirectionExceptionInterface::class.' expected');
452 } catch (RedirectionExceptionInterface) {
453 }
454
455 $this->assertSame(302, $response->getStatusCode());
456 $this->assertSame(1, $response->getInfo('redirect_count'));
457 $this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url'));
458
459 $expected = [
460 'HTTP/1.1 301 Moved Permanently',
461 'Location: http://127.0.0.1:8057/302',
462 'Content-Type: application/json',
463 'HTTP/1.1 302 Found',
464 'Location: http://localhost:8057/',
465 'Content-Type: application/json',
466 ];
467
468 $filteredHeaders = array_values(array_filter($response->getInfo('response_headers'), static fn ($h) => \in_array(substr($h, 0, 4), ['HTTP', 'Loca', 'Cont'], true)));
469
470 $this->assertSame($expected, $filteredHeaders);
471 }
472
473 public function testStream()
474 {
475 $client = $this->getHttpClient(__FUNCTION__);
476
477 $response = $client->request('GET', 'http://localhost:8057');
478 $chunks = $client->stream($response);
479 $result = [];
480
481 foreach ($chunks as $r => $chunk) {
482 if ($chunk->isTimeout()) {
483 $result[] = 't';
484 } elseif ($chunk->isLast()) {
485 $result[] = 'l';
486 } elseif ($chunk->isFirst()) {
487 $result[] = 'f';
488 }
489 }
490
491 $this->assertSame($response, $r);
492 $this->assertSame(['f', 'l'], $result);
493
494 $chunk = null;
495 $i = 0;
496
497 foreach ($client->stream($response) as $chunk) {
498 ++$i;
499 }
500
501 $this->assertSame(1, $i);
502 $this->assertTrue($chunk->isLast());
503 }
504
505 public function testAddToStream()
506 {
507 $client = $this->getHttpClient(__FUNCTION__);
508
509 $r1 = $client->request('GET', 'http://localhost:8057');
510
511 $completed = [];
512
513 $pool = [$r1];
514
515 while ($pool) {
516 $chunks = $client->stream($pool);
517 $pool = [];
518
519 foreach ($chunks as $r => $chunk) {
520 if (!$chunk->isLast()) {
521 continue;
522 }
523
524 if ($r1 === $r) {
525 $r2 = $client->request('GET', 'http://localhost:8057');
526 $pool[] = $r2;
527 }
528
529 $completed[] = $r;
530 }
531 }
532
533 $this->assertSame([$r1, $r2], $completed);
534 }
535
536 public function testCompleteTypeError()
537 {
538 $client = $this->getHttpClient(__FUNCTION__);
539
540 $this->expectException(\TypeError::class);
541 $client->stream(123);
542 }
543
544 public function testOnProgress()
545 {
546 $client = $this->getHttpClient(__FUNCTION__);
547 $response = $client->request('POST', 'http://localhost:8057/post', [
548 'headers' => ['Content-Length' => 14],
549 'body' => 'foo=0123456789',
550 'on_progress' => static function (...$state) use (&$steps) { $steps[] = $state; },
551 ]);
552
553 $body = $response->toArray();
554
555 $this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $body);
556 $this->assertSame([0, 0], \array_slice($steps[0], 0, 2));
557 $lastStep = \array_slice($steps, -1)[0];
558 $this->assertSame([57, 57], \array_slice($lastStep, 0, 2));
559 $this->assertSame('http://localhost:8057/post', $steps[0][2]['url']);
560 }
561
562 public function testPostJson()
563 {
564 $client = $this->getHttpClient(__FUNCTION__);
565
566 $response = $client->request('POST', 'http://localhost:8057/post', [
567 'json' => ['foo' => 'bar'],
568 ]);
569
570 $body = $response->toArray();
571
572 $this->assertStringContainsString('json', $body['content-type']);
573 unset($body['content-type']);
574 $this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $body);
575 }
576
577 public function testPostArray()
578 {
579 $client = $this->getHttpClient(__FUNCTION__);
580
581 $response = $client->request('POST', 'http://localhost:8057/post', [
582 'body' => ['foo' => 'bar'],
583 ]);
584
585 $this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $response->toArray());
586 }
587
588 public function testPostResource()
589 {
590 $client = $this->getHttpClient(__FUNCTION__);
591
592 $h = fopen('php://temp', 'w+');
593 fwrite($h, 'foo=0123456789');
594 rewind($h);
595
596 $response = $client->request('POST', 'http://localhost:8057/post', [
597 'body' => $h,
598 ]);
599
600 $body = $response->toArray();
601
602 $this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $body);
603 }
604
605 public function testPostCallback()
606 {
607 $client = $this->getHttpClient(__FUNCTION__);
608
609 $response = $client->request('POST', 'http://localhost:8057/post', [
610 'body' => static function () {
611 yield 'foo';
612 yield '';
613 yield '=';
614 yield '0123456789';
615 },
616 ]);
617
618 $this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray());
619 }
620
621 public function testCancel()
622 {
623 $client = $this->getHttpClient(__FUNCTION__);
624 $response = $client->request('GET', 'http://localhost:8057/timeout-header');
625
626 $response->cancel();
627 $this->expectException(TransportExceptionInterface::class);
628 $response->getHeaders();
629 }
630
631 public function testInfoOnCanceledResponse()
632 {
633 $client = $this->getHttpClient(__FUNCTION__);
634
635 $response = $client->request('GET', 'http://localhost:8057/timeout-header');
636
637 $this->assertFalse($response->getInfo('canceled'));
638 $response->cancel();
639 $this->assertTrue($response->getInfo('canceled'));
640 }
641
642 public function testCancelInStream()
643 {
644 $client = $this->getHttpClient(__FUNCTION__);
645 $response = $client->request('GET', 'http://localhost:8057/404');
646
647 foreach ($client->stream($response) as $chunk) {
648 $response->cancel();
649 }
650
651 $this->expectException(TransportExceptionInterface::class);
652
653 foreach ($client->stream($response) as $chunk) {
654 }
655 }
656
657 public function testOnProgressCancel()
658 {
659 $client = $this->getHttpClient(__FUNCTION__);
660 $response = $client->request('GET', 'http://localhost:8057/timeout-body', [
661 'on_progress' => static function ($dlNow) {
662 if (0 < $dlNow) {
663 throw new \Exception('Aborting the request.');
664 }
665 },
666 ]);
667
668 try {
669 foreach ($client->stream([$response]) as $chunk) {
670 }
671 $this->fail(ClientExceptionInterface::class.' expected');
672 } catch (TransportExceptionInterface $e) {
673 $this->assertSame('Aborting the request.', $e->getPrevious()->getMessage());
674 }
675
676 $this->assertNotNull($response->getInfo('error'));
677 $this->expectException(TransportExceptionInterface::class);
678 $response->getContent();
679 }
680
681 public function testOnProgressError()
682 {
683 $client = $this->getHttpClient(__FUNCTION__);
684 $response = $client->request('GET', 'http://localhost:8057/timeout-body', [
685 'on_progress' => static function ($dlNow) {
686 if (0 < $dlNow) {
687 throw new \Error('BUG.');
688 }
689 },
690 ]);
691
692 try {
693 foreach ($client->stream([$response]) as $chunk) {
694 }
695 $this->fail('Error expected');
696 } catch (\Error $e) {
697 $this->assertSame('BUG.', $e->getMessage());
698 }
699
700 $this->assertNotNull($response->getInfo('error'));
701 $this->expectException(TransportExceptionInterface::class);
702 $response->getContent();
703 }
704
705 public function testResolve()
706 {
707 $client = $this->getHttpClient(__FUNCTION__);
708 $response = $client->request('GET', 'http://symfony.com:8057/', [
709 'resolve' => ['symfony.com' => '127.0.0.1'],
710 ]);
711
712 $this->assertSame(200, $response->getStatusCode());
713 $this->assertSame(200, $client->request('GET', 'http://symfony.com:8057/')->getStatusCode());
714
715 $response = null;
716 $this->expectException(TransportExceptionInterface::class);
717 $client->request('GET', 'http://symfony.com:8057/', ['timeout' => 1]);
718 }
719
720 public function testIdnResolve()
721 {
722 $client = $this->getHttpClient(__FUNCTION__);
723
724 $response = $client->request('GET', 'http://0-------------------------------------------------------------0.com:8057/', [
725 'resolve' => ['0-------------------------------------------------------------0.com' => '127.0.0.1'],
726 ]);
727
728 $this->assertSame(200, $response->getStatusCode());
729
730 $response = $client->request('GET', 'http://Bücher.example:8057/', [
731 'resolve' => ['xn--bcher-kva.example' => '127.0.0.1'],
732 ]);
733
734 $this->assertSame(200, $response->getStatusCode());
735 }
736
737 public function testIPv6Resolve()
738 {
739 TestHttpServer::start(-8087);
740
741 $client = $this->getHttpClient(__FUNCTION__);
742 $response = $client->request('GET', 'http://symfony.com:8087/', [
743 'resolve' => ['symfony.com' => '::1'],
744 ]);
745
746 $this->assertSame(200, $response->getStatusCode());
747 }
748
749 public function testNotATimeout()
750 {
751 $client = $this->getHttpClient(__FUNCTION__);
752 $response = $client->request('GET', 'http://localhost:8057/timeout-header', [
753 'timeout' => 0.9,
754 ]);
755 sleep(1);
756 $this->assertSame(200, $response->getStatusCode());
757 }
758
759 public function testTimeoutOnAccess()
760 {
761 $client = $this->getHttpClient(__FUNCTION__);
762 $response = $client->request('GET', 'http://localhost:8057/timeout-header', [
763 'timeout' => 0.1,
764 ]);
765
766 $this->expectException(TransportExceptionInterface::class);
767 $response->getHeaders();
768 }
769
770 public function testTimeoutIsNotAFatalError()
771 {
772 usleep(300000); // wait for the previous test to release the server
773 $client = $this->getHttpClient(__FUNCTION__);
774 $response = $client->request('GET', 'http://localhost:8057/timeout-body', [
775 'timeout' => 0.25,
776 ]);
777
778 try {
779 $response->getContent();
780 $this->fail(TimeoutExceptionInterface::class.' expected');
781 } catch (TimeoutExceptionInterface $e) {
782 }
783
784 for ($i = 0; $i < 10; ++$i) {
785 try {
786 $this->assertSame('<1><2>', $response->getContent());
787 break;
788 } catch (TimeoutExceptionInterface $e) {
789 }
790 }
791
792 if (10 === $i) {
793 throw $e;
794 }
795 }
796
797 public function testTimeoutOnStream()
798 {
799 $client = $this->getHttpClient(__FUNCTION__);
800 $response = $client->request('GET', 'http://localhost:8057/timeout-body');
801
802 $this->assertSame(200, $response->getStatusCode());
803 $chunks = $client->stream([$response], 0.2);
804
805 $result = [];
806
807 foreach ($chunks as $r => $chunk) {
808 if ($chunk->isTimeout()) {
809 $result[] = 't';
810 } else {
811 $result[] = $chunk->getContent();
812 }
813 }
814
815 $this->assertSame(['<1>', 't'], $result);
816
817 $chunks = $client->stream([$response]);
818
819 foreach ($chunks as $r => $chunk) {
820 $this->assertSame('<2>', $chunk->getContent());
821 $this->assertSame('<1><2>', $r->getContent());
822
823 return;
824 }
825
826 $this->fail('The response should have completed');
827 }
828
829 public function testUncheckedTimeoutThrows()
830 {
831 $client = $this->getHttpClient(__FUNCTION__);
832 $response = $client->request('GET', 'http://localhost:8057/timeout-body');
833 $chunks = $client->stream([$response], 0.1);
834
835 $this->expectException(TransportExceptionInterface::class);
836
837 foreach ($chunks as $r => $chunk) {
838 }
839 }
840
841 public function testTimeoutWithActiveConcurrentStream()
842 {
843 $p1 = TestHttpServer::start(8067);
844 $p2 = TestHttpServer::start(8077);
845
846 $client = $this->getHttpClient(__FUNCTION__);
847 $streamingResponse = $client->request('GET', 'http://localhost:8067/max-duration');
848 $blockingResponse = $client->request('GET', 'http://localhost:8077/timeout-body', [
849 'timeout' => 0.25,
850 ]);
851
852 $this->assertSame(200, $streamingResponse->getStatusCode());
853 $this->assertSame(200, $blockingResponse->getStatusCode());
854
855 $this->expectException(TransportExceptionInterface::class);
856
857 try {
858 $blockingResponse->getContent();
859 } finally {
860 $p1->stop();
861 $p2->stop();
862 }
863 }
864
865 public function testTimeoutOnInitialize()
866 {
867 $p1 = TestHttpServer::start(8067);
868 $p2 = TestHttpServer::start(8077);
869
870 $client = $this->getHttpClient(__FUNCTION__);
871 $start = microtime(true);
872 $responses = [];
873
874 $responses[] = $client->request('GET', 'http://localhost:8067/timeout-header', ['timeout' => 0.25]);
875 $responses[] = $client->request('GET', 'http://localhost:8077/timeout-header', ['timeout' => 0.25]);
876 $responses[] = $client->request('GET', 'http://localhost:8067/timeout-header', ['timeout' => 0.25]);
877 $responses[] = $client->request('GET', 'http://localhost:8077/timeout-header', ['timeout' => 0.25]);
878
879 try {
880 foreach ($responses as $response) {
881 try {
882 $response->getContent();
883 $this->fail(TransportExceptionInterface::class.' expected');
884 } catch (TransportExceptionInterface) {
885 }
886 }
887 $responses = [];
888
889 $duration = microtime(true) - $start;
890
891 $this->assertLessThan(1.0, $duration);
892 } finally {
893 $p1->stop();
894 $p2->stop();
895 }
896 }
897
898 public function testTimeoutOnDestruct()
899 {
900 $p1 = TestHttpServer::start(8067);
901 $p2 = TestHttpServer::start(8077);
902
903 $client = $this->getHttpClient(__FUNCTION__);
904 $start = microtime(true);
905 $responses = [];
906
907 $responses[] = $client->request('GET', 'http://localhost:8067/timeout-header', ['timeout' => 0.25]);
908 $responses[] = $client->request('GET', 'http://localhost:8077/timeout-header', ['timeout' => 0.25]);
909 $responses[] = $client->request('GET', 'http://localhost:8067/timeout-header', ['timeout' => 0.25]);
910 $responses[] = $client->request('GET', 'http://localhost:8077/timeout-header', ['timeout' => 0.25]);
911
912 try {
913 while ($response = array_shift($responses)) {
914 try {
915 unset($response);
916 $this->fail(TransportExceptionInterface::class.' expected');
917 } catch (TransportExceptionInterface) {
918 }
919 }
920
921 $duration = microtime(true) - $start;
922
923 $this->assertLessThan(1.0, $duration);
924 } finally {
925 $p1->stop();
926 $p2->stop();
927 }
928 }
929
930 public function testDestruct()
931 {
932 $client = $this->getHttpClient(__FUNCTION__);
933
934 $start = microtime(true);
935 $client->request('GET', 'http://localhost:8057/timeout-long');
936 $client = null;
937 $duration = microtime(true) - $start;
938
939 $this->assertGreaterThan(1, $duration);
940 $this->assertLessThan(4, $duration);
941 }
942
943 public function testGetContentAfterDestruct()
944 {
945 $client = $this->getHttpClient(__FUNCTION__);
946
947 try {
948 $client->request('GET', 'http://localhost:8057/404');
949 $this->fail(ClientExceptionInterface::class.' expected');
950 } catch (ClientExceptionInterface $e) {
951 $this->assertSame('GET', $e->getResponse()->toArray(false)['REQUEST_METHOD']);
952 }
953 }
954
955 public function testGetEncodedContentAfterDestruct()
956 {
957 $client = $this->getHttpClient(__FUNCTION__);
958
959 try {
960 $client->request('GET', 'http://localhost:8057/404-gzipped');
961 $this->fail(ClientExceptionInterface::class.' expected');
962 } catch (ClientExceptionInterface $e) {
963 $this->assertSame('some text', $e->getResponse()->getContent(false));
964 }
965 }
966
967 public function testProxy()
968 {
969 $client = $this->getHttpClient(__FUNCTION__);
970 $response = $client->request('GET', 'http://localhost:8057/', [
971 'proxy' => 'http://localhost:8057',
972 ]);
973
974 $body = $response->toArray();
975 $this->assertSame('localhost:8057', $body['HTTP_HOST']);
976 $this->assertMatchesRegularExpression('#^http://(localhost|127\.0\.0\.1):8057/$#', $body['REQUEST_URI']);
977
978 $response = $client->request('GET', 'http://localhost:8057/', [
979 'proxy' => 'http://foo:b%3Dar@localhost:8057',
980 ]);
981
982 $body = $response->toArray();
983 $this->assertSame('Basic Zm9vOmI9YXI=', $body['HTTP_PROXY_AUTHORIZATION']);
984
985 $_SERVER['http_proxy'] = 'http://localhost:8057';
986 try {
987 $response = $client->request('GET', 'http://localhost:8057/');
988 $body = $response->toArray();
989 $this->assertSame('localhost:8057', $body['HTTP_HOST']);
990 $this->assertMatchesRegularExpression('#^http://(localhost|127\.0\.0\.1):8057/$#', $body['REQUEST_URI']);
991 } finally {
992 unset($_SERVER['http_proxy']);
993 }
994
995 $response = $client->request('GET', 'http://localhost:8057/301/proxy', [
996 'proxy' => 'http://localhost:8057',
997 ]);
998
999 $body = $response->toArray();
1000 $this->assertSame('localhost:8057', $body['HTTP_HOST']);
1001 $this->assertMatchesRegularExpression('#^http://(localhost|127\.0\.0\.1):8057/$#', $body['REQUEST_URI']);
1002 }
1003
1004 public function testNoProxy()
1005 {
1006 putenv('no_proxy='.$_SERVER['no_proxy'] = 'example.com, localhost');
1007
1008 try {
1009 $client = $this->getHttpClient(__FUNCTION__);
1010 $response = $client->request('GET', 'http://localhost:8057/', [
1011 'proxy' => 'http://localhost:8057',
1012 ]);
1013
1014 $body = $response->toArray();
1015
1016 $this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
1017 $this->assertSame('/', $body['REQUEST_URI']);
1018 $this->assertSame('GET', $body['REQUEST_METHOD']);
1019 } finally {
1020 putenv('no_proxy');
1021 unset($_SERVER['no_proxy']);
1022 }
1023 }
1024
1025 /**
1026 * @requires extension zlib
1027 */
1028 #[RequiresPhpExtension('zlib')]
1029 public function testAutoEncodingRequest()
1030 {
1031 $client = $this->getHttpClient(__FUNCTION__);
1032 $response = $client->request('GET', 'http://localhost:8057');
1033
1034 $this->assertSame(200, $response->getStatusCode());
1035
1036 $headers = $response->getHeaders();
1037
1038 $this->assertSame(['Accept-Encoding'], $headers['vary']);
1039 $this->assertStringContainsString('gzip', $headers['content-encoding'][0]);
1040
1041 $body = $response->toArray();
1042
1043 $this->assertStringContainsString('gzip', $body['HTTP_ACCEPT_ENCODING']);
1044 }
1045
1046 public function testBaseUri()
1047 {
1048 $client = $this->getHttpClient(__FUNCTION__);
1049 $response = $client->request('GET', '../404', [
1050 'base_uri' => 'http://localhost:8057/abc/',
1051 ]);
1052
1053 $this->assertSame(404, $response->getStatusCode());
1054 $this->assertSame(['application/json'], $response->getHeaders(false)['content-type']);
1055 }
1056
1057 public function testQuery()
1058 {
1059 $client = $this->getHttpClient(__FUNCTION__);
1060 $response = $client->request('GET', 'http://localhost:8057/?a=a', [
1061 'query' => ['b' => 'b'],
1062 ]);
1063
1064 $body = $response->toArray();
1065 $this->assertSame('GET', $body['REQUEST_METHOD']);
1066 $this->assertSame('/?a=a&b=b', $body['REQUEST_URI']);
1067 }
1068
1069 public function testInformationalResponse()
1070 {
1071 $client = $this->getHttpClient(__FUNCTION__);
1072 $response = $client->request('GET', 'http://localhost:8057/103');
1073
1074 $this->assertSame('Here the body', $response->getContent());
1075 $this->assertSame(200, $response->getStatusCode());
1076 }
1077
1078 public function testInformationalResponseStream()
1079 {
1080 $client = $this->getHttpClient(__FUNCTION__);
1081 $response = $client->request('GET', 'http://localhost:8057/103');
1082
1083 $chunks = [];
1084 foreach ($client->stream($response) as $chunk) {
1085 $chunks[] = $chunk;
1086 }
1087
1088 $this->assertSame(103, $chunks[0]->getInformationalStatus()[0]);
1089 $this->assertSame(['</style.css>; rel=preload; as=style', '</script.js>; rel=preload; as=script'], $chunks[0]->getInformationalStatus()[1]['link']);
1090 $this->assertTrue($chunks[1]->isFirst());
1091 $this->assertSame('Here the body', $chunks[2]->getContent());
1092 $this->assertTrue($chunks[3]->isLast());
1093 $this->assertNull($chunks[3]->getInformationalStatus());
1094
1095 $this->assertSame(['date', 'content-length'], array_keys($response->getHeaders()));
1096 $this->assertContains('Link: </style.css>; rel=preload; as=style', $response->getInfo('response_headers'));
1097 }
1098
1099 /**
1100 * @requires extension zlib
1101 */
1102 #[RequiresPhpExtension('zlib')]
1103 public function testUserlandEncodingRequest()
1104 {
1105 $client = $this->getHttpClient(__FUNCTION__);
1106 $response = $client->request('GET', 'http://localhost:8057', [
1107 'headers' => ['Accept-Encoding' => 'gzip'],
1108 ]);
1109
1110 $headers = $response->getHeaders();
1111
1112 $this->assertSame(['Accept-Encoding'], $headers['vary']);
1113 $this->assertStringContainsString('gzip', $headers['content-encoding'][0]);
1114
1115 $body = $response->getContent();
1116 $this->assertSame("\x1F", $body[0]);
1117
1118 $body = json_decode(gzdecode($body), true);
1119 $this->assertSame('gzip', $body['HTTP_ACCEPT_ENCODING']);
1120 }
1121
1122 /**
1123 * @requires extension zlib
1124 */
1125 #[RequiresPhpExtension('zlib')]
1126 public function testGzipBroken()
1127 {
1128 $client = $this->getHttpClient(__FUNCTION__);
1129 $response = $client->request('GET', 'http://localhost:8057/gzip-broken');
1130
1131 $this->expectException(TransportExceptionInterface::class);
1132 $response->getContent();
1133 }
1134
1135 public function testMaxDuration()
1136 {
1137 $client = $this->getHttpClient(__FUNCTION__);
1138 $response = $client->request('GET', 'http://localhost:8057/max-duration', [
1139 'max_duration' => 0.1,
1140 ]);
1141
1142 $start = microtime(true);
1143
1144 try {
1145 $response->getContent();
1146 } catch (TransportExceptionInterface) {
1147 $this->addToAssertionCount(1);
1148 }
1149
1150 $duration = microtime(true) - $start;
1151
1152 $this->assertLessThan(10, $duration);
1153 }
1154
1155 public function testMaxConnectDurationInfo()
1156 {
1157 $client = $this->getHttpClient(__FUNCTION__);
1158 $response = $client->request('GET', 'http://localhost:8057/', [
1159 'max_connect_duration' => 10.0,
1160 ]);
1161
1162 $this->assertSame(10.0, $response->getInfo('max_connect_duration'));
1163 $this->assertSame(200, $response->getStatusCode());
1164 }
1165
1166 public function testMaxConnectDuration()
1167 {
1168 $client = $this->getHttpClient(__FUNCTION__);
1169
1170 $response = $client->request('GET', 'http://10.255.255.1/', [
1171 'max_connect_duration' => 0.1,
1172 'timeout' => 10,
1173 ]);
1174
1175 $start = microtime(true);
1176
1177 try {
1178 $response->getHeaders();
1179 $this->fail(TransportExceptionInterface::class.' expected');
1180 } catch (TransportExceptionInterface) {
1181 $this->addToAssertionCount(1);
1182 }
1183
1184 $duration = microtime(true) - $start;
1185
1186 $this->assertLessThan(2, $duration, 'Should timeout much faster than the 10s timeout option');
1187 $this->assertGreaterThan(0.05, $duration, 'Should take at least some time before timing out');
1188 }
1189
1190 public function testWithOptions()
1191 {
1192 $client = $this->getHttpClient(__FUNCTION__);
1193 $client2 = $client->withOptions(['base_uri' => 'http://localhost:8057/']);
1194
1195 $this->assertNotSame($client, $client2);
1196 $this->assertSame($client::class, $client2::class);
1197
1198 $response = $client2->request('GET', '/');
1199 $this->assertSame(200, $response->getStatusCode());
1200 }
1201
1202 public function testBindToPort()
1203 {
1204 $client = $this->getHttpClient(__FUNCTION__);
1205 $response = $client->request('GET', 'http://localhost:8057', ['bindto' => '127.0.0.1:9876']);
1206 $response->getStatusCode();
1207
1208 $vars = $response->toArray();
1209
1210 self::assertSame('127.0.0.1', $vars['REMOTE_ADDR']);
1211 self::assertSame('9876', $vars['REMOTE_PORT']);
1212 }
1213
1214 public function testBindToPortV6()
1215 {
1216 TestHttpServer::start(-8087);
1217
1218 $client = $this->getHttpClient(__FUNCTION__);
1219 $response = $client->request('GET', 'http://[::1]:8087', ['bindto' => '[::1]:9876']);
1220 $response->getStatusCode();
1221
1222 $vars = $response->toArray();
1223
1224 self::assertSame('::1', $vars['REMOTE_ADDR']);
1225
1226 if ('\\' !== \DIRECTORY_SEPARATOR) {
1227 self::assertSame('9876', $vars['REMOTE_PORT']);
1228 }
1229 }
1230 }