forked from imperugo/StackExchange.Redis.Extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CacheClientTestBase.cs
1053 lines (831 loc) · 40.9 KB
/
CacheClientTestBase.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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Moq;
using StackExchange.Redis.Extensions.Binary;
using StackExchange.Redis.Extensions.Core.Abstractions;
using StackExchange.Redis.Extensions.Core.Configuration;
using StackExchange.Redis.Extensions.Core.Implementations;
using StackExchange.Redis.Extensions.Protobuf;
using StackExchange.Redis.Extensions.Tests.Extensions;
using StackExchange.Redis.Extensions.Tests.Helpers;
using Xunit;
using static System.Linq.Enumerable;
namespace StackExchange.Redis.Extensions.Core.Tests
{
[Collection("Redis")]
public abstract partial class CacheClientTestBase : IDisposable
{
private readonly IRedisCacheClient sut;
private readonly IDatabase db;
private readonly ISerializer serializer;
private readonly RedisConfiguration redisConfiguration;
private readonly IRedisCacheConnectionPoolManager connectionPoolManager;
internal CacheClientTestBase(ISerializer serializer)
{
redisConfiguration = new RedisConfiguration()
{
AbortOnConnectFail = true,
KeyPrefix = "MyPrefix__",
Hosts = new RedisHost[]
{
new RedisHost { Host = "localhost", Port = 6379 }
},
AllowAdmin = true,
ConnectTimeout = 3000,
Database = 0,
PoolSize = 5,
ServerEnumerationStrategy = new ServerEnumerationStrategy()
{
Mode = ServerEnumerationStrategy.ModeOptions.All,
TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.Throw
}
};
var moqLogger = new Mock<ILogger<RedisCacheConnectionPoolManager>>();
this.serializer = serializer;
connectionPoolManager = new RedisCacheConnectionPoolManager(redisConfiguration, moqLogger.Object);
sut = new RedisCacheClient(connectionPoolManager, this.serializer, redisConfiguration);
db = sut.GetDbFromConfiguration().Database;
}
protected IRedisCacheClient Sut => sut;
public void Dispose()
{
db.FlushDatabase();
db.Multiplexer.GetSubscriber().UnsubscribeAll();
connectionPoolManager.Dispose();
}
[Fact]
public async Task Info_Should_Return_Valid_Information()
{
var response = await Sut.GetDbFromConfiguration().GetInfoAsync().ConfigureAwait(false);
Assert.NotNull(response);
Assert.True(response.Any());
Assert.Equal("6379", response["tcp_port"]);
}
[Fact]
public async Task Info_Category_Should_Return_Valid_Information()
{
var response = await Sut.GetDbFromConfiguration().GetInfoCategorizedAsync().ConfigureAwait(false);
Assert.NotNull(response);
Assert.True(response.Any());
Assert.Equal("6379", response.SingleOrDefault(x => x.Key == "tcp_port").InfoValue);
}
[Fact]
public async Task Add_Item_To_Redis_Database()
{
var added = await Sut.GetDbFromConfiguration().AddAsync("my Key", "my value");
var redisValue = await db.KeyExistsAsync("my Key");
Assert.True(added);
Assert.True(redisValue);
}
[Fact]
public async Task Add_Complex_Item_To_Redis_Database()
{
var testobject = new TestClass<DateTime>();
var added = await Sut.GetDbFromConfiguration().AddAsync("my Key", testobject);
var redisValue = await db.StringGetAsync("my Key");
Assert.True(added);
var obj = serializer.Deserialize<TestClass<DateTime>>(redisValue);
Assert.True(db.KeyExists("my Key"));
Assert.NotNull(obj);
Assert.Equal(testobject.Key, obj.Key);
Assert.Equal(testobject.Value.ToUniversalTime(), obj.Value.ToUniversalTime());
}
[Fact]
public async Task Add_Multiple_Object_With_A_Single_Roundtrip_To_Redis_Must_Store_Data_Correctly_Into_Database()
{
var values = new List<Tuple<string, string>>
{
new Tuple<string, string>("key1", "value1"),
new Tuple<string, string>("key2", "value2"),
new Tuple<string, string>("key3", "value3")
};
var added = await Sut.GetDbFromConfiguration().AddAllAsync(values);
Assert.True(added);
Assert.True(await db.KeyExistsAsync("key1"));
Assert.True(await db.KeyExistsAsync("key2"));
Assert.True(await db.KeyExistsAsync("key3"));
Assert.Equal("value1", serializer.Deserialize<string>(await db.StringGetAsync("key1")));
Assert.Equal("value2", serializer.Deserialize<string>(await db.StringGetAsync("key2")));
Assert.Equal("value3", serializer.Deserialize<string>(await db.StringGetAsync("key3")));
}
[Fact]
public async Task Get_All_Should_Return_All_Database_Keys()
{
var values = Range(0, 5)
.Select(i => new TestClass<string>($"Key{i}", Guid.NewGuid().ToString()))
.ToArray();
foreach (var x in values)
{
await db.StringSetAsync(x.Key, serializer.Serialize(x.Value));
}
var keys = new[] { values[0].Key, values[1].Key, values[2].Key, "notexistingkey" };
var result = await Sut.GetDbFromConfiguration().GetAllAsync<string>(keys);
Assert.True(result.Count() == 4);
Assert.Equal(result[values[0].Key], values[0].Value);
Assert.Equal(result[values[1].Key], values[1].Value);
Assert.Equal(result[values[2].Key], values[2].Value);
Assert.Null(result["notexistingkey"]);
}
[Fact]
public async Task Get_With_Complex_Item_Should_Return_Correct_Value()
{
var value = Range(0, 1)
.Select(i => new ComplexClassForTest<string, Guid>($"Key{i}", Guid.NewGuid()))
.First();
await db.StringSetAsync(value.Item1, serializer.Serialize(value));
var cachedObject = await Sut.GetDbFromConfiguration().GetAsync<ComplexClassForTest<string, Guid>>(value.Item1);
Assert.NotNull(cachedObject);
Assert.Equal(value.Item1, cachedObject.Item1);
Assert.Equal(value.Item2, cachedObject.Item2);
}
[Fact]
public async Task Remove_All_Should_Remove_All_Specified_Keys()
{
var values = Range(1, 5)
.Select(i => new TestClass<string>($"Key{i}", Guid.NewGuid().ToString()))
.ToArray();
foreach (var x in values)
{
await db.StringSetAsync(x.Key, x.Value);
}
await Sut.GetDbFromConfiguration().RemoveAllAsync(values.Select(x => x.Key));
foreach (var value in values)
{
Assert.False(db.KeyExists(value.Key));
}
}
[Fact]
public async Task Search_With_Valid_Start_With_Pattern_Should_Return_Correct_Keys()
{
var values = Range(1, 20)
.Select(i => new TestClass<string>($"Key{i}", Guid.NewGuid().ToString()))
.ToArray();
foreach (var x in values)
{
await db.StringSetAsync(x.Key, x.Value);
}
var key = (await Sut.GetDbFromConfiguration().SearchKeysAsync("Key1*")).ToList();
Assert.True(key.Count == 11);
}
[Fact]
public async Task SearchKeys_With_Key_Prefix_Should_Return_All_Database_Keys()
{
var tsk1 = Sut.GetDbFromConfiguration().AddAsync("mykey1", "Foo");
var tsk2 = Sut.GetDbFromConfiguration().AddAsync("mykey2", "Bar");
var tsk3 = Sut.GetDbFromConfiguration().AddAsync("key3", "Bar");
await Task.WhenAll(tsk1, tsk2, tsk3);
var keys = await Sut.GetDbFromConfiguration().SearchKeysAsync("*mykey*");
Assert.True(keys.Count() == 2);
}
[Fact]
public async Task SearchKeys_With_Start_Should_Return_All_Keys()
{
var values = Range(0, 10)
.Select(i => new TestClass<string>($"mykey{i}", Guid.NewGuid().ToString()))
.ToArray();
foreach (var x in values)
{
await db.StringSetAsync(x.Key, x.Value);
}
var result = (await Sut.GetDbFromConfiguration().SearchKeysAsync("*")).OrderBy(k => k).ToList();
Assert.True(result.Count == 10);
}
[Fact]
public async Task SearchKeys_With_Key_Prefix_Should_Return_Keys_Without_Prefix()
{
var values = Range(0, 10)
.Select(i => new TestClass<string>($"mykey{i}", Guid.NewGuid().ToString()))
.ToArray();
foreach (var x in values)
await db.StringSetAsync(x.Key, x.Value);
var result = (await Sut.GetDbFromConfiguration().SearchKeysAsync("*mykey*")).OrderBy(k => k).ToList();
Assert.True(result.Count == 10);
for (var i = 0; i < result.Count; i++)
Assert.Equal(result[i], values[i].Key);
}
[Fact]
public async Task Exist_With_Valid_Object_Should_Return_The_Correct_Instance()
{
var values = Range(0, 2)
.Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()))
.ToArray();
foreach (var x in values)
await db.StringSetAsync(x.Key, x.Value);
Assert.True(await Sut.GetDbFromConfiguration().ExistsAsync(values[0].Key));
}
[Fact]
public async Task Exist_With_Not_Valid_Object_Should_Return_The_Correct_Instance()
{
var values = Range(0, 2).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()));
foreach (var x in values)
await db.StringSetAsync(x.Key, x.Value);
Assert.False(await Sut.GetDbFromConfiguration().ExistsAsync("this key doesn not exist into redi"));
}
[Fact]
public async Task SetAdd_With_An_Existing_Key_Should_Return_Valid_Data()
{
var values = Range(0, 5)
.Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()))
.ToArray();
foreach (var x in values)
{
await db.StringSetAsync(x.Key, serializer.Serialize(x.Value));
await Sut.GetDbFromConfiguration().SetAddAsync("MySet", x.Key);
}
var keys = db.SetMembers("MySet");
Assert.Equal(keys.Length, values.Length);
}
[Fact]
public async Task SetPop_With_An_Existing_Key_Should_Return_Valid_Data()
{
var values = Range(0, 5)
.Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()))
.ToArray();
foreach (var value in values)
{
await db.SetAddAsync("MySet", serializer.Serialize(value.Value));
}
var result = await Sut.GetDbFromConfiguration().SetPopAsync<string>("MySet");
Assert.NotNull(result);
Assert.Contains(values, v => v.Value == result);
var members = await db.SetMembersAsync("MySet");
var itemsLeft = members.Select(m => serializer.Deserialize<string>(m)).ToArray();
Assert.True(itemsLeft.Length == 4);
Assert.DoesNotContain(itemsLeft, l => l == result);
}
[Fact]
public async Task SetPop_With_A_Non_Existing_Key_Should_Return_Null()
{
var result = await Sut.GetDbFromConfiguration().SetPopAsync<string>("MySet");
Assert.Null(result);
}
[Fact]
public async Task SetPop_With_An_Empty_Key_Should_Throw_Exception()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().SetPopAsync<string>(string.Empty));
}
[Fact]
public async Task SetPop_Count_With_An_Existing_Key_Should_Return_Valid_Data()
{
var values = Range(0, 5)
.Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()))
.ToArray();
foreach (var value in values)
{
await db.SetAddAsync("MySet", serializer.Serialize(value.Value));
}
var result = await Sut.GetDbFromConfiguration().SetPopAsync<string>("MySet", 3);
Assert.NotNull(result);
Assert.Equal(3, result.Count());
foreach (var r in result)
Assert.Contains(values, v => v.Value == r);
var members = await db.SetMembersAsync("MySet");
var itemsLeft = members.Select(m => serializer.Deserialize<string>(m)).ToArray();
Assert.True(itemsLeft.Length == 2);
foreach (var r in result)
Assert.DoesNotContain(itemsLeft, l => l == r);
}
[Fact]
public async Task SetPop_Count_With_A_Non_Existing_Key_Should_Return_Null()
{
var result = await Sut.GetDbFromConfiguration().SetPopAsync<string>("MySet", 0);
Assert.Null(result);
}
[Fact]
public async Task SetPop_Count_With_An_Empty_Key_Should_Throw_Exception()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().SetPopAsync<string>(string.Empty, 0));
}
[Fact]
public async Task SetMembers_With_Valid_Data_Should_Return_Correct_Keys()
{
var values = Range(0, 5).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())).ToArray();
foreach (var x in values)
await db.SetAddAsync("MySet", serializer.Serialize(x));
var keys = (await Sut.GetDbFromConfiguration().SetMembersAsync<TestClass<string>>("MySet")).ToArray();
Assert.Equal(keys.Length, values.Length);
foreach (var key in keys)
Assert.Contains(values, x => x.Key == key.Key && x.Value == key.Value);
}
[Fact]
public async Task SetMember_With_Valid_Data_Should_Return_Correct_Keys()
{
var values = Range(0, 5).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())).ToArray();
foreach (var x in values)
{
await db.StringSetAsync(x.Key, serializer.Serialize(x.Value));
await db.SetAddAsync("MySet", x.Key);
}
var keys = await Sut.GetDbFromConfiguration().SetMemberAsync("MySet");
Assert.Equal(keys.Length, values.Length);
}
[Fact]
public async Task SetMembers_With_Complex_Object_And_Valid_Data_Should_Return_Correct_Keys()
{
var values = Range(0, 5).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())).ToArray();
foreach (var x in values)
await db.SetAddAsync("MySet", serializer.Serialize(x));
var keys = (await Sut.GetDbFromConfiguration().SetMembersAsync<TestClass<string>>("MySet")).ToArray();
Assert.Equal(keys.Length, values.Length);
}
[Fact]
public async Task Massive_Add_Should_Not_Throw_Exception_And_Work_Correctly()
{
const int size = 3000;
var values = Range(0, size).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())).ToArray();
var tupleValues = values.Select(x => new Tuple<string, TestClass<string>>(x.Key, x)).ToList();
var result = await Sut.GetDbFromConfiguration().AddAllAsync(tupleValues);
var cached = await Sut.GetDbFromConfiguration().GetAllAsync<TestClass<string>>(values.Select(x => x.Key));
Assert.True(result);
Assert.NotNull(cached);
Assert.Equal(size, cached.Count);
foreach (var value in values)
{
Assert.Equal(value.Key, cached[value.Key].Key);
Assert.Equal(value.Value, cached[value.Key].Value);
}
}
[Fact]
public async Task Massive_Add_With_Expiring_Should_Delete_Expired_Keys()
{
var values = new List<Tuple<string, string>>
{
new Tuple<string, string>("ProductOneList1", "1"),
new Tuple<string, string>("ProductOneList2", "2"),
new Tuple<string, string>("ProductOneList3", "3"),
new Tuple<string, string>("ProductOneList4", "4"),
new Tuple<string, string>("ProductOneList5", "5"),
new Tuple<string, string>("ProductOneList6", "6"),
new Tuple<string, string>("ProductOneList7", "7"),
new Tuple<string, string>("ProductOneList8", "8"),
new Tuple<string, string>("ProductOneList9", "9"),
};
await Sut.GetDbFromConfiguration().AddAllAsync(values, TimeSpan.FromMilliseconds(1));
await Task.Delay(TimeSpan.FromMilliseconds(2));
foreach (var value in values)
{
var exists = await Sut.GetDbFromConfiguration().ExistsAsync(value.Item1);
Assert.False(exists, value.Item1);
}
}
[Fact]
public async Task Massive_Add_With_Expiring_And_Add_List_Again_Should_Work()
{
// Issue 228
// https://github.com/imperugo/StackExchange.Redis.Extensions/issues/288
var valuesOneList = new List<Tuple<string, string>>
{
new Tuple<string, string>("ProductManyList1", "1"),
new Tuple<string, string>("ProductManyList2", "2"),
new Tuple<string, string>("ProductManyList3", "3"),
new Tuple<string, string>("ProductManyList4", "4"),
new Tuple<string, string>("ProductManyList5", "5"),
new Tuple<string, string>("ProductManyList6", "6"),
new Tuple<string, string>("ProductManyList7", "7"),
new Tuple<string, string>("ProductManyList8", "8"),
new Tuple<string, string>("ProductManyList9", "9"),
};
await Sut.GetDbFromConfiguration().AddAllAsync(valuesOneList, TimeSpan.FromMilliseconds(1));
await Task.Delay(TimeSpan.FromMilliseconds(2));
foreach (var value in valuesOneList)
{
var exists = await Sut.GetDbFromConfiguration().ExistsAsync(value.Item1);
Assert.False(exists, value.Item1);
}
var valuesTwoLis = new List<Tuple<string, string>>
{
new Tuple<string, string>("ProductManyList10", "1"),
new Tuple<string, string>("ProductManyList11", "2"),
new Tuple<string, string>("ProductManyList12", "3"),
new Tuple<string, string>("ProductManyList13", "4"),
new Tuple<string, string>("ProductManyList14", "5"),
new Tuple<string, string>("ProductManyList15", "6"),
new Tuple<string, string>("ProductManyList16", "7"),
new Tuple<string, string>("ProductManyList17", "8"),
new Tuple<string, string>("ProductManyList18", "9"),
};
await Sut.GetDbFromConfiguration().AddAllAsync(valuesTwoLis, TimeSpan.FromMilliseconds(1));
await Task.Delay(TimeSpan.FromMilliseconds(2));
foreach (var value in valuesTwoLis)
{
var exists = await Sut.GetDbFromConfiguration().ExistsAsync(value.Item1);
Assert.False(exists, value.Item1);
}
}
[Fact]
public async Task Adding_Value_Type_Should_Return_Correct_Value()
{
var d = 1;
var added = await Sut.GetDbFromConfiguration().AddAsync("my Key", d);
var dbValue = await Sut.GetDbFromConfiguration().GetAsync<int>("my Key");
Assert.True(added);
Assert.True(db.KeyExists("my Key"));
Assert.Equal(dbValue, d);
}
[Fact]
public async Task Adding_Value_Type_Should_Return_Non_Generic_Correct_Value()
{
var d = new TestClass<string> { Key = $"key21", Value = "value21" };
var added = await Sut.GetDbFromConfiguration().AddAsync("my Key", d);
// TODO: Assuming that only the type of TestClass<string> can be obtained here.
var returnType = typeof(TestClass<string>);
// TODO: Use non-generic methods to get results.
var dbValue = await Sut.GetDbFromConfiguration().GetAsync("my Key", returnType);
Assert.True(added);
Assert.True(db.KeyExists("my Key"));
// TODO: dbValue equal.
Assert.Equal(dbValue, d);
}
[Fact]
public async Task Adding_Value_Type_Validate_Generic_Return_Object()
{
var d = new TestClass<string> { Key = $"key21", Value = "value21" };
var added = await Sut.GetDbFromConfiguration().AddAsync("my Key", d);
Assert.True(added);
Assert.True(db.KeyExists("my Key"));
if (Sut.GetDbFromConfiguration().Serializer is ProtobufSerializer)
{
// TODO: ProtobufSerializer generic get object throws an ArgumentNullException.
await Assert.ThrowsAsync<ArgumentNullException>(() => Sut.GetDbFromConfiguration().GetAsync<object>("my Key"));
}
else
{
// TODO: Use generic methods to get results.
var dbValue = await Sut.GetDbFromConfiguration().GetAsync<object>("my Key");
if (Sut.GetDbFromConfiguration().Serializer is BinarySerializer)
{
// TODO: BinarySerializer dbValue equal.
Assert.Equal(dbValue, d);
}
else
{
// TODO: dbValue not equal.
Assert.NotEqual(dbValue, d);
}
}
}
[Fact]
public async Task Adding_Collection_To_Redis_Should_Work_Correctly()
{
var items = Range(1, 3).Select(i => new TestClass<string> { Key = $"key{i}", Value = "value{i}" }).ToArray();
var added = await Sut.GetDbFromConfiguration().AddAsync("my Key", items);
var dbValue = await Sut.GetDbFromConfiguration().GetAsync<TestClass<string>[]>("my Key");
Assert.True(added);
Assert.True(await db.KeyExistsAsync("my Key"));
Assert.Equal(dbValue.Length, items.Length);
for (var i = 0; i < items.Length; i++)
{
Assert.Equal(dbValue[i].Value, items[i].Value);
Assert.Equal(dbValue[i].Key, items[i].Key);
}
}
[Fact]
public async Task Adding_Collection_To_Redis_Should_Expire()
{
var expiresIn = new TimeSpan(0, 0, 1);
var items = Range(1, 3).Select(i => new Tuple<string, string>($"key{i}", "value{i}")).ToArray();
var added = await Sut.GetDbFromConfiguration().AddAllAsync(items, expiresIn);
await Task.Delay(expiresIn.Add(new TimeSpan(0, 0, 1)));
var hasExpired = items.All(x => !db.KeyExists(x.Item1));
Assert.True(added);
Assert.True(hasExpired);
}
[Fact]
public async Task Pub_Sub()
{
var message = Range(0, 10).ToArray();
var channel = new RedisChannel(Encoding.UTF8.GetBytes("unit_test"), RedisChannel.PatternMode.Auto);
var subscriberNotified = false;
IEnumerable<int> subscriberValue = null;
Func<IEnumerable<int>, Task> action = value =>
{
{
subscriberNotified = true;
subscriberValue = value;
}
return Task.CompletedTask;
};
await Sut.GetDbFromConfiguration().SubscribeAsync(channel, action);
var result = await Sut.GetDbFromConfiguration().PublishAsync(channel, message);
while (!subscriberNotified)
{
await Task.Delay(100);
}
Assert.Equal(1, result);
Assert.True(subscriberNotified);
Assert.Equal(message, subscriberValue);
}
[Fact]
public async Task SetAddGenericShouldThrowExceptionWhenKeyIsEmpty()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().SetAddAsync(string.Empty, string.Empty));
}
[Fact]
public async Task SetAddGenericShouldThrowExceptionWhenItemIsNull()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => Sut.GetDbFromConfiguration().SetAddAsync<string>("MySet", null));
}
[Fact]
public async Task SetAddGeneric_With_An_Existing_Key_Should_Return_Valid_Data()
{
var values = Range(0, 5).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())).ToList();
foreach (var x in values)
{
await db.StringSetAsync(x.Key, serializer.Serialize(x.Value));
await Sut.GetDbFromConfiguration().SetAddAsync("MySet", x);
}
var keys = await db.SetMembersAsync("MySet");
Assert.Equal(keys.Length, values.Count);
}
[Fact]
public async Task SetAddAsyncGenericShouldThrowExceptionWhenKeyIsEmpty()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().SetAddAsync(string.Empty, string.Empty));
}
[Fact]
public async Task SetAddAsyncGenericShouldThrowExceptionWhenItemIsNull()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => Sut.GetDbFromConfiguration().SetAddAsync<string>("MySet", null));
}
[Fact]
public async Task SetContainsAsyncShouldThrowExceptionWhenKeyIsEmpty()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().SetContainsAsync(string.Empty, string.Empty));
}
[Fact]
public async Task SetContainsAsyncShouldReturnTrue()
{
var key = "MySet";
var item = "MyItem";
await Sut.GetDbFromConfiguration().SetAddAsync(key, item);
var result = await Sut.GetDbFromConfiguration().SetContainsAsync(key, item);
Assert.True(result);
}
[Fact]
public async Task SetContainsAsyncShouldReturnFalseWhenItemIsWrong()
{
var key = "MySet";
var item = "MyItem";
var unknownItem = "MyUnknownItem";
await Sut.GetDbFromConfiguration().SetAddAsync(key, item);
var result = await Sut.GetDbFromConfiguration().SetContainsAsync(key, unknownItem);
Assert.False(result);
}
[Fact]
public async Task SetContainsAsyncShouldReturnFalseWhenKeyIsWrong()
{
var key = "MySet";
var item = "MyItem";
var unknownKey = "MyUnknownKey";
await Sut.GetDbFromConfiguration().SetAddAsync(key, item);
var result = await Sut.GetDbFromConfiguration().SetContainsAsync(unknownKey, item);
Assert.False(result);
}
[Fact]
public async Task SetContainsAsyncShouldThrowExceptionWhenItemIsNull()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => Sut.GetDbFromConfiguration().SetContainsAsync<string>("MySet", null));
}
[Fact]
public async Task SetAddAllGenericShouldThrowExceptionWhenItemsIsNull()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => Sut.GetDbFromConfiguration().SetAddAllAsync("MySet", CommandFlags.None, (string[])null));
}
[Fact]
public async Task SetAddAllGenericShouldThrowExceptionWhenItemsContainsOneNullItem()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().SetAddAllAsync("MySet", CommandFlags.None, "value", null, "value2"));
}
[Fact]
public async Task SetRemoveGenericWithAnExistingItemShouldReturnTrue()
{
const string key = "MySet", item = "MyItem";
await Sut.GetDbFromConfiguration().SetAddAsync(key, item);
var result = await Sut.GetDbFromConfiguration().SetRemoveAsync(key, item);
Assert.True(result);
}
[Fact]
public async Task SetRemoveGenericWithAnUnexistingItemShouldReturnFalse()
{
const string key = "MySet";
await Sut.GetDbFromConfiguration().SetAddAsync(key, "ExistingItem");
var result = await Sut.GetDbFromConfiguration().SetRemoveAsync(key, "UnexistingItem");
Assert.False(result);
}
[Fact]
public async Task SetRemoveAsyncGenericWithAnExistingItemShouldReturnTrue()
{
const string key = "MySet", item = "MyItem";
await Sut.GetDbFromConfiguration().SetAddAsync(key, item);
var result = await Sut.GetDbFromConfiguration().SetRemoveAsync(key, item);
Assert.True(result);
}
[Fact]
public async Task SetRemoveAllGenericShouldThrowExceptionWhenItemsContainsOneNullItem()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().SetRemoveAllAsync("MySet", CommandFlags.None, "value", null, "value2"));
}
[Fact]
public async Task SetRemoveAllGenericWithAnExistingItemShouldReturnValidData()
{
const string key = "MySet";
var items = new[] { "MyItem1", "MyItem2" };
await Sut.GetDbFromConfiguration().SetAddAllAsync(key, CommandFlags.None, items);
var result = await Sut.GetDbFromConfiguration().SetRemoveAllAsync(key, CommandFlags.None, items);
Assert.Equal(items.Length, result);
}
[Fact]
public async Task SetRemoveAllAsyncGenericShouldThrowExceptionWhenItemsContainsOneNullItem()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().SetRemoveAllAsync<string>("MySet", CommandFlags.None, "value", null, "value2"));
}
[Fact]
public async Task ListAddToLeftGenericShouldThrowExceptionWhenKeyIsEmpty()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().ListAddToLeftAsync(string.Empty, string.Empty));
}
[Fact]
public async Task ListAddToLeftArrayShouldThrowExceptionWhenKeyIsEmpty()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().ListAddToLeftAsync(string.Empty, items: Array.Empty<TestClass<string>>()));
}
[Fact]
public async Task ListAddToLeftGenericShouldThrowExceptionWhenItemIsNull()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => Sut.GetDbFromConfiguration().ListAddToLeftAsync<string>("MyList", item: null));
}
[Fact]
public async Task ListAddToLeftGenericShouldThrowExceptionWhenItemsIsNull()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => Sut.GetDbFromConfiguration().ListAddToLeftAsync<string>("MyList", items: null));
}
[Fact]
public async Task ListAddToLeftGeneric_With_An_Existing_Key_Should_Return_Valid_Data()
{
var values = Range(0, 5).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())).ToList();
const string key = "MyList";
foreach (var x in values)
{
await Sut.GetDbFromConfiguration().ListAddToLeftAsync(key, serializer.Serialize(x));
}
var keys = await db.ListRangeAsync(key);
Assert.Equal(keys.Length, values.Count);
}
[Fact]
public async Task ListAddToLeftArray_With_An_Existing_Key_Should_Return_Valid_Data()
{
var values = Range(0, 5000).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())).ToArray();
const string key = "MyList";
await Sut.GetDbFromConfiguration().ListAddToLeftAsync(key, items: values);
var keys = await db.ListRangeAsync(key);
Assert.Equal(keys.Length, values.Length);
}
[Fact]
public async Task ListAddToLeftAsyncGenericShouldThrowExceptionWhenKeyIsEmpty()
{
await Assert.ThrowsAsync<ArgumentException>(
() => Sut.GetDbFromConfiguration().ListAddToLeftAsync(string.Empty, string.Empty));
}
[Fact]
public async Task ListAddToLeftAsyncArrayShouldThrowExceptionWhenKeyIsEmpty()
{
await Assert.ThrowsAsync<ArgumentException>(
() => Sut.GetDbFromConfiguration().ListAddToLeftAsync(string.Empty, items: Array.Empty<TestClass<string>>()));
}
[Fact]
public async Task ListAddToLeftAsyncGenericShouldThrowExceptionWhenItemIsNull()
{
await Assert.ThrowsAsync<ArgumentNullException>(
() => Sut.GetDbFromConfiguration().ListAddToLeftAsync<string>("MyList", item: null));
}
[Fact]
public async Task ListAddToLeftAsyncGenericShouldThrowExceptionWhenItemsIsNull()
{
await Assert.ThrowsAsync<ArgumentNullException>(
() => Sut.GetDbFromConfiguration().ListAddToLeftAsync<string>("MyList", items: null));
}
[Fact]
public async Task ListAddToLeftAsyncGeneric_With_An_Existing_Key_Should_Return_Valid_Data()
{
var values = Range(0, 5).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())).ToList();
const string key = "MyListAsync";
foreach (var value in values)
{
// TODO: why no assertion on the result?
var result = await Sut.GetDbFromConfiguration().ListAddToLeftAsync(key, serializer.Serialize(value));
}
var keys = await db.ListRangeAsync(key);
Assert.Equal(keys.Length, values.Count);
}
[Fact]
public async Task ListAddToLeftAsyncArray_With_An_Existing_Key_Should_Return_Valid_Data()
{
var values = Range(0, 5000).Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())).ToArray();
const string key = "MyListAsync";
await Sut.GetDbFromConfiguration().ListAddToLeftAsync(key, items: values);
var keys = await db.ListRangeAsync(key);
Assert.Equal(keys.Length, values.Length);
}
[Fact]
public async Task ListGetFromRightGenericShouldThrowExceptionWhenKeyIsEmpty()
{
await Assert.ThrowsAsync<ArgumentException>(() => Sut.GetDbFromConfiguration().ListGetFromRightAsync<string>(string.Empty));
}
[Fact]
public async Task ListGetFromRightGeneric_With_An_Existing_Key_Should_Return_Valid_Data()
{
var values = Range(0, 1)
.Select(_ => new TestClass<string>(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()))
.ToArray();
var key = "MyList";
foreach (var x in values)
await db.ListLeftPushAsync(key, serializer.Serialize(x));
var item = await Sut.GetDbFromConfiguration().ListGetFromRightAsync<TestClass<string>>(key);
Assert.Equal(item.Key, values[0].Key);
Assert.Equal(item.Value, values[0].Value);
}
[Fact]
public async Task ListGetFromRightGeneric_With_An_Existing_Key_Should_Return_Null_If_List_Is_Empty()
{
var key = "MyList";
var item = await Sut.GetDbFromConfiguration().ListGetFromRightAsync<TestClass<string>>(key);
Assert.Null(item);
}
[Fact]
public async Task ListGetFromRight_With_An_Existing_Key_Should_Return_Null_If_List_Is_Empty()
{
var key = "MyList";
var item = await Sut.GetDbFromConfiguration().ListGetFromRightAsync<TestClass<string>>(key);
Assert.Null(item);
}
[Fact]
public async Task Get_Value_With_Expiry_Updates_ExpiryAt()
{
var key = "TestKey";
var value = "TestValue";
var originalTime = DateTime.UtcNow.AddSeconds(5);
var testTime = DateTime.UtcNow.AddSeconds(20);
var resultTimeSpan = originalTime.Subtract(DateTime.UtcNow);
await Sut.GetDbFromConfiguration().AddAsync(key, value, originalTime);
await Sut.GetDbFromConfiguration().GetAsync<string>(key, testTime);
var resultValue = await db.StringGetWithExpiryAsync(key);
Assert.True(resultTimeSpan < resultValue.Expiry.Value);
}
[Fact]
public async Task Get_Value_With_Expiry_Updates_ExpiryIn()
{
var key = "TestKey";
var value = "TestValue";
var originalTime = new TimeSpan(0, 0, 5);
var testTime = new TimeSpan(0, 0, 20);
var resultTimeSpan = originalTime;
await Sut.GetDbFromConfiguration().AddAsync(key, value, originalTime);
await Sut.GetDbFromConfiguration().GetAsync<string>(key, testTime);
var resultValue = await db.StringGetWithExpiryAsync(key);