symfony: [BrowserKit] [HttpKernel] StreamedResponse is not working with BrowserKit after Symfony is upgraded to 6.1

Symfony version(s) affected

6.1

Description

Symfony\Component\HttpFoundation\StreamedResponse is not working in tests (BrowserKit) after Symfony is upgraded to 6.1 - the output is not rendered.

How to reproduce

When asserting that following StreamedResponse using BrowserKit produces 'test' output:

return new StreamedResponse(static function (): void {
    echo 'test';
});

the test is passing on Symfony 6.0 (see reproducer app: https://github.com/HtunHtunHtet/bug_app/tree/main) but starts to fail after upgrading to 6.1-RC1 (see: https://github.com/HtunHtunHtet/bug_app/tree/symfony-6.1) as the output is empty:

Below information is the output of the PHPUnit test.

Time: 00:00.150, Memory: 12.00 MB

There was 1 failure:

1) App\Tests\DefaultControllerTest::testSomething
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'test'
+''

Only the tests are affected as navigating to the controller page returns a correct response.

Possible Solution

No response

Additional Context

It might be related to recent StreamedResponseListener deprecation: #45476

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 5
  • Comments: 19 (6 by maintainers)

Most upvoted comments

I think i got a similar problem regarding a test for a StreamedResponse:

working test with symfony 6.0

ob_start();
$client->request(Request::METHOD_GET, 'myTestUrl');
$content = \ob_get_clean();
self::assertEquals('foo', $content);

What (know) works for me with symfony 6.1:

$client->request(Request::METHOD_GET, 'myTestUrl');
$content = $client->getInternalResponse()->getContent();
self::assertEquals('foo', $content);

Making StreamedResponse::getContent return the full content completely defeats the purpose of making it a streamed response.

In HttpFoundation, Response::getContent() has a return type string|false precisely to handle the case of responses that are not able to give you the full content at once as a string.

Actually the issue is still at stake!

The solution proposed by @encreinformatique works:

The $client->getInternalResponse()->getContent() worked for me.

    self::$client = self::loggedIn();
    self::$client->request('GET', '/export');
    $content = self::$client->getInternalResponse()->getContent();

    self::assertResponseIsSuccessful();
    self::assertResponseHasHeader('Content-Disposition', 'attachment; filename=users.csv');
    self::assertStringStartsWith('xxx;yyy', $content);

But this is quite obscure, it would be simpler if $streamedResponse->getContent() returned the generated streamed content directly. Otherwise we need to check if the Response is a StreamedResponse and then retrieve the content thanks to $client->getInternalResponse()->getContent().