I am using Guzzle to do the following request:
// Client.php
public function request($verb, $url)
{
$stack = HandlerStack::create($handler);
$client = new GuzzleClient(['handler' => $stack]);
$info = '';
$response = $client->request($verb, $url, [
'curl' => blah,
'cookies' => blah,
'headers' => blah,
'on_stats' => function (TransferStats $stats) use (&$info) {
$info = $stats->getHandlerStats();
}
]);
// build custom response with $info and return it
}
and in the test I have:
// ClientTest.php
public function testSomeStuffInHandlerStats()
{
$handler = new MockHandler([new Response(200)]);
$client = new Client($handler);
$response = $client->request('GET', 'http://example.com');
$expectedResponse = ['foo' => 'bar']
$this->assertEquals($expectedResponse, $response);
}
If I do the request in real life, CurlHandler()
is passed as the $handler
, and $stats->getHandlerStats()
returns something similar to this, from the invokeStats()
method in CurlFactory.php
, which is used to build the custom response:
[
"url" => "https://example.com",
"content_type" => "text/html; charset=UTF-8",
"http_code" => 200,
"header_size" => 3225,
"request_size" => 777,
"filetime" => -1,
"ssl_verify_result" => 0,
"redirect_count" => 3,
"total_time" => 0.929452,
"namelookup_time" => 0.092699,
"connect_time" => 0.249524,
"pretransfer_time" => 0.5648,
"size_upload" => 0.0,
"size_download" => 0.0,
"speed_download" => 0.0,
"speed_upload" => 0.0,
"download_content_length" => -1.0,
"upload_content_length" => -1.0,
"starttransfer_time" => 0.925437,
"redirect_time" => 0.708288,
"redirect_url" => "",
"primary_ip" => "primary IP",
"certinfo" => [],
"primary_port" => 443,
"local_ip" => "local IP",
"local_port" => 39164,
]
However, in test mode, getHandlerStats()
always returns an empty array, because the invokeStats()
method in the MockHandler
is called instead, and these stats are not passed to the constructor of TransferStats
, in which case, the default value (an empty array) is set:
// MockHandler.php
private function invokeStats(
RequestInterface $request,
array $options,
ResponseInterface $response = null,
$reason = null
) {
if (isset($options['on_stats'])) {
$stats = new TransferStats($request, $response, 0, $reason); // no handlerStats passed
call_user_func($options['on_stats'], $stats);
}
}
Is it intentional that no $handlerStats
argument is passed to the constructor of TransferStats
in the invokeStats
method of the MockHandler
class?
Is there a way to pass these stats to $info
from the test? I tried creating the test instance of MockHandler with an $onFulfilled
callback, but $info
can't be reached from there anyway.
question from:
https://stackoverflow.com/questions/66068429/how-to-test-whats-returned-by-transferstats-gethandlerstats