Closed riley-van-hengstum closed 8 years ago
Hi, sorry, I don't get it. Can you share some more information? So I can take a look.
Which stream do you mean? And how do you access it?
Thanks
I'm testing with a simple webservice that just returns some json content. When I use the GuzzleBundle provided Guzzle Client, I have to explicitly rewind the stream.
// Test without GuzzleBundle. This test succeeds.
public function testWithoutGuzzleBundle()
{
$client = new Client(['base_uri' => $this::BASE_URI]);
$response = $client->get($this::SERVICE_URI);
$contents = $response->getBody()->getContents();
$this->assertGreaterThan(0, strlen($contents));
}
// Using the Guzzle Client provided by GuzzleBundle. This test fails.
public function testGuzzleBundle_Fail()
{
$client = $this->container->get('guzzle.client.test');
$response = $client->get($this::SERVICE_URI);
$contents = $response->getBody()->getContents();
$this->assertGreaterThan(0, strlen($contents));
}
// Rewinding the stream before reading it. Now the test succeeds.
public function testGuzzleBundle_Success()
{
$client = $this->container->get('guzzle.client.test');
$response = $client->get($this::SERVICE_URI);
$response->getBody()->seek(0); // explicitly rewind the stream
$contents = $response->getBody()->getContents();
$this->assertGreaterThan(0, strlen($contents));
}
I see now it's my misunderstanding. getContents()
only reads the remainder of te stream, you have to cast it to string to read the all the data of the stream.
This does work:
public function testGuzzleBundle()
{
$client = $this->container->get('guzzle.client.test');
$response = $client->get($this::SERVICE_URI);
$contents = (string) $response->getBody();
$this->assertGreaterThan(0, strlen($contents));
}
Sorry for that. StreamInterface
doesn't have the most clear definition.
No problem :+1:
I noticed that the LogMiddleware doesn't rewind the stream after logging, so you have to do a
seek(0)
on the stream before you can read the body.I guess this is done intentionally but I couldn't find any documentation on whether Guzzle handlers should handle resetting the stream after reading the body.