-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFakeHttpClient.php
More file actions
80 lines (63 loc) · 1.91 KB
/
Copy pathFakeHttpClient.php
File metadata and controls
80 lines (63 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
declare(strict_types=1);
namespace TestingBot\Tests\Support;
use TestingBot\Http\HttpClientInterface;
use TestingBot\Http\Request;
use TestingBot\Http\Response;
/**
* Test double for {@see HttpClientInterface}: records every request it receives
* and replays queued canned responses (falling back to a default 200). It can
* also be told to simulate a transport failure.
*/
final class FakeHttpClient implements HttpClientInterface
{
/** @var list<Request> */
public array $requests = [];
/** @var list<Response> */
private array $responses = [];
private ?\Throwable $throwable = null;
public function __construct(private Response $default = new Response(200, '{}'))
{
}
/**
* Queue a canned response (FIFO). Returns $this for chaining.
*/
public function queue(Response $response): self
{
$this->responses[] = $response;
return $this;
}
/**
* @param array<string, string> $headers
*/
public function queueJson(int $status, mixed $body, array $headers = []): self
{
return $this->queue(new Response($status, (string) json_encode($body), $headers));
}
/**
* Make the next send() throw, to simulate a transport-level failure.
*/
public function failWith(\Throwable $throwable): self
{
$this->throwable = $throwable;
return $this;
}
public function send(Request $request): Response
{
$this->requests[] = $request;
if ($this->throwable !== null) {
$throwable = $this->throwable;
$this->throwable = null;
throw $throwable;
}
return array_shift($this->responses) ?? $this->default;
}
public function lastRequest(): Request
{
$last = end($this->requests);
if ($last === false) {
throw new \LogicException('No request was recorded.');
}
return $last;
}
}