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

feat(testing): accept type-hinted requests as assertSent parameters #424

Open
wants to merge 2 commits into
base: v3
Choose a base branch
from
Open
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
15 changes: 15 additions & 0 deletions phpstan.baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,18 @@ parameters:
message: "#^Match arm is unreachable because previous comparison is always true.$#"
count: 1
path: src/Http/Pool.php

-
message: "#^Method Saloon\\\\Http\\\\Faking\\\\MockClient\\:\\:getRequestClass\\(\\) should return class-string|null but returns class-string<Saloon\\\\Http\\\\Request>|Saloon\\\\Http\\\\Request$#"
count: 1
path: src/Http/Faking/MockClient.php

-
message: "#^Call to an undefined method ReflectionType\\:\\:getName\\(\\)\\.$#"
count: 1
path: src/Http/Faking/MockClient.php

-
message: "#^Parameter \\#1 \\$function of class ReflectionFunction constructor expects Closure|string, callable\\(\\)\\: mixed given\\.$#"
count: 1
path: src/Http/Faking/MockClient.php
Comment on lines +57 to +71
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
-
message: "#^Method Saloon\\\\Http\\\\Faking\\\\MockClient\\:\\:getRequestClass\\(\\) should return class-string|null but returns class-string<Saloon\\\\Http\\\\Request>|Saloon\\\\Http\\\\Request$#"
count: 1
path: src/Http/Faking/MockClient.php
-
message: "#^Call to an undefined method ReflectionType\\:\\:getName\\(\\)\\.$#"
count: 1
path: src/Http/Faking/MockClient.php
-
message: "#^Parameter \\#1 \\$function of class ReflectionFunction constructor expects Closure|string, callable\\(\\)\\: mixed given\\.$#"
count: 1
path: src/Http/Faking/MockClient.php

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without them, phpstan doesn't pass:

CleanShot 2024-08-05 at 02 14 13

I believe they are false-positive.

40 changes: 38 additions & 2 deletions src/Http/Faking/MockClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -451,14 +451,29 @@ private function checkClosureAgainstResponses(callable $closure, ?int $index = n
return false;
}

if(! is_null($index)) {
if (! is_null($index)) {
$response = $this->getRecordedResponses()[$index];
$request = $response->getPendingRequest()->getRequest();

return $closure($request, $response);
}

// Let's first check if the latest response resolves the callable
// Let's first check if the callable type-hints the latest request class.
// If so, we try to find the corresponding request in the recorded responses
// and call the callable accordingly. We will only fail if it returns `false`.

if ($fqcn = $this->getRequestClass($closure)) {
/** @var Response */
foreach ($this->getRecordedResponses() as $response) {
if (get_class($request = $response->getPendingRequest()->getRequest()) !== $fqcn) {
continue;
}

return $closure($request, $response) !== false;
}
}

// Let's then check if the latest response resolves the callable
// with a successful result.

$lastResponse = $this->getLastResponse();
Expand Down Expand Up @@ -524,4 +539,25 @@ private function getRequestSentCount(): array

return array_count_values($requests);
}

/**
* Get the FQCN of the request class if type-hinted.
*
* @return class-string
*/
private function getRequestClass(callable $closure): ?string
{
$reflection = new \ReflectionFunction($closure);
$parameters = $reflection->getParameters();

if (! ($fqcn = $parameters[0]->getType()?->getName())) {
return null;
}

if (! is_a($fqcn, Request::class, allow_string: true)) {
return null;
}

return $fqcn;
}
}
35 changes: 35 additions & 0 deletions tests/Unit/MockClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

declare(strict_types=1);

use Pest\Expectation;
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Saloon\Tests\Fixtures\Requests\UserRequest;
use Saloon\Tests\Fixtures\Requests\ErrorRequest;
use PHPUnit\Framework\ExpectationFailedException;
use Saloon\Exceptions\NoMockResponseFoundException;
use Saloon\Tests\Fixtures\Connectors\TestConnector;
use Saloon\Tests\Fixtures\Exceptions\TestResponseException;
Expand Down Expand Up @@ -261,3 +263,36 @@
$response = connector()->send(new UserRequest, $mockClient);
$response->throw();
});

test('`assertSent` accepts the request class as a type-hint', function () {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam']),
]);

$request = new UserRequest;
$request->headers()->add('X-Foo', 'bar');

connector()->send($request, $mockClient);

$mockClient->assertSent(function (UserRequest $request) {
expect($request->headers()->all())->toMatchArray([
'X-Foo' => 'bar',
]);
});
});

test('`assertSent` fails or succeeds depending on the closure result when the closure is type-hinted', function (mixed $returns, bool $shouldThrow) {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam']),
]);

connector()->send(new UserRequest, $mockClient);

expect(fn () => $mockClient->assertSent(fn (UserRequest $request) => $returns))
->when($shouldThrow, fn (Expectation $e) => $e->toThrow(ExpectationFailedException::class))
->when(! $shouldThrow, fn (Expectation $e) => $e->not->toThrow(ExpectationFailedException::class));
})->with([
[false, true],
[true, false],
[null, false],
]);