Skip to content

Commit

Permalink
Adds Hyperf\HttpServer\Request::fake() (#724)
Browse files Browse the repository at this point in the history
Co-authored-by: Deeka Wong <[email protected]>
  • Loading branch information
huangdijia and huangdijia authored Oct 16, 2024
1 parent 8fe1a74 commit 1e539fb
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

namespace Hyperf\HttpServer\Contract;

use Closure;
use Psr\Http\Message\ServerRequestInterface;

interface RequestInterface
{
/**
Expand Down Expand Up @@ -52,6 +55,11 @@ public function date(string $key, ?string $format = null, ?string $tz = null): ?
*/
public function except($keys): array;

/**
* @param Closure(ServerRequestInterface):ServerRequestInterface|null $closure
*/
public static function fake(?Closure $closure = null): ServerRequestInterface;

/**
* Determine if the request contains a non-empty value for an input item.
*/
Expand Down
7 changes: 7 additions & 0 deletions src/macros/src/RequestMixin.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
use Carbon\Carbon;
use Hyperf\Collection\Arr;
use Hyperf\Context\Context;
use Hyperf\HttpMessage\Server\Request as ServerRequest;
use Hyperf\HttpServer\Request;
use Hyperf\Stringable\Str;
use stdClass;

use function Hyperf\Collection\collect;
use function Hyperf\Collection\data_get;
use function Hyperf\Support\with;

/**
* @property array $contextkeys
Expand Down Expand Up @@ -115,6 +117,11 @@ public function exists()
return fn ($key) => $this->has($key);
}

public function fake()
{
return fn ($closure = null) => with(new ServerRequest('GET', '/'), $closure);
}

public function filled()
{
return function ($key) {
Expand Down
19 changes: 19 additions & 0 deletions tests/Macros/HttpServerRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* @contact [email protected]
*/
use Hyperf\Context\Context;
use Hyperf\HttpMessage\Uri\Uri;
use Hyperf\HttpServer\Request;
use Mockery as m;
use Psr\Http\Message\ServerRequestInterface;
Expand Down Expand Up @@ -149,3 +150,21 @@

expect($request->wantsJson())->toBeFalse();
});

test('test fake', function () {
$psrRequest = Request::fake();
expect($psrRequest)->toBeInstanceOf(ServerRequestInterface::class);

$psrRequest = Request::fake(function ($request) {
return $request->withMethod('POST')->withUri(new Uri('/foo'));
});

expect($psrRequest->getMethod())->toBe('POST');
expect($psrRequest->getUri()->getPath())->toBe('/foo');

Context::set(ServerRequestInterface::class, $psrRequest);

$request = new Request();
expect($request->getMethod())->toBe('POST');
expect($request->getUri()->getPath())->toBe('/foo');
});

0 comments on commit 1e539fb

Please sign in to comment.