-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
CacheSpecs.cs
700 lines (527 loc) · 29.3 KB
/
CacheSpecs.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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
using System;
using System.Threading;
using FluentAssertions;
using Polly.Caching;
using Polly.Specs.Helpers;
using Polly.Specs.Helpers.Caching;
using Polly.Utilities;
using Polly.Wrap;
using Xunit;
namespace Polly.Specs.Caching
{
[Collection(Polly.Specs.Helpers.Constants.SystemClockDependentTestCollection)]
public class CacheSpecs : IDisposable
{
#region Configuration
[Fact]
public void Should_throw_when_cache_provider_is_null()
{
ISyncCacheProvider cacheProvider = null;
Action action = () => Policy.Cache(cacheProvider, TimeSpan.MaxValue);
action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("cacheProvider");
}
[Fact]
public void Should_throw_when_ttl_strategy_is_null()
{
ISyncCacheProvider cacheProvider = new StubCacheProvider();
ITtlStrategy ttlStrategy = null;
Action action = () => Policy.Cache(cacheProvider, ttlStrategy);
action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("ttlStrategy");
}
[Fact]
public void Should_throw_when_cache_key_strategy_is_null()
{
ISyncCacheProvider cacheProvider = new StubCacheProvider();
Func<Context, string> cacheKeyStrategy = null;
Action action = () => Policy.Cache(cacheProvider, TimeSpan.MaxValue, cacheKeyStrategy);
action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("cacheKeyStrategy");
}
#endregion
#region Caching behaviours
[Fact]
public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value()
{
const string valueToReturnFromCache = "valueToReturnFromCache";
const string valueToReturnFromExecution = "valueToReturnFromExecution";
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));
bool delegateExecuted = false;
cache.Execute(ctx =>
{
delegateExecuted = true;
return valueToReturnFromExecution;
}, new Context(operationKey))
.Should().Be(valueToReturnFromCache);
delegateExecuted.Should().BeFalse();
}
[Fact]
public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value()
{
const string valueToReturn = "valueToReturn";
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
(bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
cacheHit1.Should().BeFalse();
fromCache1.Should().BeNull();
cache.Execute(ctx => { return valueToReturn; }, new Context(operationKey)).Should().Be(valueToReturn);
(bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
cacheHit2.Should().BeTrue();
fromCache2.Should().Be(valueToReturn);
}
[Fact]
public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_execute_delegate_again()
{
const string valueToReturn = "valueToReturn";
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
TimeSpan ttl = TimeSpan.FromMinutes(30);
CachePolicy cache = Policy.Cache(stubCacheProvider, ttl);
(bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
cacheHit1.Should().BeFalse();
fromCache1.Should().BeNull();
int delegateInvocations = 0;
Func<Context, string> func = ctx =>
{
delegateInvocations++;
return valueToReturn;
};
DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow();
SystemClock.DateTimeOffsetUtcNow = () => fixedTime;
// First execution should execute delegate and put result in the cache.
cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn);
delegateInvocations.Should().Be(1);
(bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
cacheHit2.Should().BeTrue();
fromCache2.Should().Be(valueToReturn);
// Second execution (before cache expires) should get it from the cache - no further delegate execution.
// (Manipulate time so just prior cache expiry).
SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(-1);
cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn);
delegateInvocations.Should().Be(1);
// Manipulate time to force cache expiry.
SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(1);
// Third execution (cache expired) should not get it from the cache - should cause further delegate execution.
cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn);
delegateInvocations.Should().Be(2);
}
[Fact]
public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not_hold_value_but_ttl_indicates_not_worth_caching()
{
const string valueToReturn = "valueToReturn";
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.Zero);
(bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
cacheHit1.Should().BeFalse();
fromCache1.Should().BeNull();
cache.Execute(ctx => { return valueToReturn; }, new Context(operationKey)).Should().Be(valueToReturn);
(bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
cacheHit2.Should().BeFalse();
fromCache2.Should().BeNull();
}
[Fact]
public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_execution_has_cached()
{
const string valueToReturn = "valueToReturn";
const string operationKey = "SomeOperationKey";
CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue);
int delegateInvocations = 0;
Func<Context, string> func = ctx =>
{
delegateInvocations++;
return valueToReturn;
};
cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn);
delegateInvocations.Should().Be(1);
cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn);
delegateInvocations.Should().Be(1);
cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn);
delegateInvocations.Should().Be(1);
}
[Fact]
public void Should_allow_custom_FuncCacheKeyStrategy()
{
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]);
object person1 = new object();
stubCacheProvider.Put("person1", person1, new Ttl(TimeSpan.MaxValue));
object person2 = new object();
stubCacheProvider.Put("person2", person2, new Ttl(TimeSpan.MaxValue));
bool funcExecuted = false;
Func<Context, object> func = ctx => { funcExecuted = true; return new object(); };
cache.Execute(func, new Context("person", new { id = "1" }.AsDictionary())).Should().BeSameAs(person1);
funcExecuted.Should().BeFalse();
cache.Execute(func, new Context("person", new { id = "2" }.AsDictionary())).Should().BeSameAs(person2);
funcExecuted.Should().BeFalse();
}
[Fact]
public void Should_allow_custom_ICacheKeyStrategy()
{
Action<Context, string, Exception> noErrorHandling = (_, __, ___) => { };
Action<Context, string> emptyDelegate = (_, __) => { };
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]);
CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling);
object person1 = new object();
stubCacheProvider.Put("person1", person1, new Ttl(TimeSpan.MaxValue));
object person2 = new object();
stubCacheProvider.Put("person2", person2, new Ttl(TimeSpan.MaxValue));
bool funcExecuted = false;
Func<Context, object> func = ctx => { funcExecuted = true; return new object(); };
cache.Execute(func, new Context("person", new { id = "1" }.AsDictionary())).Should().BeSameAs(person1);
funcExecuted.Should().BeFalse();
cache.Execute(func, new Context("person", new { id = "2" }.AsDictionary())).Should().BeSameAs(person2);
funcExecuted.Should().BeFalse();
}
#endregion
#region Caching behaviours, default(TResult)
[Fact]
public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_reference_type()
{
ResultClass valueToReturn = default(ResultClass);
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
(bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
cacheHit1.Should().BeFalse();
fromCache1.Should().BeNull();
cache.Execute(ctx => { return valueToReturn; }, new Context(operationKey)).Should().Be(valueToReturn);
(bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
cacheHit2.Should().BeTrue();
fromCache2.Should().Be(valueToReturn);
}
[Fact]
public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_reference_type()
{
ResultClass valueToReturnFromCache = default(ResultClass);
ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good);
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));
bool delegateExecuted = false;
cache.Execute(ctx =>
{
delegateExecuted = true;
return valueToReturnFromExecution;
}, new Context(operationKey))
.Should().Be(valueToReturnFromCache);
delegateExecuted.Should().BeFalse();
}
[Fact]
public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_value_type()
{
ResultPrimitive valueToReturn = default(ResultPrimitive);
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
(bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
cacheHit1.Should().BeFalse();
fromCache1.Should().BeNull();
cache.Execute(ctx => { return valueToReturn; }, new Context(operationKey)).Should().Be(valueToReturn);
(bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
cacheHit2.Should().BeTrue();
fromCache2.Should().Be(valueToReturn);
}
[Fact]
public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value__default_for_value_type()
{
ResultPrimitive valueToReturnFromCache = default(ResultPrimitive);
ResultPrimitive valueToReturnFromExecution = ResultPrimitive.Good;
valueToReturnFromExecution.Should().NotBe(valueToReturnFromCache);
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));
bool delegateExecuted = false;
cache.Execute(ctx =>
{
delegateExecuted = true;
return valueToReturnFromExecution;
}, new Context(operationKey))
.Should().Be(valueToReturnFromCache);
delegateExecuted.Should().BeFalse();
}
#endregion
#region Non-generic CachePolicy in non-generic PolicyWrap
[Fact]
public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_outermost_in_policywrap()
{
const string valueToReturnFromCache = "valueToReturnFromCache";
const string valueToReturnFromExecution = "valueToReturnFromExecution";
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
Policy noop = Policy.NoOp();
PolicyWrap wrap = Policy.Wrap(cache, noop);
stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));
bool delegateExecuted = false;
wrap.Execute(ctx =>
{
delegateExecuted = true;
return valueToReturnFromExecution;
}, new Context(operationKey))
.Should().Be(valueToReturnFromCache);
delegateExecuted.Should().BeFalse();
}
[Fact]
public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_innermost_in_policywrap()
{
const string valueToReturnFromCache = "valueToReturnFromCache";
const string valueToReturnFromExecution = "valueToReturnFromExecution";
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
Policy noop = Policy.NoOp();
PolicyWrap wrap = Policy.Wrap(noop, cache);
stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));
bool delegateExecuted = false;
wrap.Execute(ctx =>
{
delegateExecuted = true;
return valueToReturnFromExecution;
}, new Context(operationKey))
.Should().Be(valueToReturnFromCache);
delegateExecuted.Should().BeFalse();
}
[Fact]
public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_mid_policywrap()
{
const string valueToReturnFromCache = "valueToReturnFromCache";
const string valueToReturnFromExecution = "valueToReturnFromExecution";
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
Policy noop = Policy.NoOp();
PolicyWrap wrap = Policy.Wrap(noop, cache, noop);
stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));
bool delegateExecuted = false;
wrap.Execute(ctx =>
{
delegateExecuted = true;
return valueToReturnFromExecution;
}, new Context(operationKey))
.Should().Be(valueToReturnFromCache);
delegateExecuted.Should().BeFalse();
}
#endregion
#region No-op pass-through behaviour
[Fact]
public void Should_always_execute_delegate_if_execution_key_not_set()
{
string valueToReturn = Guid.NewGuid().ToString();
CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue);
int delegateInvocations = 0;
Func<string> func = () =>
{
delegateInvocations++;
return valueToReturn;
};
cache.Execute(func /*, no operation key */).Should().Be(valueToReturn);
delegateInvocations.Should().Be(1);
cache.Execute(func /*, no operation key */).Should().Be(valueToReturn);
delegateInvocations.Should().Be(2);
}
[Fact]
public void Should_always_execute_delegate_if_execution_is_void_returning()
{
string operationKey = "SomeKey";
CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue);
int delegateInvocations = 0;
Action<Context> action = ctx => { delegateInvocations++; };
cache.Execute(action, new Context(operationKey));
delegateInvocations.Should().Be(1);
cache.Execute(action, new Context(operationKey));
delegateInvocations.Should().Be(2);
}
#endregion
#region Cancellation
[Fact]
public void Should_honour_cancellation_even_if_prior_execution_has_cached()
{
const string valueToReturn = "valueToReturn";
const string operationKey = "SomeOperationKey";
CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue);
CancellationTokenSource tokenSource = new CancellationTokenSource();
int delegateInvocations = 0;
Func<Context, CancellationToken, string> func = (ctx, ct) =>
{
// delegate does not observe cancellation token; test is whether CacheEngine does.
delegateInvocations++;
return valueToReturn;
};
cache.Execute(func, new Context(operationKey), tokenSource.Token).Should().Be(valueToReturn);
delegateInvocations.Should().Be(1);
tokenSource.Cancel();
cache.Invoking(policy => policy.Execute(func, new Context(operationKey), tokenSource.Token))
.ShouldThrow<OperationCanceledException>();
delegateInvocations.Should().Be(1);
}
[Fact]
public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_cache()
{
const string valueToReturn = "valueToReturn";
const string operationKey = "SomeOperationKey";
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue);
CancellationTokenSource tokenSource = new CancellationTokenSource();
Func<Context, CancellationToken, string> func = (ctx, ct) =>
{
tokenSource.Cancel(); // simulate cancellation raised during delegate execution
ct.ThrowIfCancellationRequested();
return valueToReturn;
};
cache.Invoking(policy => policy.Execute(func, new Context(operationKey), tokenSource.Token))
.ShouldThrow<OperationCanceledException>();
(bool cacheHit, object fromCache) = stubCacheProvider.TryGet(operationKey);
cacheHit.Should().BeFalse();
fromCache.Should().BeNull();
}
#endregion
#region Policy hooks
[Fact]
public void Should_call_onError_delegate_if_cache_get_errors()
{
Exception ex = new Exception();
ISyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: ex, putException: null);
Exception exceptionFromCacheProvider = null;
const string valueToReturnFromCache = "valueToReturnFromCache";
const string valueToReturnFromExecution = "valueToReturnFromExecution";
const string operationKey = "SomeOperationKey";
Action<Context, string, Exception> onError = (ctx, key, exc) => { exceptionFromCacheProvider = exc; };
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError);
stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));
bool delegateExecuted = false;
// Even though value is in cache, get will error; so value is returned from execution.
cache.Execute(ctx =>
{
delegateExecuted = true;
return valueToReturnFromExecution;
}, new Context(operationKey))
.Should().Be(valueToReturnFromExecution);
delegateExecuted.Should().BeTrue();
// And error should be captured by onError delegate.
exceptionFromCacheProvider.Should().Be(ex);
}
[Fact]
public void Should_call_onError_delegate_if_cache_put_errors()
{
Exception ex = new Exception();
ISyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: null, putException: ex);
Exception exceptionFromCacheProvider = null;
const string valueToReturn = "valueToReturn";
const string operationKey = "SomeOperationKey";
Action<Context, string, Exception> onError = (ctx, key, exc) => { exceptionFromCacheProvider = exc; };
CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError);
(bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
cacheHit1.Should().BeFalse();
fromCache1.Should().BeNull();
cache.Execute(ctx => { return valueToReturn; }, new Context(operationKey)).Should().Be(valueToReturn);
// error should be captured by onError delegate.
exceptionFromCacheProvider.Should().Be(ex);
// failed to put it in the cache
(bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
cacheHit2.Should().BeFalse();
fromCache2.Should().BeNull();
}
[Fact]
public void Should_execute_oncacheget_after_got_from_cache()
{
const string valueToReturnFromCache = "valueToReturnFromCache";
const string valueToReturnFromExecution = "valueToReturnFromExecution";
const string operationKey = "SomeOperationKey";
string keyPassedToDelegate = null;
Context contextToExecute = new Context(operationKey);
Context contextPassedToDelegate = null;
Action<Context, string, Exception> noErrorHandling = (_, __, ___) => { };
Action<Context, string> emptyDelegate = (_, __) => { };
Action<Context, string> onCacheAction = (ctx, key) => { contextPassedToDelegate = ctx; keyPassedToDelegate = key; };
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, onCacheAction, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling);
stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue));
bool delegateExecuted = false;
cache.Execute(ctx =>
{
delegateExecuted = true;
return valueToReturnFromExecution;
}, contextToExecute)
.Should().Be(valueToReturnFromCache);
delegateExecuted.Should().BeFalse();
contextPassedToDelegate.Should().BeSameAs(contextToExecute);
keyPassedToDelegate.Should().Be(operationKey);
}
[Fact]
public void Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_hold_value_and_put()
{
const string valueToReturn = "valueToReturn";
const string operationKey = "SomeOperationKey";
string keyPassedToOnCacheMiss = null;
string keyPassedToOnCachePut = null;
Context contextToExecute = new Context(operationKey);
Context contextPassedToOnCacheMiss = null;
Context contextPassedToOnCachePut = null;
Action<Context, string, Exception> noErrorHandling = (_, __, ___) => { };
Action<Context, string> emptyDelegate = (_, __) => { };
Action<Context, string> onCacheMiss = (ctx, key) => { contextPassedToOnCacheMiss = ctx; keyPassedToOnCacheMiss = key; };
Action<Context, string> onCachePut = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; };
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling);
(bool cacheHit1, object fromCache1) = stubCacheProvider.TryGet(operationKey);
cacheHit1.Should().BeFalse();
fromCache1.Should().BeNull();
cache.Execute(ctx => { return valueToReturn; }, contextToExecute).Should().Be(valueToReturn);
(bool cacheHit2, object fromCache2) = stubCacheProvider.TryGet(operationKey);
cacheHit2.Should().BeTrue();
fromCache2.Should().Be(valueToReturn);
contextPassedToOnCacheMiss.Should().BeSameAs(contextToExecute);
keyPassedToOnCacheMiss.Should().Be(operationKey);
contextPassedToOnCachePut.Should().BeSameAs(contextToExecute);
keyPassedToOnCachePut.Should().Be(operationKey);
}
[Fact]
public void Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold_value_and_returned_value_not_worth_caching()
{
const string valueToReturn = "valueToReturn";
const string operationKey = "SomeOperationKey";
string keyPassedToOnCacheMiss = null;
string keyPassedToOnCachePut = null;
Context contextToExecute = new Context(operationKey);
Context contextPassedToOnCacheMiss = null;
Context contextPassedToOnCachePut = null;
Action<Context, string, Exception> noErrorHandling = (_, __, ___) => { };
Action<Context, string> emptyDelegate = (_, __) => { };
Action<Context, string> onCacheMiss = (ctx, key) => { contextPassedToOnCacheMiss = ctx; keyPassedToOnCacheMiss = key; };
Action<Context, string> onCachePut = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; };
ISyncCacheProvider stubCacheProvider = new StubCacheProvider();
CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.Zero), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling);
(bool cacheHit, object fromCache) = stubCacheProvider.TryGet(operationKey);
cacheHit.Should().BeFalse();
fromCache.Should().BeNull();
cache.Execute(ctx => { return valueToReturn; }, contextToExecute).Should().Be(valueToReturn);
contextPassedToOnCacheMiss.Should().BeSameAs(contextToExecute);
keyPassedToOnCacheMiss.Should().Be(operationKey);
contextPassedToOnCachePut.Should().BeNull();
keyPassedToOnCachePut.Should().BeNull();
}
[Fact]
public void Should_not_execute_oncachemiss_if_dont_query_cache_because_cache_key_not_set()
{
string valueToReturn = Guid.NewGuid().ToString();
Action<Context, string, Exception> noErrorHandling = (_, __, ___) => { };
Action<Context, string> emptyDelegate = (_, __) => { };
bool onCacheMissExecuted = false;
Action<Context, string> onCacheMiss = (ctx, key) => { onCacheMissExecuted = true; };
CachePolicy cache = Policy.Cache(new StubCacheProvider(), new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, emptyDelegate, noErrorHandling, noErrorHandling);
cache.Execute(() => valueToReturn /*, no operation key */).Should().Be(valueToReturn);
onCacheMissExecuted.Should().BeFalse();
}
#endregion
public void Dispose()
{
SystemClock.Reset();
}
}
}