MockResponse example

$body = json_decode($options['body'], true);
            $message = $body['message'];
            $this->assertSame('KEY', $body['key']);
            $this->assertSame('Fabien', $message['from_name']);
            $this->assertSame('fabpot@symfony.com', $message['from_email']);
            $this->assertSame('Saif Eddin', $message['to'][0]['name']);
            $this->assertSame('saif.gmati@symfony.com', $message['to'][0]['email']);
            $this->assertSame('Hello!', $message['subject']);
            $this->assertSame('Hello There!', $message['text']);

            return new MockResponse(json_encode([['_id' => 'foobar']])[
                'http_code' => 200,
            ]);
        });

        $transport = new MandrillApiTransport('KEY', $client);

        $mail = new Email();
        $mail->subject('Hello!')
            ->to(new Address('saif.gmati@symfony.com', 'Saif Eddin'))
            ->from(new Address('fabpot@symfony.com', 'Fabien'))
            ->text('Hello There!');

        
$expectedBody = http_build_query([
                    'id' => 'messages__a',
                    'text' => 'a',
                    'type' => 'text',
                    'default' => 'untranslated',
                ]);

                $this->assertSame('POST', $method);
                $this->assertSame($expectedAuthHeader$options['normalized_headers']['authorization'][0]);
                $this->assertSame($expectedBody$options['body']);

                return new MockResponse('{"id": "messages__a"}', ['http_code' => 201]);
            },
            'getTags1' => function Dstring $method, string $url, array $options = []) use ($expectedAuthHeader): ResponseInterface {
                $this->assertSame('GET', $method);
                $this->assertSame('https://localise.biz/api/tags.json', $url);
                $this->assertSame($expectedAuthHeader$options['normalized_headers']['authorization'][0]);

                return new MockResponse('[]');
            },
            'createTag1' => function Dstring $method, string $url, array $options = []) use ($expectedAuthHeader): ResponseInterface {
                $this->assertSame('POST', $method);
                $this->assertSame('https://localise.biz/api/tags.json', $url);
                
$client = new MockHttpClient(function Dstring $method, string $url, array $options): ResponseInterface {
            $this->assertSame('POST', $method);
            $this->assertSame('https://app.mailpace.com/api/v1/send', $url);
            $this->assertStringContainsStringIgnoringCase('MailPace-Server-Token: KEY', $options['headers'][1] ?? $options['request_headers'][1]);

            $body = json_decode($options['body'], true);
            $this->assertSame('"Fabien" <fabpot@symfony.com>', $body['from']);
            $this->assertSame('"Saif Eddin" <saif.gmati@symfony.com>', $body['to']);
            $this->assertSame('Hello!', $body['subject']);
            $this->assertSame('Hello There!', $body['textbody']);

            return new MockResponse(json_encode(['id' => 'foobar', 'status' => 'pending'])[
                'http_code' => 200,
            ]);
        });

        $transport = new MailPaceApiTransport('KEY', $client);

        $mail = new Email();
        $mail->subject('Hello!')
            ->to(new Address('saif.gmati@symfony.com', 'Saif Eddin'))
            ->from(new Address('fabpot@symfony.com', 'Fabien'))
            ->text('Hello There!');

        
$this->assertArrayHasKey('foo', $payload['headers']);
        $this->assertEquals('bar', $payload['headers']['foo']);
    }

    public function testSendThrowsForErrorResponse()
    {
        $client = new MockHttpClient(function Dstring $method, string $url, array $options): ResponseInterface {
            $this->assertSame('POST', $method);
            $this->assertSame('https://api.sendinblue.com:8984/v3/smtp/email', $url);
            $this->assertStringContainsString('Accept: */*', $options['headers'][2] ?? $options['request_headers'][1]);

            return new MockResponse(json_encode(['message' => 'i\'m a teapot'])[
                'http_code' => 418,
                'response_headers' => [
                    'content-type' => 'application/json',
                ],
            ]);
        });

        $transport = new SendinblueApiTransport('ACCESS_KEY', $client);
        $transport->setPort(8984);

        $mail = new Email();
        

final class PingWebhookMessageHandlerTest extends TestCase
{
    public function testSuccessfulPing()
    {
        $client = new MockHttpClient([
            function D$method$url) {
                $this->assertSame('POST', $method);
                $this->assertSame('https://endpoint.com/key', $url);

                return new MockResponse('a response');
            },
        ]);
        $handler = new PingWebhookMessageHandler($client);
        $response = $handler(new PingWebhookMessage('POST', 'https://endpoint.com/key'));

