-->

如何检索响应流(如下载文件)与Symfony的测试客户端(How to retrieve a str

2019-08-18 11:34发布

我写这封信与Symfony2的功能测试。

我有一个控制器,它调用getImage()如下哪些流中的图像文件的功能:

public function getImage($filePath)
    $response = new StreamedResponse();
    $response->headers->set('Content-Type', 'image/png');

    $response->setCallback(function () use ($filePath) {
        $bytes = @readfile(filePath);
        if ($bytes === false || $bytes <= 0)
            throw new NotFoundHttpException();
    });

    return $response;
}

在功能测试,我尽量要求与内容Symfony的测试客户端 ,如下所示:

$client = static::createClient();
$client->request('GET', $url);
$content = $client->getResponse()->getContent();

问题是, $content是空的,我猜想因为只要HTTP头是由客户端收到生成的响应,而无需等待数据流交付。

有没有一种方法,同时还使用捉流响应的内容$client->request()或者甚至一些其它功能)将请求发送到服务器?

Answer 1:

sendContent的返回值(而不是的getContent)是你设置回调。 实际上的getContent刚刚在Symfony2中返回false

使用sendContent您可以启用输出缓冲并分配的内容能为您的测试,像这样:

$client = static::createClient();
$client->request('GET', $url);

// Enable the output buffer
ob_start();
// Send the response to the output buffer
$client->getResponse()->sendContent();
// Get the contents of the output buffer
$content = ob_get_contents();
// Clean the output buffer and end it
ob_end_clean();

你可以阅读更多的输出缓冲器这里

对于StreamResponse的API是这里



Answer 2:

对我来说,没有工作那样。 相反,我用ob_start()提出请求之前,和请求后,我用$内容= ob_get_clean()和制作上断言该内容。

在测试:

    // Enable the output buffer
    ob_start();
    $this->client->request(
        'GET',
        '$url',
        array(),
        array(),
        array('CONTENT_TYPE' => 'application/json')
    );
    // Get the output buffer and clean it
    $content = ob_get_clean();
    $this->assertEquals('my response content', $content);

也许这是因为我的反应是一个CSV文件。

在控制器:

    $response->headers->set('Content-Type', 'text/csv; charset=utf-8');


文章来源: How to retrieve a streamed response (e.g. download a file) with Symfony test client