2013-03-31 1 views
10

Symfony2로 기능 테스트를 작성하고 있습니다.Symfony 테스트 클라이언트로 스트리밍 된 응답을 검색하는 방법 (예 : 파일 다운로드)

나는이 다음과 같이 이미지 파일을 스트리밍하는 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 test client와 컨텐츠를 요청하는 시도를 :

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

문제는 $content이 비어 있다는 것입니다. 데이터 스트림이 전달되기를 기다리지 않고 클라이언트가 HTTP 헤더를 수신하자마자 응답이 생성되기 때문에 문제가 발생합니다.

서버에 요청을 보내기 위해 $client->request() (또는 일부 다른 기능)을 사용하면서 스트리밍 된 응답의 콘텐츠를 잡는 방법이 있습니까?

답변

7

getContent이 아닌 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(); 

당신은 더에 읽을 수 있습니다 : 의 getContent은 실제로 당신이 출력 버퍼를 활성화하고과 같이, 당신의 검사 결과에 대한 것과 내용을 할당 할 수 있습니다 sendContent를 사용

Symfony2

에서 거짓을 반환 출력 버퍼 here

StreamResponse위한 API는 here

이다
+2

나 요청을하기 전에()이 내가위한 ob_start 배치했다 작동하도록하기 위해. –

6

나를 위해 그렇게 일하지 않았다. 대신, 요청을하기 전에 ob_start()를 사용했고 요청 후에 $ content = ob_get_clean()을 사용하여 해당 내용에 대해 주장했습니다. 테스트에서

: 내 대답은 csv 파일이기 때문에

// 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); 

는 어쩌면이었다. 컨트롤러에서

:

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

고마워, 저 역시'Symfony \ Component \ HttpFoundation \ Response' 객체를 사용하여 저에게 효과적이었습니다. –