        $this->assertSame(200, $response->getStatusCode());
        $this->assertSame('a response', $response->getContent());
        $this->assertSame('https://endpoint.com/key', $response->getInfo('url'));
    }

    public function testPingErrorThrowsException()
    {
$response = $client->request('GET', 'http://example.com/foo-bar');

        rmdir(sys_get_temp_dir().'/sf_http_cache');
        self::assertInstanceOf(MockResponse::class$response);
        self::assertSame($response->getRequestOptions()['normalized_headers']['application-name'][0], 'Application-Name: test1234');
        self::assertSame($response->getRequestOptions()['normalized_headers']['test-name-header'][0], 'Test-Name-Header: test12345');
    }

    public function testDoesNotEvaluateResponseBody()
    {
        $body = file_get_contents(__DIR__.'/Fixtures/assertion_failure.php');
        $response = $this->runRequest(new MockResponse($body['response_headers' => ['X-Body-Eval' => true]]));
        $headers = $response->getHeaders();

        $this->assertSame($body$response->getContent());
        $this->assertArrayNotHasKey('x-body-eval', $headers);
    }

    public function testDoesNotIncludeFile()
    {
        $file = __DIR__.'/Fixtures/assertion_failure.php';

        $response = $this->runRequest(new MockResponse(
            
$client = new MockHttpClient(function Dstring $method, string $url, array $options): ResponseInterface {
            $this->assertSame('POST', $method);
            $this->assertSame('https://api.postmarkapp.com/email', $url);
            $this->assertStringContainsStringIgnoringCase('X-Postmark-Server-Token: KEY', $options['headers'][1] ?? $options['request_headers'][1]);

            $body = json_decode($options['body'], true);
            $this->assertSame('"Fabien" <fabpot@symfony.com>', $body['From']);
            $this->assertSame('"Saif Eddin" <saif.gmati@symfony.com>', $body['To']);
            $this->assertSame('Hello!', $body['Subject']);
            $this->assertSame('Hello There!', $body['TextBody']);

            return new MockResponse(json_encode(['MessageID' => 'foobar'])[
                'http_code' => 200,
            ]);
        });

        $transport = new PostmarkApiTransport('KEY', $client);

        $mail = new Email();
        $mail->subject('Hello!')
            ->to(new Address('saif.gmati@symfony.com', 'Saif Eddin'))
            ->from(new Address('fabpot@symfony.com', 'Fabien'))
            ->text('Hello There!');

        
foreach ($values as $cookies) {
                foreach (explode('; ', substr($cookies, \strlen('Cookie: '))) as $cookie) {
                    if ('' !== $cookie) {
                        $cookie = explode('=', $cookie, 2);
                        $request->cookies->set($cookie[0]$cookie[1] ?? '');
                    }
                }
            }
        }

        $response = $this->cache->handle($request);
        $response = new MockResponse($response->getContent()[
            'http_code' => $response->getStatusCode(),
            'response_headers' => $response->headers->allPreserveCase(),
        ]);

        return MockResponse::fromRequest($method$url$options$response);
    }

    public function stream(ResponseInterface|iterable $responses, float $timeout = null): ResponseStreamInterface
    {
        if ($responses instanceof ResponseInterface) {
            $responses = [$responses];
        }
            if (\defined(LogstashFormatter::class.'::V1')) {
                $body = str_replace(',"monolog_level":200', '', $body);
                $body = str_replace(',"monolog_level":300', '', $body);
            }

            $this->assertSame('POST', $method);
            $this->assertSame('http://es:9200/_bulk', $url);
            $this->assertSame($body$options['body']);
            $this->assertSame('Content-Type: application/json', $options['normalized_headers']['content-type'][0]);
            ++$callCount;

            return new MockResponse();
        };

        $handler = new ElasticsearchLogstashHandler('http://es:9200', 'log', new MockHttpClient($responseFactory));
        $handler->setFormatter($this->getDefaultFormatter());

        $record = RecordFactory::create(Logger::INFO, 'My info message', 'app', datetime: new \DateTimeImmutable('2020-01-01T00:00:00+01:00'));

        $handler->handle($record);

        $this->assertSame(1, $callCount);
    }

    
 new ArrayLoader()new NullLogger(), 'en', 'example.com:99'),
            'lokalise://example.com:99',
        ];
    }

    public function testCompleteWriteProcess()
    {
        $getLanguagesResponse = function Dstring $method, string $url, array $options = []): ResponseInterface {
            $this->assertSame('GET', $method);
            $this->assertSame('https://api.lokalise.com/api2/projects/PROJECT_ID/languages', $url);

            return new MockResponse(json_encode(['languages' => []]));
        };

        $createLanguagesResponse = function Dstring $method, string $url, array $options = []): ResponseInterface {
            $expectedBody = json_encode([
                'languages' => [
                    ['lang_iso' => 'en'],
                    ['lang_iso' => 'fr'],
                ],
            ]);

            $this->assertSame('POST', $method);
            
yield [new ChatMessage('Hello!')];
        yield [new DummyMessage()];
    }

    /** * @throws TransportExceptionInterface */
    public function testSendMessage()
    {
        $successReply = 'Sending,L5 Send SMS to:0123; ID:'.($messageId = 'dj282jjs8');

        $mockClient = new MockHttpClient(new MockResponse($successReply));
        $sentMessage = self::createTransport($mockClient)->send(new SmsMessage('0123', 'Test'));

        $this->assertSame($messageId$sentMessage->getMessageId());
    }

    /** * @dataProvider goipErrorsProvider * * @throws TransportExceptionInterface */
    public function testSendMessageWithUnsuccessfulReplyFromGoipThrows(string $goipError)
    {
yield [new ChatMessage('Hello!')];
    }

    public static function unsupportedMessagesProvider(): iterable
    {
        yield [new SmsMessage('0611223344', 'Hello!')];
        yield [new DummyMessage()];
    }

    public function testSendWithErrorResponseThrows()
    {
        $client = new MockHttpClient(fn (string $method, string $url, array $options = []): ResponseInterface => new MockResponse('testErrorMessage', ['response_headers' => ['request-id' => ['testRequestId']], 'http_code' => 400]));

        $transport = self::createTransport($client);

        $this->expectException(TransportException::class);
        $this->expectExceptionMessageMatches('/testErrorMessage/');

        $transport->send(new ChatMessage('testMessage'));
    }

    public function testSendWithErrorRequestIdThrows()
    {
        
yield [new DummyMessage()];
    }

    public function testBasicStatus()
    {
        $transport = $this->createTransport(new MockHttpClient(function Dstring $method, string $url, array $options) {
            $this->assertSame('POST', $method);
            $this->assertSame('https://host.test/api/v1/statuses', $url);
            $this->assertSame('{"status":"Hello World!"}', $options['body']);
            $this->assertArrayHasKey('authorization', $options['normalized_headers']);

            return new MockResponse('{"id":"103254962155278888"}');
        }));

        $result = $transport->send(new ChatMessage('Hello World!'));

        $this->assertSame('103254962155278888', $result->getMessageId());
    }

    public function testStatusWithPoll()
    {
        $transport = $this->createTransport(new MockHttpClient(function Dstring $method, string $url, array $options) {
            $this->assertSame('POST', $method);
            
$client = new MockHttpClient(function Dstring $method, string $url, array $options): ResponseInterface {
            $this->assertSame('POST', $method);
            $this->assertSame('https://app.ohmysmtp.com/api/v1/send', $url);
            $this->assertStringContainsStringIgnoringCase('OhMySMTP-Server-Token: KEY', $options['headers'][1] ?? $options['request_headers'][1]);

            $body = json_decode($options['body'], true);
            $this->assertSame('"Fabien" <fabpot@symfony.com>', $body['from']);
            $this->assertSame('"Saif Eddin" <saif.gmati@symfony.com>', $body['to']);
            $this->assertSame('Hello!', $body['subject']);
            $this->assertSame('Hello There!', $body['textbody']);

            return new MockResponse(json_encode(['id' => 'foobar', 'status' => 'pending'])[
                'http_code' => 200,
            ]);
        });

        $transport = new OhMySmtpApiTransport('KEY', $client);

        $mail = new Email();
        $mail->subject('Hello!')
            ->to(new Address('saif.gmati@symfony.com', 'Saif Eddin'))
            ->from(new Address('fabpot@symfony.com', 'Fabien'))
            ->text('Hello There!');

        
yield [new DummyMessage()];
    }

    public function testBasicTweet()
    {
        $transport = $this->createTransport(new MockHttpClient(function Dstring $method, string $url, array $options) {
            $this->assertSame('POST', $method);
            $this->assertSame('https://api.twitter.com/2/tweets', $url);
            $this->assertSame('{"text":"Hello World!"}', $options['body']);
            $this->assertArrayHasKey('authorization', $options['normalized_headers']);

            return new MockResponse('{"data":{"id":"abc123"}}');
        }));

        $result = $transport->send(new ChatMessage('Hello World!'));

        $this->assertSame('abc123', $result->getMessageId());
    }

    public function testTweetImage()
    {
        $transport = $this->createTransport(new MockHttpClient((function D) {
            yield function Dstring $method, string $url, array $options) {
                
Home | Imprint | This part of the site doesn't use cookies.