-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRealmRecordsPersistenceTests.cs
261 lines (216 loc) · 9.37 KB
/
RealmRecordsPersistenceTests.cs
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#if DEBUG
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using TitanShark.Thresher.Core;
using Xunit;
using Xunit.Abstractions;
namespace TitanShark.Thresher.Realm.Tests
{
public class RealmRecordsPersistenceTests
{
private const string AcceptJson = "application/json";
private const string BasicAuthScheme = "Basic";
private const string BasicAuthValue = "cm9vdDpyb290";
private readonly ITestOutputHelper _output;
private volatile int _successCounter;
private readonly object _lock = new object();
public RealmRecordsPersistenceTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public async Task Record_Replay_With_Default_Settings()
{
// prepares
var stats = new Dictionary<HttpStatusCode, int>
{
[HttpStatusCode.OK] = 0,
[HttpStatusCode.NotAcceptable] = 0,
[HttpStatusCode.Unauthorized] = 0,
[HttpStatusCode.BadRequest] = 0,
[HttpStatusCode.NotFound] = 0
};
var transmitter = new Transmitter
(
(callId, request, cancellationToken) =>
{
_output.WriteLine($"Request to '{request.RequestUri}' was sent out.");
var response = Mock.Build(request);
stats[response.StatusCode] += 1;
return Task.FromResult(response);
}
);
// acts
// ... recording
RealmRecordsPersistence persistence = CreateRealmPersistence();
var recorder = new Recorder(persistence);
var handler = new InterceptableHttpClientHandler(
transmitter: transmitter,
interceptorsRunner: new SequentialInterceptorsRunner(recorder));
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(AcceptJson));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(BasicAuthScheme, BasicAuthValue);
var started = DateTime.UtcNow;
await client.GetAsync("https://testing.only/Successful").ConfigureAwait(false);
await client.GetAsync("https://testing.only/Failed").ConfigureAwait(false);
await client.GetAsync("https://testing.only/NotFound").ConfigureAwait(false);
var ended = DateTime.UtcNow;
await Task.Delay(TimeSpan.FromMilliseconds(100));
await client.GetAsync("https://testing.only/Failed").ConfigureAwait(false);
// asserts
stats[HttpStatusCode.OK].Should().Be(1);
stats[HttpStatusCode.NotAcceptable].Should().Be(0);
stats[HttpStatusCode.Unauthorized].Should().Be(0);
stats[HttpStatusCode.BadRequest].Should().Be(2);
stats[HttpStatusCode.NotFound].Should().Be(1);
// cleans up
stats[HttpStatusCode.OK] = 0;
stats[HttpStatusCode.NotAcceptable] = 0;
stats[HttpStatusCode.Unauthorized] = 0;
stats[HttpStatusCode.BadRequest] = 0;
stats[HttpStatusCode.NotFound] = 0;
client.Dispose();
// acts
// ... snapshots
// ... gets only logic-failed requests
var snapshot = await persistence.Snapshot(
started, ended,
new[] { HttpStatusCode.BadRequest, HttpStatusCode.NotFound });
// ... re-creates a fresh instance of HttpClient, without recorder.
handler = new InterceptableHttpClientHandler(transmitter: transmitter);
client = new HttpClient(handler);
// ... replays
var replayer = new Replayer(new SequentialReplayingStrategy(), client, snapshot);
await replayer.Start();
replayer.Stop();
// cleans up
client.Dispose();
// asserts
stats[HttpStatusCode.OK].Should().Be(0);
stats[HttpStatusCode.BadRequest].Should().Be(1);
stats[HttpStatusCode.NotFound].Should().Be(1);
}
[Fact]
public async Task Record_Replay_Long_Running_In_Parallel()
{
// prepares
const int total = 1000;
_successCounter = 0;
var transmitter = new Transmitter
(
(callId, request, cancellationToken) =>
{
var response = Mock.Build(request);
if (response.IsSuccessStatusCode)
{
lock (_lock)
{
_successCounter++;
}
}
return Task.FromResult(response);
}
);
// acts
// ... recording
RealmRecordsPersistence persistence = CreateRealmPersistence();
var recorder = new Recorder(persistence);
var handler = new InterceptableHttpClientHandler(
transmitter: transmitter,
interceptorsRunner: new SequentialInterceptorsRunner(recorder));
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(AcceptJson));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(BasicAuthScheme, BasicAuthValue);
var started = DateTime.UtcNow;
await Task.WhenAll(Enumerable
.Range(1, total)
.Select(num => Task.Run(async () =>
{
await client.GetAsync("https://testing.only/Successful").ConfigureAwait(false);
})));
var ended = DateTime.UtcNow;
// asserts
_successCounter.Should().Be(total);
// cleans up
_successCounter = 0;
client.Dispose();
// acts
// ... snapshots
var snapshot = await persistence.Snapshot(started, ended);
snapshot.TotalRecords.Should().Be(total);
// ... re-creates a fresh instance of HttpClient, without recorder.
handler = new InterceptableHttpClientHandler(transmitter: transmitter);
client = new HttpClient(handler);
// ... replays
var replayer = new Replayer(
new SequentialReplayingStrategy
{
BatchSize = 11 // for checking the Algorithm of Batching!
},
client,
snapshot);
await replayer.Start();
replayer.Stop();
// asserts
_successCounter.Should().Be(total);
// cleans up
client.Dispose();
}
private static RealmRecordsPersistence CreateRealmPersistence()
{
var location = Assembly.GetExecutingAssembly().Location;
var persistence = new RealmRecordsPersistence(Path.Combine(Path.GetDirectoryName(location), "records.realm"));
return persistence;
}
private class Mock
{
public const string Ok = "Okay!";
public const string Unauthorized = "No auth!";
public const string NotAcceptable = "No auth!";
public const string BadRequest = "Bad request!";
public const string NotFound = "Not found!";
public static HttpResponseMessage Build(HttpRequestMessage request)
{
if (!request.Headers.Accept.Any(accept => string.Equals(accept.MediaType, AcceptJson, StringComparison.InvariantCultureIgnoreCase)))
{
return new HttpResponseMessage(HttpStatusCode.NotAcceptable)
{
Content = new StringContent(NotAcceptable)
};
}
if (!string.Equals(request.Headers.Authorization.ToString(), $"{BasicAuthScheme} {BasicAuthValue}", StringComparison.InvariantCultureIgnoreCase))
{
return new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent(Unauthorized)
};
}
return BuildInternal(request);
}
private static HttpResponseMessage BuildInternal(HttpRequestMessage request) => request.RequestUri.PathAndQuery switch
{
"/Successful" => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(Ok)
},
"/Failed" => new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(BadRequest)
},
_ => new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(NotFound)
}
};
}
}
}
#endif