Skip to content

Commit eb7b39b

Browse files
committed
polish PestHttpRecorder::class
- remove adding query to file-name - instead add short hash of query to file-name - or (if given) allow user to set a specific name for upcoming query - additionally save header, method and payload within the snapshot
1 parent 2b11b70 commit eb7b39b

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

src/Macros/PestHttpRecorder.php

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55
use GuzzleHttp\Client;
66
use Illuminate\Http\Client\Request;
7+
use Illuminate\Support\Arr;
78
use Illuminate\Support\Facades\File;
9+
use Illuminate\Support\Facades\Hash;
810
use Illuminate\Support\Facades\Http;
911
use Illuminate\Support\Str;
1012

@@ -37,6 +39,9 @@ class HttpRecorder
3739

3840
private $usePrettyJson = true;
3941

42+
private $requestNames = [];
43+
44+
4045
public function storeIn($directory)
4146
{
4247
$this->snapshotDirectory = $directory;
@@ -51,22 +56,33 @@ public function minifyJson()
5156
return $this;
5257
}
5358

59+
public function nameForNextRequest($name)
60+
{
61+
array_push($this->requestNames, $name);
62+
}
63+
5464
public function handle(Request $request)
5565
{
5666
$forceRecording = in_array('--force-recording', $_SERVER['argv']);
5767

5868
$urlInfo = parse_url($request->url());
69+
$payload = null;
5970

6071
// create specific filename for storing snapshots
72+
$header = $request->headers();
6173
$method = Str::lower($request->method());
6274
$name = Str::slug(Str::replace('/', '-', $urlInfo['path']));
63-
$query = Str::slug(Str::replace('&', '_', Str::replace('=', '-', $urlInfo['query'])));
75+
$payload = ($method === 'get') ? $urlInfo['query'] : $request->body();
76+
$queryName = array_pop($this->requestNames) ?? hash('adler32', $payload);
6477

65-
$fileName = "{$method}_{$name}_{$query}.json";
78+
$fileName = "{$method}_{$name}_{$queryName}.json";
6679
$directoryPath = "tests/{$this->snapshotDirectory}";
6780
$filePath = "{$directoryPath}/{$fileName}";
6881

69-
if ($forceRecording || ! File::exists($filePath)) {
82+
// filter out Notion API Token Header
83+
$header = Arr::except($header, ['Authorization']);
84+
85+
if ($forceRecording || !File::exists($filePath)) {
7086
File::makeDirectory($directoryPath, 0744, true, true);
7187

7288
$client = new Client();
@@ -77,7 +93,10 @@ public function handle(Request $request)
7793
]);
7894

7995
$recordedResponse = [
96+
'header' => $header,
97+
'method' => $method,
8098
'status' => $response->getStatusCode(),
99+
'payload' => ($method === 'get') ? $payload : json_decode($payload, true),
81100
'data' => json_decode($response->getBody()->getContents(), true),
82101
];
83102

0 commit comments

Comments
 (0)