File: MockHttpClientTest.php

package info (click to toggle)
symfony 7.3.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 147,804 kB
  • sloc: php: 1,506,509; xml: 6,816; javascript: 1,043; sh: 586; makefile: 241; pascal: 70
file content (596 lines) | stat: -rw-r--r-- 22,180 bytes parent folder | download
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
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpClient\Tests;

use Symfony\Component\HttpClient\Chunk\DataChunk;
use Symfony\Component\HttpClient\Chunk\ErrorChunk;
use Symfony\Component\HttpClient\Chunk\FirstChunk;
use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\NativeHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\HttpClient\Response\ResponseStream;
use Symfony\Contracts\HttpClient\ChunkInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class MockHttpClientTest extends HttpClientTestCase
{
    #[\PHPUnit\Framework\Attributes\DataProvider('mockingProvider')]
    public function testMocking($factory, array $expectedResponses)
    {
        $client = new MockHttpClient($factory);
        $this->assertSame(0, $client->getRequestsCount());

        $urls = ['/foo', '/bar'];
        foreach ($urls as $i => $url) {
            $response = $client->request('POST', $url, ['body' => 'payload']);
            $this->assertEquals($expectedResponses[$i], $response->getContent());
        }

        $this->assertSame(2, $client->getRequestsCount());
    }

    public static function mockingProvider(): iterable
    {
        yield 'callable' => [
            static fn (string $method, string $url, array $options = []) => new MockResponse($method.': '.$url.' (body='.$options['body'].')'),
            [
                'POST: https://example.com/foo (body=payload)',
                'POST: https://example.com/bar (body=payload)',
            ],
        ];

        yield 'array of callable' => [
            [
                static fn (string $method, string $url, array $options = []) => new MockResponse($method.': '.$url.' (body='.$options['body'].') [1]'),
                static fn (string $method, string $url, array $options = []) => new MockResponse($method.': '.$url.' (body='.$options['body'].') [2]'),
            ],
            [
                'POST: https://example.com/foo (body=payload) [1]',
                'POST: https://example.com/bar (body=payload) [2]',
            ],
        ];

        yield 'array of response objects' => [
            [
                new MockResponse('static response [1]'),
                new MockResponse('static response [2]'),
            ],
            [
                'static response [1]',
                'static response [2]',
            ],
        ];

        yield 'iterator' => [
            new \ArrayIterator(
                [
                    new MockResponse('static response [1]'),
                    new MockResponse('static response [2]'),
                ]
            ),
            [
                'static response [1]',
                'static response [2]',
            ],
        ];

        yield 'null' => [
            null,
            [
                '',
                '',
            ],
        ];
    }

    #[\PHPUnit\Framework\Attributes\DataProvider('validResponseFactoryProvider')]
    public function testValidResponseFactory($responseFactory)
    {
        (new MockHttpClient($responseFactory))->request('GET', 'https://foo.bar');

        $this->addToAssertionCount(1);
    }

    public static function validResponseFactoryProvider()
    {
        return [
            [static fn (): MockResponse => new MockResponse()],
            [new MockResponse()],
            [[new MockResponse()]],
            [new \ArrayIterator([new MockResponse()])],
            [null],
            [(static function (): \Generator { yield new MockResponse(); })()],
        ];
    }

    #[\PHPUnit\Framework\Attributes\DataProvider('transportExceptionProvider')]
    public function testTransportExceptionThrowsIfPerformedMoreRequestsThanConfigured($factory)
    {
        $client = new MockHttpClient($factory);

        $client->request('POST', '/foo');
        $client->request('POST', '/foo');

        $this->expectException(TransportException::class);
        $client->request('POST', '/foo');
    }

    public static function transportExceptionProvider(): iterable
    {
        yield 'array of callable' => [
            [
                static fn (string $method, string $url, array $options = []) => new MockResponse(),
                static fn (string $method, string $url, array $options = []) => new MockResponse(),
            ],
        ];

        yield 'array of response objects' => [
            [
                new MockResponse(),
                new MockResponse(),
            ],
        ];

        yield 'iterator' => [
            new \ArrayIterator(
                [
                    new MockResponse(),
                    new MockResponse(),
                ]
            ),
        ];
    }

    #[\PHPUnit\Framework\Attributes\DataProvider('invalidResponseFactoryProvider')]
    public function testInvalidResponseFactory($responseFactory, string $expectedExceptionMessage)
    {
        $this->expectException(TransportException::class);
        $this->expectExceptionMessage($expectedExceptionMessage);

        (new MockHttpClient($responseFactory))->request('GET', 'https://foo.bar');
    }

    public static function invalidResponseFactoryProvider()
    {
        return [
            [static function (): \Generator { yield new MockResponse(); }, 'The response factory passed to MockHttpClient must return/yield an instance of ResponseInterface, "Generator" given.'],
            [static fn (): array => [new MockResponse()], 'The response factory passed to MockHttpClient must return/yield an instance of ResponseInterface, "array" given.'],
            [(static function (): \Generator { yield 'ccc'; })(), 'The response factory passed to MockHttpClient must return/yield an instance of ResponseInterface, "string" given.'],
        ];
    }

    public function testZeroStatusCode()
    {
        $client = new MockHttpClient(new MockResponse('', ['response_headers' => ['HTTP/1.1 000 ']]));
        $response = $client->request('GET', 'https://foo.bar');
        $this->assertSame(0, $response->getStatusCode());
    }

    public function testFixContentLength()
    {
        $client = new MockHttpClient();

        $response = $client->request('POST', 'http://localhost:8057/post', [
            'body' => 'abc=def',
            'headers' => ['Content-Length: 4'],
        ]);

        $requestOptions = $response->getRequestOptions();
        $this->assertSame('Content-Length: 7', $requestOptions['headers'][0]);
        $this->assertSame(['Content-Length: 7'], $requestOptions['normalized_headers']['content-length']);

        $response = $client->request('POST', 'http://localhost:8057/post', [
            'body' => 'abc=def',
        ]);

        $requestOptions = $response->getRequestOptions();
        $this->assertSame('Content-Length: 7', $requestOptions['headers'][1]);
        $this->assertSame(['Content-Length: 7'], $requestOptions['normalized_headers']['content-length']);

        $response = $client->request('POST', 'http://localhost:8057/post', [
            'body' => "8\r\nSymfony \r\n5\r\nis aw\r\n6\r\nesome!\r\n0\r\n\r\n",
            'headers' => ['Transfer-Encoding: chunked'],
        ]);

        $requestOptions = $response->getRequestOptions();
        $this->assertSame(['Content-Length: 19'], $requestOptions['normalized_headers']['content-length']);

        $response = $client->request('POST', 'http://localhost:8057/post', [
            'body' => '',
        ]);

        $requestOptions = $response->getRequestOptions();
        $this->assertFalse(isset($requestOptions['normalized_headers']['content-length']));
    }

    public function testThrowExceptionInBodyGenerator()
    {
        $mockHttpClient = new MockHttpClient([
            new MockResponse((static function (): \Generator {
                yield 'foo';
                throw new TransportException('foo ccc');
            })()),
            new MockResponse((static function (): \Generator {
                yield 'bar';
                throw new \RuntimeException('bar ccc');
            })()),
        ]);

        try {
            $mockHttpClient->request('GET', 'https://symfony.com', [])->getContent();
            $this->fail();
        } catch (TransportException $e) {
            $this->assertEquals(new TransportException('foo ccc'), $e->getPrevious());
            $this->assertSame('foo ccc', $e->getMessage());
        }

        $chunks = [];
        try {
            foreach ($mockHttpClient->stream($mockHttpClient->request('GET', 'https://symfony.com', [])) as $chunk) {
                $chunks[] = $chunk;
            }
            $this->fail();
        } catch (TransportException $e) {
            $this->assertEquals(new \RuntimeException('bar ccc'), $e->getPrevious());
            $this->assertSame('bar ccc', $e->getMessage());
        }

        $this->assertCount(3, $chunks);
        $this->assertEquals(new FirstChunk(0, ''), $chunks[0]);
        $this->assertEquals(new DataChunk(0, 'bar'), $chunks[1]);
        $this->assertInstanceOf(ErrorChunk::class, $chunks[2]);
        $this->assertSame(3, $chunks[2]->getOffset());
        $this->assertSame('bar ccc', $chunks[2]->getError());
    }

    public function testMergeDefaultOptions()
    {
        $mockHttpClient = new MockHttpClient(null, 'https://example.com');

        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid URL: scheme is missing');
        $mockHttpClient->request('GET', '/foo', ['base_uri' => null]);
    }

    public function testExceptionDirectlyInBody()
    {
        $mockHttpClient = new MockHttpClient([
            new MockResponse(['foo', new \RuntimeException('foo ccc')]),
            new MockResponse((static function (): \Generator {
                yield 'bar';
                yield new TransportException('bar ccc');
            })()),
        ]);

        try {
            $mockHttpClient->request('GET', 'https://symfony.com', [])->getContent();
            $this->fail();
        } catch (TransportException $e) {
            $this->assertEquals(new \RuntimeException('foo ccc'), $e->getPrevious());
            $this->assertSame('foo ccc', $e->getMessage());
        }

        $chunks = [];
        try {
            foreach ($mockHttpClient->stream($mockHttpClient->request('GET', 'https://symfony.com', [])) as $chunk) {
                $chunks[] = $chunk;
            }
            $this->fail();
        } catch (TransportException $e) {
            $this->assertEquals(new TransportException('bar ccc'), $e->getPrevious());
            $this->assertSame('bar ccc', $e->getMessage());
        }

        $this->assertCount(3, $chunks);
        $this->assertEquals(new FirstChunk(0, ''), $chunks[0]);
        $this->assertEquals(new DataChunk(0, 'bar'), $chunks[1]);
        $this->assertInstanceOf(ErrorChunk::class, $chunks[2]);
        $this->assertSame(3, $chunks[2]->getOffset());
        $this->assertSame('bar ccc', $chunks[2]->getError());
    }

    protected function getHttpClient(string $testCase): HttpClientInterface
    {
        $responses = [];

        $headers = [
            'Host: localhost:8057',
            'Content-Type: application/json',
        ];

        $body = '{
    "SERVER_PROTOCOL": "HTTP/1.1",
    "SERVER_NAME": "127.0.0.1",
    "REQUEST_URI": "/",
    "REQUEST_METHOD": "GET",
    "HTTP_ACCEPT": "*/*",
    "HTTP_FOO": "baR",
    "HTTP_HOST": "localhost:8057"
}';

        $client = new NativeHttpClient();

        switch ($testCase) {
            default:
                return new MockHttpClient(function (string $method, string $url, array $options) use ($client, $testCase) {
                    try {
                        // force the request to be completed so that we don't test side effects of the transport
                        $response = $client->request($method, $url, ['buffer' => false] + $options);
                        $content = $response->getContent(false);

                        return new MockResponse($content, $response->getInfo());
                    } catch (\Throwable $e) {
                        if (str_starts_with($testCase, 'testNoPrivateNetwork')) {
                            throw $e;
                        }
                        $this->fail($e->getMessage());
                    }
                });

            case 'testUnsupportedOption':
                $this->markTestSkipped('MockHttpClient accepts any options by default');
                break;

            case 'testChunkedEncoding':
                $this->markTestSkipped("MockHttpClient doesn't dechunk");
                break;

            case 'testGzipBroken':
                $this->markTestSkipped("MockHttpClient doesn't unzip");
                break;

            case 'testTimeoutWithActiveConcurrentStream':
                $this->markTestSkipped('Real transport required');
                break;

            case 'testTimeoutOnInitialize':
            case 'testTimeoutOnDestruct':
                $this->markTestSkipped('Real transport required');
                break;

            case 'testDestruct':
                $this->markTestSkipped("MockHttpClient doesn't timeout on destruct");
                break;

            case 'testHandleIsRemovedOnException':
                $this->markTestSkipped("MockHttpClient doesn't cache handles");
                break;

            case 'testPause':
            case 'testPauseReplace':
            case 'testPauseDuringBody':
                $this->markTestSkipped("MockHttpClient doesn't support pauses by default");
                break;

            case 'testDnsFailure':
                $this->markTestSkipped("MockHttpClient doesn't use a DNS");
                break;

            case 'testGetRequest':
                array_unshift($headers, 'HTTP/1.1 200 OK');
                $responses[] = new MockResponse($body, ['response_headers' => $headers]);

                $headers = [
                    'Host: localhost:8057',
                    'Content-Length: 1000',
                    'Content-Type: application/json',
                ];

                $responses[] = new MockResponse($body, ['response_headers' => $headers]);
                break;

            case 'testDnsError':
                $responses[] = $mockResponse = new MockResponse('', ['error' => 'DNS error']);
                $responses[] = $mockResponse;
                break;

            case 'testToStream':
            case 'testBadRequestBody':
            case 'testOnProgressCancel':
            case 'testOnProgressError':
            case 'testReentrantBufferCallback':
            case 'testThrowingBufferCallback':
            case 'testInfoOnCanceledResponse':
            case 'testChangeResponseFactory':
                $responses[] = new MockResponse($body, ['response_headers' => $headers]);
                break;

            case 'testTimeoutOnAccess':
                $responses[] = new MockResponse('', ['error' => 'Timeout']);
                break;

            case 'testAcceptHeader':
                $responses[] = new MockResponse($body, ['response_headers' => $headers]);
                $responses[] = new MockResponse(str_replace('*/*', 'foo/bar', $body), ['response_headers' => $headers]);
                $responses[] = new MockResponse(str_replace('"HTTP_ACCEPT": "*/*",', '', $body), ['response_headers' => $headers]);
                break;

            case 'testResolve':
                $responses[] = new MockResponse($body, ['response_headers' => $headers]);
                $responses[] = new MockResponse($body, ['response_headers' => $headers]);
                $responses[] = new MockResponse((function () { yield ''; })(), ['response_headers' => $headers]);
                break;

            case 'testTimeoutOnStream':
            case 'testUncheckedTimeoutThrows':
            case 'testTimeoutIsNotAFatalError':
                $body = ['<1>', '', '<2>'];
                $responses[] = new MockResponse($body, ['response_headers' => $headers]);
                break;

            case 'testInformationalResponseStream':
                $client = $this->createMock(HttpClientInterface::class);
                $response = new MockResponse('Here the body', ['response_headers' => [
                    'HTTP/1.1 103 ',
                    'Link: </style.css>; rel=preload; as=style',
                    'HTTP/1.1 200 ',
                    'Date: foo',
                    'Content-Length: 13',
                ]]);
                $client->method('request')->willReturn($response);
                $client->method('stream')->willReturn(new ResponseStream((function () use ($response) {
                    $chunk = $this->createMock(ChunkInterface::class);
                    $chunk->method('getInformationalStatus')
                        ->willReturn([103, ['link' => ['</style.css>; rel=preload; as=style', '</script.js>; rel=preload; as=script']]]);

                    yield $response => $chunk;

                    $chunk = $this->createMock(ChunkInterface::class);
                    $chunk->method('isFirst')->willReturn(true);

                    yield $response => $chunk;

                    $chunk = $this->createMock(ChunkInterface::class);
                    $chunk->method('getContent')->willReturn('Here the body');

                    yield $response => $chunk;

                    $chunk = $this->createMock(ChunkInterface::class);
                    $chunk->method('isLast')->willReturn(true);

                    yield $response => $chunk;
                })()));

                return $client;

            case 'testNonBlockingStream':
            case 'testSeekAsyncStream':
                $responses[] = new MockResponse(
                    (function () {
                        yield '<1>';
                        yield '';
                        yield '<2>';
                    })(),
                    ['response_headers' => $headers]
                );
                break;

            case 'testMaxDuration':
                $responses[] = new MockResponse(
                    '',
                    ['error' => 'Max duration was reached.']
                );
                break;
        }

        return new MockHttpClient($responses);
    }

    public function testHttp2PushVulcain()
    {
        $this->markTestSkipped('MockHttpClient doesn\'t support HTTP/2 PUSH.');
    }

    public function testHttp2PushVulcainWithUnusedResponse()
    {
        $this->markTestSkipped('MockHttpClient doesn\'t support HTTP/2 PUSH.');
    }

    public function testUnixSocket()
    {
        $this->markTestSkipped('MockHttpClient doesn\'t support binding to unix sockets.');
    }

    public function testChangeResponseFactory()
    {
        /** @var MockHttpClient $client */
        $client = $this->getHttpClient(__METHOD__);
        $expectedBody = '{"foo": "bar"}';
        $client->setResponseFactory(new MockResponse($expectedBody));

        $response = $client->request('GET', 'http://localhost:8057');

        $this->assertSame($expectedBody, $response->getContent());
    }

    public function testStringableBodyParam()
    {
        $client = new MockHttpClient();

        $param = new class {
            public function __toString(): string
            {
                return 'bar';
            }
        };

        $response = $client->request('GET', 'https://example.com', [
            'body' => ['foo' => $param],
        ]);

        $this->assertSame('foo=bar', $response->getRequestOptions()['body']);
    }

    public function testResetsRequestCount()
    {
        $client = new MockHttpClient([new MockResponse()]);
        $this->assertSame(0, $client->getRequestsCount());

        $client->request('POST', '/url', ['body' => 'payload']);

        $this->assertSame(1, $client->getRequestsCount());
        $client->reset();
        $this->assertSame(0, $client->getRequestsCount());
    }

    public function testCancelingMockResponseExecutesOnProgressWithUpdatedInfo()
    {
        $client = new MockHttpClient(new MockResponse(['foo', 'bar', 'ccc']));
        $canceled = false;
        $response = $client->request('GET', 'https://example.com', [
            'on_progress' => static function (int $dlNow, int $dlSize, array $info) use (&$canceled): void {
                $canceled = $info['canceled'];
            },
        ]);

        foreach ($client->stream($response) as $response => $chunk) {
            if ('bar' === $chunk->getContent()) {
                $response->cancel();

                break;
            }
        }

        $this->assertTrue($canceled);
    }

    public function testEmptyResponseFactory()
    {
        $this->expectException(TransportException::class);
        $this->expectExceptionMessage('The response factory iterator passed to MockHttpClient is empty.');

        $client = new MockHttpClient([]);
        $client->request('GET', 'https://example.com');
    }

    public function testMoreRequestsThanResponseFactoryResponses()
    {
        $this->expectException(TransportException::class);
        $this->expectExceptionMessage('No more response left in the response factory iterator passed to MockHttpClient: the number of requests exceeds the number of responses.');

        $client = new MockHttpClient([new MockResponse()]);
        $client->request('GET', 'https://example.com');
        $client->request('GET', 'https://example.com');
    }

    public function testMockStartTimeInfo()
    {
        $client = new MockHttpClient(new MockResponse('foobarccc', [
            'start_time' => 1701187598.313123,
        ]));

        $response = $client->request('GET', 'https://example.com');
        $this->assertSame(1701187598.313123, $response->getInfo('start_time'));
    }
}