-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathResilienceTelemetryDiagnosticSourceTests.cs
More file actions
381 lines (319 loc) · 14.2 KB
/
ResilienceTelemetryDiagnosticSourceTests.cs
File metadata and controls
381 lines (319 loc) · 14.2 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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
using System.Net.Http;
using Microsoft.Extensions.Logging;
using Polly.Extensions.Telemetry;
using Polly.Telemetry;
namespace Polly.Extensions.Tests.Telemetry;
#pragma warning disable S103 // Lines should not be too long
[Collection("NonParallelizableTests")]
public class ResilienceTelemetryDiagnosticSourceTests : IDisposable
{
private readonly FakeLogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly List<MeteringEvent> _events = new();
private readonly IDisposable _metering;
private Action<TelemetryEventArguments>? _onEvent;
public ResilienceTelemetryDiagnosticSourceTests()
{
_metering = TestUtilities.EnablePollyMetering(_events);
_loggerFactory = TestUtilities.CreateLoggerFactory(out _logger);
}
public void Dispose()
{
_metering.Dispose();
_loggerFactory.Dispose();
}
[Fact]
public void Meter_Ok()
{
ResilienceTelemetryDiagnosticSource.Meter.Name.Should().Be("Polly");
ResilienceTelemetryDiagnosticSource.Meter.Version.Should().Be("1.0");
var source = new ResilienceTelemetryDiagnosticSource(new TelemetryOptions());
source.Counter.Description.Should().Be("Tracks the number of resilience events that occurred in resilience strategies.");
source.AttemptDuration.Description.Should().Be("Tracks the duration of execution attempts.");
source.AttemptDuration.Unit.Should().Be("ms");
}
[Fact]
public void IsEnabled_true()
{
var source = Create();
source.IsEnabled("dummy").Should().BeTrue();
}
[Fact]
public void Write_InvalidType_Nothing()
{
var source = Create();
source.Write("dummy", new object());
_logger.GetRecords().Should().BeEmpty();
}
[InlineData(true)]
[InlineData(false)]
[Theory]
public void WriteEvent_LoggingWithOutcome_Ok(bool noOutcome)
{
var telemetry = Create();
using var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
ReportEvent(telemetry, noOutcome ? null : Outcome.FromResult<object>(response));
var messages = _logger.GetRecords(new EventId(0, "ResilienceEvent")).ToList();
messages.Should().HaveCount(1);
if (noOutcome)
{
messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Operation Key: 'op-key', Result: ''");
}
else
{
messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Operation Key: 'op-key', Result: '200'");
}
}
[InlineData(true)]
[InlineData(false)]
[Theory]
public void WriteEvent_LoggingWithException_Ok(bool noOutcome)
{
var telemetry = Create();
ReportEvent(telemetry, noOutcome ? null : Outcome.FromException<object>(new InvalidOperationException("Dummy message.")));
var messages = _logger.GetRecords(new EventId(0, "ResilienceEvent")).ToList();
messages.Should().HaveCount(1);
if (!noOutcome)
{
messages[0].Exception.Should().NotBeNull();
}
if (noOutcome)
{
messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Operation Key: 'op-key', Result: ''");
}
else
{
messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Operation Key: 'op-key', Result: 'Dummy message.'");
}
}
[Fact]
public void WriteEvent_LoggingWithoutStrategyKey_Ok()
{
var telemetry = Create();
ReportEvent(telemetry, null, strategyKey: null);
var messages = _logger.GetRecords(new EventId(0, "ResilienceEvent")).ToList();
messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: '', Operation Key: 'op-key', Result: ''");
}
[InlineData(ResilienceEventSeverity.Error, LogLevel.Error)]
[InlineData(ResilienceEventSeverity.Warning, LogLevel.Warning)]
[InlineData(ResilienceEventSeverity.Information, LogLevel.Information)]
[InlineData(ResilienceEventSeverity.Debug, LogLevel.Debug)]
[InlineData(ResilienceEventSeverity.Critical, LogLevel.Critical)]
[InlineData(ResilienceEventSeverity.None, LogLevel.None)]
[InlineData((ResilienceEventSeverity)99, LogLevel.None)]
[Theory]
public void WriteEvent_EnsureSeverityRespected(ResilienceEventSeverity severity, LogLevel logLevel)
{
var telemetry = Create();
ReportEvent(telemetry, null, severity: severity);
var messages = _logger.GetRecords(new EventId(0, "ResilienceEvent")).ToList();
messages[0].LogLevel.Should().Be(logLevel);
var events = GetEvents("resilience-events");
events.Should().HaveCount(1);
var ev = events[0]["event-severity"].Should().Be(severity.ToString());
}
[Fact]
public void WriteExecutionAttempt_LoggingWithException_Ok()
{
var telemetry = Create();
using var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
ReportEvent(telemetry, Outcome.FromException<object>(new InvalidOperationException("Dummy message.")), arg: new ExecutionAttemptArguments(4, TimeSpan.FromMilliseconds(123), true));
var messages = _logger.GetRecords(new EventId(3, "ExecutionAttempt")).ToList();
messages.Should().HaveCount(1);
messages[0].Message.Should().Be("Execution attempt. Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Operation Key: 'op-key', Result: 'Dummy message.', Handled: 'True', Attempt: '4', Execution Time: '123'");
}
[InlineData(true, true)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(false, false)]
[Theory]
public void WriteExecutionAttempt_LoggingWithOutcome_Ok(bool noOutcome, bool handled)
{
var telemetry = Create();
using var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
ReportEvent(telemetry, noOutcome ? null : Outcome.FromResult<object>(response), arg: new ExecutionAttemptArguments(4, TimeSpan.FromMilliseconds(123), handled));
var messages = _logger.GetRecords(new EventId(3, "ExecutionAttempt")).ToList();
messages.Should().HaveCount(1);
if (noOutcome)
{
string resultString = string.Empty;
messages[0].Message.Should().Be($"Execution attempt. Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Operation Key: 'op-key', Result: '{resultString}', Handled: '{handled}', Attempt: '4', Execution Time: '123'");
}
else
{
messages[0].Message.Should().Be($"Execution attempt. Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Operation Key: 'op-key', Result: '200', Handled: '{handled}', Attempt: '4', Execution Time: '123'");
}
messages[0].LogLevel.Should().Be(LogLevel.Warning);
}
[Fact]
public void WriteExecutionAttempt_NotEnabled_EnsureNotLogged()
{
var telemetry = Create();
_logger.Enabled = false;
ReportEvent(telemetry, null, arg: new ExecutionAttemptArguments(4, TimeSpan.FromMilliseconds(123), true));
var messages = _logger.GetRecords(new EventId(3, "ExecutionAttempt")).ToList();
messages.Should().HaveCount(0);
}
[InlineData(true, false)]
[InlineData(false, false)]
[InlineData(true, true)]
[InlineData(false, true)]
[Theory]
public void WriteEvent_MeteringWithoutEnrichers_Ok(bool noOutcome, bool exception)
{
var telemetry = Create();
Outcome<object>? outcome = noOutcome switch
{
false => null,
true when exception => Outcome.FromException<object>(new InvalidOperationException("Dummy message.")),
_ => Outcome.FromResult<object>(true)
};
ReportEvent(telemetry, outcome, context: ResilienceContext.Get("op-key").WithResultType<bool>());
var events = GetEvents("resilience-events");
events.Should().HaveCount(1);
var ev = events[0];
ev.Count.Should().Be(9);
ev["event-name"].Should().Be("my-event");
ev["event-severity"].Should().Be("Warning");
ev["strategy-type"].Should().Be("my-strategy-type");
ev["strategy-name"].Should().Be("my-strategy");
ev["strategy-key"].Should().Be("my-strategy-key");
ev["operation-key"].Should().Be("op-key");
ev["builder-name"].Should().Be("my-builder");
ev["result-type"].Should().Be("Boolean");
if (outcome?.Exception is not null)
{
ev["exception-name"].Should().Be("System.InvalidOperationException");
}
else
{
ev["exception-name"].Should().Be(null);
}
}
[InlineData(true, false)]
[InlineData(false, false)]
[InlineData(true, true)]
[InlineData(false, true)]
[Theory]
public void WriteExecutionAttemptEvent_Metering_Ok(bool noOutcome, bool exception)
{
var telemetry = Create();
var attemptArg = new ExecutionAttemptArguments(5, TimeSpan.FromSeconds(50), true);
Outcome<object>? outcome = noOutcome switch
{
false => null,
true when exception => Outcome.FromException<object>(new InvalidOperationException("Dummy message.")),
_ => Outcome.FromResult<object>(true)
};
ReportEvent(telemetry, outcome, context: ResilienceContext.Get("op-key").WithResultType<bool>(), arg: attemptArg);
var events = GetEvents("execution-attempt-duration");
events.Should().HaveCount(1);
var ev = events[0];
ev.Count.Should().Be(11);
ev["event-name"].Should().Be("my-event");
ev["event-severity"].Should().Be("Warning");
ev["strategy-type"].Should().Be("my-strategy-type");
ev["strategy-name"].Should().Be("my-strategy");
ev["strategy-key"].Should().Be("my-strategy-key");
ev["operation-key"].Should().Be("op-key");
ev["builder-name"].Should().Be("my-builder");
ev["result-type"].Should().Be("Boolean");
ev["attempt-number"].Should().Be(5);
ev["attempt-handled"].Should().Be(true);
if (outcome?.Exception is not null)
{
ev["exception-name"].Should().Be("System.InvalidOperationException");
}
else
{
ev["exception-name"].Should().Be(null);
}
_events.Single(v => v.Name == "execution-attempt-duration").Measurement.Should().Be(50000);
}
[InlineData(1)]
[InlineData(100)]
[Theory]
public void WriteEvent_MeteringWithEnrichers_Ok(int count)
{
const int DefaultDimensions = 8;
var telemetry = Create(enrichers =>
{
enrichers.Add(context =>
{
for (int i = 0; i < count; i++)
{
context.Tags.Add(new KeyValuePair<string, object?>($"custom-{i}", $"custom-{i}-value"));
}
});
enrichers.Add(context =>
{
context.Tags.Add(new KeyValuePair<string, object?>("other", "other-value"));
});
});
ReportEvent(telemetry, Outcome.FromResult<object>(true));
var events = GetEvents("resilience-events");
var ev = events[0];
ev.Count.Should().Be(DefaultDimensions + count + 2);
ev["other"].Should().Be("other-value");
for (int i = 0; i < count; i++)
{
ev[$"custom-{i}"].Should().Be($"custom-{i}-value");
}
}
[Fact]
public void WriteEvent_MeteringWithoutStrategyKey_Ok()
{
var telemetry = Create();
ReportEvent(telemetry, null, strategyKey: null);
var events = GetEvents("resilience-events")[0]["strategy-key"].Should().BeNull();
}
[InlineData(true)]
[InlineData(false)]
[Theory]
public void OnTelemetryEvent_Ok(bool hasCallback)
{
var called = false;
if (hasCallback)
{
_onEvent = e => called = true;
}
var telemetry = Create();
ReportEvent(telemetry, null, strategyKey: null);
called.Should().Be(hasCallback);
}
private List<Dictionary<string, object?>> GetEvents(string eventName) => _events.Where(e => e.Name == eventName).Select(v => v.Tags).ToList();
private ResilienceTelemetryDiagnosticSource Create(Action<ICollection<Action<EnrichmentContext>>>? configureEnrichers = null)
{
var options = new TelemetryOptions
{
LoggerFactory = _loggerFactory,
OnTelemetryEvent = _onEvent
};
configureEnrichers?.Invoke(options.Enrichers);
return new(options);
}
private static void ReportEvent(
ResilienceTelemetryDiagnosticSource telemetry,
Outcome<object>? outcome,
string? strategyKey = "my-strategy-key",
ResilienceContext? context = null,
object? arg = null,
ResilienceEventSeverity severity = ResilienceEventSeverity.Warning)
{
context ??= ResilienceContext.Get("op-key");
var props = new ResilienceProperties();
if (!string.IsNullOrEmpty(strategyKey))
{
props.Set(new ResiliencePropertyKey<string?>("Polly.StrategyKey"), strategyKey);
}
telemetry.ReportEvent(
new ResilienceEvent(severity, "my-event"),
"my-builder",
props,
"my-strategy",
"my-strategy-type",
context,
outcome,
arg ?? new TestArguments());
}
}