-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCassetteHandler.cs
More file actions
168 lines (144 loc) · 5.35 KB
/
CassetteHandler.cs
File metadata and controls
168 lines (144 loc) · 5.35 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
using System.Net;
using System.Net.Http.Headers;
using System.Text.Json;
namespace FlowableExternalWorkerClient.Tests;
/// <summary>
/// A DelegatingHandler that records HTTP interactions to a JSON cassette file
/// and replays them in order on subsequent runs.
///
/// Mode: Auto - if cassette file exists, replays; otherwise records.
/// Replay is sequential (ordered), not matching-based, to correctly handle
/// repeated calls to the same endpoint with different responses.
/// </summary>
public class CassetteHandler : DelegatingHandler
{
private readonly string _cassettePath;
private readonly List<RecordedInteraction> _interactions;
private int _replayIndex;
private readonly bool _isReplaying;
public CassetteHandler(string cassettePath)
: base(new HttpClientHandler())
{
_cassettePath = cassettePath;
if (File.Exists(cassettePath))
{
var json = File.ReadAllText(cassettePath);
_interactions = JsonSerializer.Deserialize<List<RecordedInteraction>>(json,
new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) ?? new();
_isReplaying = true;
}
else
{
_interactions = new();
_isReplaying = false;
}
}
public bool IsReplaying => _isReplaying;
public HttpClient CreateHttpClient()
{
return new HttpClient(this, disposeHandler: false);
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (_isReplaying)
{
return Replay(request);
}
return await Record(request, cancellationToken);
}
private HttpResponseMessage Replay(HttpRequestMessage request)
{
int index;
lock (_interactions)
{
index = _replayIndex++;
}
if (index >= _interactions.Count)
{
throw new InvalidOperationException(
$"Cassette '{Path.GetFileName(_cassettePath)}' has no more recorded interactions " +
$"(tried index {index}, total {_interactions.Count}). " +
$"Delete the cassette file to re-record.");
}
return _interactions[index].ToHttpResponseMessage();
}
private async Task<HttpResponseMessage> Record(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
// Buffer the response body so both recording and caller can use it
var bodyBytes = response.Content != null
? await response.Content.ReadAsByteArrayAsync(cancellationToken)
: Array.Empty<byte>();
var interaction = new RecordedInteraction
{
Method = request.Method.Method,
Uri = request.RequestUri?.ToString() ?? "",
StatusCode = (int)response.StatusCode,
ResponseBody = Convert.ToBase64String(bodyBytes),
ResponseContentType = response.Content?.Headers.ContentType?.ToString()
};
foreach (var header in response.Headers)
{
interaction.ResponseHeaders[header.Key] = header.Value.ToArray();
}
lock (_interactions)
{
_interactions.Add(interaction);
}
// Return a new response with buffered body so the caller can read it
var newResponse = new HttpResponseMessage(response.StatusCode);
newResponse.Content = new ByteArrayContent(bodyBytes);
if (response.Content?.Headers.ContentType != null)
{
newResponse.Content.Headers.ContentType = response.Content.Headers.ContentType;
}
foreach (var header in response.Headers)
{
newResponse.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
newResponse.RequestMessage = request;
return newResponse;
}
public void Save()
{
if (!_isReplaying)
{
Directory.CreateDirectory(Path.GetDirectoryName(_cassettePath)!);
var json = JsonSerializer.Serialize(_interactions, new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
File.WriteAllText(_cassettePath, json);
}
}
}
public class RecordedInteraction
{
public string Method { get; set; } = "";
public string Uri { get; set; } = "";
public int StatusCode { get; set; }
public string? ResponseBody { get; set; }
public string? ResponseContentType { get; set; }
public Dictionary<string, string[]> ResponseHeaders { get; set; } = new();
public HttpResponseMessage ToHttpResponseMessage()
{
var response = new HttpResponseMessage((HttpStatusCode)StatusCode);
if (ResponseBody != null)
{
var bytes = Convert.FromBase64String(ResponseBody);
response.Content = new ByteArrayContent(bytes);
if (ResponseContentType != null)
{
response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ResponseContentType);
}
}
foreach (var header in ResponseHeaders)
{
response.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return response;
}
}