Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Call on_stats handler in Http stub callbacks #37738

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions src/Illuminate/Http/Client/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
namespace Illuminate\Http\Client;

use Closure;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Response as Psr7Response;
use GuzzleHttp\TransferStats;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
Expand Down Expand Up @@ -162,11 +164,20 @@ public function fake($callback = null)
}

$this->stubCallbacks = $this->stubCallbacks->merge(collect([
$callback instanceof Closure
? $callback
: function () use ($callback) {
return $callback;
},
function ($request, $options) use ($callback) {
$response = $callback instanceof Closure
? $callback($request, $options)
: $callback;

if ($response instanceof PromiseInterface) {
$options['on_stats'](new TransferStats(
$request->toPsrRequest(),
$response->wait(),
));
}

return $response;
},
]));

return $this;
Expand Down
10 changes: 9 additions & 1 deletion tests/Http/HttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -942,7 +942,7 @@ public function testTheRequestSendingAndResponseReceivedEventsAreFiredWhenAReque

public function testTheTransferStatsAreCalledSafelyWhenFakingTheRequest()
{
$this->factory->fake(['https://example.com' => $this->factory->response()]);
$this->factory->fake(['https://example.com' => ['world' => 'Hello world']]);
$stats = $this->factory->get('https://example.com')->handlerStats();
$effectiveUri = $this->factory->get('https://example.com')->effectiveUri();

Expand All @@ -952,6 +952,14 @@ public function testTheTransferStatsAreCalledSafelyWhenFakingTheRequest()
$this->assertNull($effectiveUri);
}

public function testTransferStatsArePresentWhenFakingTheRequestUsingAPromiseResponse()
{
$this->factory->fake(['https://example.com' => $this->factory->response()]);
$effectiveUri = $this->factory->get('https://example.com')->effectiveUri();

$this->assertSame('https://example.com', (string) $effectiveUri);
}

public function testClonedClientsWorkSuccessfullyWithTheRequestObject()
{
$events = m::mock(Dispatcher::class);
Expand Down