2013-03-31 9 views
10

Sto scrivendo test funzionali con Symfony2.Come recuperare una risposta in streaming (ad esempio, scaricare un file) con il client di prova Symfony

ho un controller che chiama una funzione getImage() che emana un file immagine come segue:

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; 
} 

Nei test funzionale, ho una richiesta al contenuto con la Symfony test client come segue:

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

Il problema è che $content è vuoto, suppongo perché la risposta viene generata non appena le intestazioni HTTP vengono ricevute dal client, senza attendere la consegna di un flusso di dati.

C'è un modo per intercettare il contenuto della risposta in streaming mentre si utilizza ancora $client->request() (o anche qualche altra funzione) per inviare la richiesta al server?

risposta

7

Il valore di ritorno di sendContent (piuttosto che getContent) è il callback che hai impostato. getContent in realtà restituisce solo falso in Symfony2

Utilizzando sendContent è possibile attivare il buffer di output e assegnare il contenuto a quello per i test, in questo modo:

$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(); 

Puoi leggere altro su il buffer di uscita here

l'API per StreamResponse è here

+2

Per me arrivare a questo lavoro ho dovuto mettere ob_start() prima di effettuare la richiesta. –

6

Per me non ha funzionato in questo modo. Invece, ho usato ob_start() prima di fare la richiesta, e dopo la richiesta ho usato $ content = ob_get_clean() e fatto affermazioni su quel contenuto.

In prova:

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

Forse questo era perché la mia risposta è un file csv.

In regolatore:

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

Grazie, ha funzionato anche con l'oggetto 'Symfony \ Component \ HttpFoundation \ Response'. –

Problemi correlati