-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathWrapperValueObjectTests.cs
943 lines (788 loc) · 38.7 KB
/
WrapperValueObjectTests.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
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using Architect.DomainModeling.Conversions;
using Architect.DomainModeling.Tests.WrapperValueObjectTestTypes;
using Xunit;
namespace Architect.DomainModeling.Tests
{
public class WrapperValueObjectTests
{
[Fact]
public void StringComparison_WithNonStringType_ShouldThrow()
{
var instance = new IntValue(default);
Assert.Throws<NotSupportedException>(() => instance.GetStringComparison());
}
[Fact]
public void StringComparison_WithStringType_ShouldReturnExpectedResult()
{
var instance = new StringValue("");
Assert.Equal(StringComparison.OrdinalIgnoreCase, instance.GetStringComparison());
}
[Fact]
public void Construct_WithNull_ShouldThrow()
{
Assert.Throws<ArgumentNullException>(() => new StringValue(null!));
}
[Fact]
public void ToString_Regularly_ShouldReturnExpectedResult()
{
Assert.Equal("1", new IntValue(1).ToString());
}
[Fact]
public void GetHashCode_Regulary_ShouldReturnExpectedResult()
{
Assert.Equal(1.GetHashCode(), new IntValue(1).GetHashCode());
}
[Fact]
public void GetHashCode_WithIgnoreCaseString_ShouldReturnExpectedResult()
{
var one = new StringValue("A").GetHashCode();
var two = new StringValue("a").GetHashCode();
Assert.Equal(one, two);
}
[Fact]
public void GetHashCode_WithUnintializedObject_ShouldReturnExpectedResult()
{
var instance = (StringValue)RuntimeHelpers.GetUninitializedObject(typeof(StringValue));
Assert.Equal(0, instance.GetHashCode());
}
[Theory]
[InlineData(null, null, true)] // Implementation should still handle null left operand as expected
[InlineData(null, "", false)] // Custom collection's hash code always returns 1
[InlineData("", null, false)] // Custom collection's hash code always returns 1
[InlineData("A", "A", true)] // Custom collection's hash code always returns 1
[InlineData("A", "B", true)] // Custom collection's hash code always returns 1
public void GetHashCode_WithCustomEquatableCollection_ShouldHonorItsOverride(string? one, string? two, bool expectedResult)
{
var left = one is null
? RuntimeHelpers.GetUninitializedObject(typeof(CustomCollectionWrapperValueObject))
: new CustomCollectionWrapperValueObject(new CustomCollectionWrapperValueObject.CustomCollection(one));
var right = two is null
? RuntimeHelpers.GetUninitializedObject(typeof(CustomCollectionWrapperValueObject))
: new CustomCollectionWrapperValueObject(new CustomCollectionWrapperValueObject.CustomCollection(two));
var leftHashCode = left.GetHashCode();
var rightHashCode = right.GetHashCode();
Assert.Equal(expectedResult, leftHashCode == rightHashCode);
}
[Theory]
[InlineData(0, 0, true)]
[InlineData(0, 1, false)]
[InlineData(1, -1, false)]
public void Equals_Regularly_ShouldReturnExpectedResult(int one, int two, bool expectedResult)
{
var left = new IntValue(one);
var right = new IntValue(two);
Assert.Equal(expectedResult, left.Equals(right));
}
[Theory]
[InlineData("", "", true)]
[InlineData("A", "A", true)]
[InlineData("A", "a", true)]
[InlineData("A", "B", false)]
public void Equals_WithIgnoreCaseString_ShouldReturnExpectedResult(string one, string two, bool expectedResult)
{
var left = new StringValue(one);
var right = new StringValue(two);
Assert.Equal(expectedResult, left.Equals(right));
}
[Fact]
public void Equals_WithUnintializedObject_ShouldReturnExpectedResult()
{
var left = (StringValue)RuntimeHelpers.GetUninitializedObject(typeof(StringValue));
var right = new StringValue("Example");
Assert.NotEqual(left, right);
Assert.NotEqual(right, left);
}
[Theory]
[InlineData(null, null, true)] // Implementation should still handle null left operand as expected
[InlineData(null, "", false)] // Implementation should still handle null left operand as expected
[InlineData("", null, true)] // Custom collection's equality always returns true
[InlineData("A", "A", true)] // Custom collection's equality always returns true
[InlineData("A", "B", true)] // Custom collection's equality always returns true
public void Equals_WithCustomEquatableCollection_ShouldHonorItsOverride(string? one, string? two, bool expectedResult)
{
var left = one is null
? RuntimeHelpers.GetUninitializedObject(typeof(CustomCollectionWrapperValueObject))
: new CustomCollectionWrapperValueObject(new CustomCollectionWrapperValueObject.CustomCollection(one));
var right = two is null
? RuntimeHelpers.GetUninitializedObject(typeof(CustomCollectionWrapperValueObject))
: new CustomCollectionWrapperValueObject(new CustomCollectionWrapperValueObject.CustomCollection(two));
Assert.Equal(expectedResult, left.Equals(right));
}
[Theory]
[InlineData(0, 0)]
[InlineData(0, 1)]
[InlineData(1, -1)]
public void EqualityOperator_Regularly_ShouldMatchEquals(int one, int two)
{
var left = new IntValue(one);
var right = new IntValue(two);
Assert.Equal(left.Equals(right), left == right);
}
[Theory]
[InlineData("", "")]
[InlineData("A", "A")]
[InlineData("A", "a")]
[InlineData("A", "B")]
public void EqualityOperator_WithIgnoreCaseString_ShouldMatchEquals(string one, string two)
{
var left = new StringValue(one);
var right = new StringValue(two);
Assert.Equal(left.Equals(right), left == right);
}
[Theory]
[InlineData("", "")]
[InlineData("A", "A")]
[InlineData("A", "a")]
[InlineData("A", "B")]
public void CompareTo_WithEqualValuesAndIgnoreCaseString_ShouldHaveEqualityMatchingEquals(string one, string two)
{
var left = new StringValue(one);
var right = new StringValue(two);
Assert.Equal(left.Equals(right), left.CompareTo(right) == 0);
}
[Fact]
public void CompareTo_WithoutExplicitInterface_ShouldNotBeImplemented()
{
var array = new[] { new IntValue(1), new IntValue(2) };
Assert.Throws<InvalidOperationException>(() => Array.Sort(array));
}
[Fact]
public void CompareTo_WithExplicitInterface_ShouldBeImplementedCorrectly()
{
var array = new[] { new StringValue("a"), new StringValue("A"), new StringValue("0"), };
array = array.OrderBy(x => x).ToArray(); // Stable sort
Assert.Equal("0", array[0].Value);
Assert.Equal("a", array[1].Value); // Stable sort combined with ignore-case should have kept "a" before "A"
Assert.Equal("A", array[2].Value);
}
[Theory]
[InlineData(null, null, 0)]
[InlineData(null, "", -1)]
[InlineData("", null, +1)]
[InlineData("", "", 0)]
[InlineData("", "A", -1)]
[InlineData("A", "", +1)]
[InlineData("A", "a", 0)]
[InlineData("a", "A", 0)]
[InlineData("A", "B", -1)]
[InlineData("AA", "A", +1)]
public void CompareTo_WithIgnoreCaseString_ShouldReturnExpectedResult(string? one, string? two, int expectedResult)
{
var left = (StringValue?)one;
var right = (StringValue?)two;
Assert.Equal(expectedResult, Comparer<StringValue>.Default.Compare(left, right));
Assert.Equal(-expectedResult, Comparer<StringValue>.Default.Compare(right, left));
}
[Theory]
[InlineData(null, null, 0)]
[InlineData(null, "", -1)]
[InlineData("", null, +1)]
[InlineData("", "", 0)]
[InlineData("", "A", -1)]
[InlineData("A", "", +1)]
[InlineData("A", "a", 0)]
[InlineData("a", "A", 0)]
[InlineData("A", "B", -1)]
[InlineData("AA", "A", +1)]
public void GreaterThan_WithIgnoreCaseString_ShouldReturnExpectedResult(string? one, string? two, int expectedResult)
{
var left = (StringValue?)one;
var right = (StringValue?)two;
Assert.Equal(expectedResult > 0, left > right);
Assert.Equal(expectedResult <= 0, left <= right);
}
[Theory]
[InlineData(null, null, 0)]
[InlineData(null, "", -1)]
[InlineData("", null, +1)]
[InlineData("", "", 0)]
[InlineData("", "A", -1)]
[InlineData("A", "", +1)]
[InlineData("A", "a", 0)]
[InlineData("a", "A", 0)]
[InlineData("A", "B", -1)]
[InlineData("AA", "A", +1)]
public void LessThan_WithIgnoreCaseString_ShouldReturnExpectedResult(string? one, string? two, int expectedResult)
{
var left = (StringValue?)one;
var right = (StringValue?)two;
Assert.Equal(expectedResult < 0, left < right);
Assert.Equal(expectedResult >= 0, left >= right);
}
[Theory]
[InlineData(null, null)]
[InlineData(0, 0)]
[InlineData(1, 1)]
public void CastToUnderlyingType_Regularly_ShouldReturnExpectedResult(int? value, int? expectedResult)
{
var instance = value is null ? null : new IntValue(value.Value);
if (expectedResult is null)
Assert.Throws<NullReferenceException>(() => (int)instance!);
else
Assert.Equal(expectedResult, (int)instance!);
}
[Theory]
[InlineData(null, null)]
[InlineData(0, 0)]
[InlineData(1, 1)]
public void CastToNullableUnderlyingType_Regularly_ShouldReturnExpectedResult(int? value, int? expectedResult)
{
var instance = value is null ? null : new IntValue(value.Value);
var result = (int?)instance;
Assert.Equal(expectedResult, result);
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 1)]
public void CastFromUnderlyingType_Regularly_ShouldReturnExpectedResult(int value, int expectedResult)
{
Assert.Equal(new IntValue(expectedResult), (IntValue)value);
}
[Theory]
[InlineData(null, null)]
[InlineData(0, 0)]
[InlineData(1, 1)]
public void CastFromNullableUnderlyingType_Regularly_ShouldReturnExpectedResult(int? value, int? expectedResult)
{
var result = (IntValue?)value;
Assert.Equal(expectedResult, result?.Value);
}
[Theory]
[InlineData(null)]
[InlineData(0)]
[InlineData(1)]
public void SerializeWithSystemTextJson_Regularly_ShouldReturnExpectedResult(int? value)
{
var intInstance = (IntValue?)value;
Assert.Equal(value?.ToString() ?? "null", System.Text.Json.JsonSerializer.Serialize(intInstance));
var stringInstance = (StringValue?)value?.ToString();
Assert.Equal(value is null ? "null" : $@"""{value}""", System.Text.Json.JsonSerializer.Serialize(stringInstance));
// Even with nested identity and/or wrapper value objects, no constructors should be hit
var nestedInstance = value is null ? null : new JsonTestingStringWrapper(value.ToString()!, false);
Assert.Equal(value is null ? "null" : $@"""{value}""", System.Text.Json.JsonSerializer.Serialize(nestedInstance));
}
[Theory]
[InlineData(null)]
[InlineData(0)]
[InlineData(1)]
public void SerializeWithNewtonsoftJson_Regularly_ShouldReturnExpectedResult(int? value)
{
var intInstance = (IntValue?)value;
Assert.Equal(value?.ToString() ?? "null", Newtonsoft.Json.JsonConvert.SerializeObject(intInstance));
var stringInstance = (StringValue?)value?.ToString();
Assert.Equal(value is null ? "null" : $@"""{value}""", Newtonsoft.Json.JsonConvert.SerializeObject(stringInstance));
// Even with nested identity and/or wrapper value objects, no constructors should be hit
var nestedInstance = value is null ? null : new JsonTestingStringWrapper(value.ToString()!, false);
Assert.Equal(value is null ? "null" : $@"""{value}""", Newtonsoft.Json.JsonConvert.SerializeObject(nestedInstance));
}
/// <summary>
/// ValueObjects should (de)serialize decimals normally, which is the most expected behavior.
/// Some special-casing exists only for generated identities.
/// </summary>
[Theory]
[InlineData(null)]
[InlineData(0)]
[InlineData(1)]
public void SerializeWithSystemTextJson_WithDecimal_ShouldReturnExpectedResult(int? value)
{
// Attempt to mess with the stringification, which should have no effect
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
var instance = (DecimalValue?)value;
Assert.Equal(value?.ToString() ?? "null", System.Text.Json.JsonSerializer.Serialize(instance));
}
/// <summary>
/// ValueObjects should (de)serialize decimals normally, which is the most expected behavior.
/// Some special-casing exists only for generated identities.
/// </summary>
[Theory]
[InlineData(null)]
[InlineData(0)]
[InlineData(1)]
public void SerializeWithNewtonsoftJson_WithDecimal_ShouldReturnExpectedResult(int? value)
{
// Attempt to mess with the stringification, which should have no effect
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("nl-NL");
var instance = (DecimalValue?)value;
// Newtonsoft appends ".0" for some reason
Assert.Equal(value is null ? "null" : $"{value}.0", Newtonsoft.Json.JsonConvert.SerializeObject(instance));
}
[Theory]
[InlineData("null", null)]
[InlineData("0", 0)]
[InlineData("1", 1)]
public void DeserializeWithSystemTextJson_Regularly_ShouldReturnExpectedResult(string json, int? value)
{
Assert.Equal(value, System.Text.Json.JsonSerializer.Deserialize<IntValue>(json)?.Value);
json = json == "null" ? json : $@"""{json}""";
Assert.Equal(value?.ToString(), System.Text.Json.JsonSerializer.Deserialize<StringValue>(json)?.Value);
// Even with nested identity and/or wrapper value objects, no constructors should be hit
Assert.Equal(value?.ToString(), json == "null" ? null : System.Text.Json.JsonSerializer.Deserialize<JsonTestingNestedStringWrapper>(json)?.Value.Value?.Value);
}
[Theory]
[InlineData("null", null)]
[InlineData("0", 0)]
[InlineData("1", 1)]
public void DeserializeWithNewtonsoftJson_Regularly_ShouldReturnExpectedResult(string json, int? value)
{
Assert.Equal(value, Newtonsoft.Json.JsonConvert.DeserializeObject<IntValue>(json)?.Value);
json = json == "null" ? json : $@"""{json}""";
Assert.Equal(value?.ToString(), Newtonsoft.Json.JsonConvert.DeserializeObject<StringValue>(json)?.Value);
// Even with nested identity and/or wrapper value objects, no constructors should be hit
Assert.Equal(value?.ToString(), json == "null" ? null : Newtonsoft.Json.JsonConvert.DeserializeObject<JsonTestingNestedStringWrapper>(json)?.Value.Value?.Value);
}
/// <summary>
/// ValueObjects should (de)serialize decimals normally, which is the most expected behavior.
/// Some special-casing exists only for generated identities.
/// </summary>
[Theory]
[InlineData("null", null)]
[InlineData("0", 0)]
[InlineData("1", 1)]
public void DeserializeWithSystemTextJson_WithDecimal_ShouldReturnExpectedResult(string json, int? value)
{
// Attempt to mess with the deserialization, which should have no effect
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("nl-NL");
Assert.Equal(value, System.Text.Json.JsonSerializer.Deserialize<DecimalValue>(json)?.Value);
}
/// <summary>
/// ValueObjects should (de)serialize decimals normally, which is the most expected behavior.
/// Some special-casing exists only for generated identities.
/// </summary>
[Theory]
[InlineData("null", null)]
[InlineData("0", 0)]
[InlineData("1", 1)]
public void DeserializeWithNewtonsoftJson_WithDecimal_ShouldReturnExpectedResult(string json, int? value)
{
// Attempt to mess with the deserialization, which should have no effect
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Assert.Equal(value, Newtonsoft.Json.JsonConvert.DeserializeObject<DecimalValue>(json)?.Value);
}
[Theory]
[InlineData("0", 0)]
[InlineData("1", 1)]
public void ReadAsPropertyNameWithSystemTextJson_Regularly_ShouldReturnExpectedResult(string json, int value)
{
json = $$"""{ "{{json}}": true }""";
Assert.Equal(KeyValuePair.Create((IntValue)value, true), System.Text.Json.JsonSerializer.Deserialize<Dictionary<IntValue, bool>>(json)?.Single());
Assert.Equal(KeyValuePair.Create((StringValue)value.ToString(), true), System.Text.Json.JsonSerializer.Deserialize<Dictionary<StringValue, bool>>(json)?.Single());
Assert.Equal(KeyValuePair.Create((DecimalValue)value, true), System.Text.Json.JsonSerializer.Deserialize<Dictionary<DecimalValue, bool>>(json)?.Single());
// Even with nested identity and/or wrapper value objects, no constructors should be hit
Assert.Equal(KeyValuePair.Create(new JsonTestingStringWrapper(value.ToString(), false), true), System.Text.Json.JsonSerializer.Deserialize<Dictionary<JsonTestingStringWrapper, bool>>(json)?.Single());
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void WriteAsPropertyNameWithSystemTextJson_Regularly_ShouldReturnExpectedResult(int value)
{
var expectedResult = $$"""{"{{value}}":true}""";
Assert.Equal(expectedResult, System.Text.Json.JsonSerializer.Serialize(new Dictionary<IntValue, bool>() { [(IntValue)value] = true }));
Assert.Equal(expectedResult, System.Text.Json.JsonSerializer.Serialize(new Dictionary<StringValue, bool>() { [(StringValue)value.ToString()] = true }));
Assert.Equal(expectedResult, System.Text.Json.JsonSerializer.Serialize(new Dictionary<DecimalValue, bool>() { [(DecimalValue)value] = true }));
// Even with nested identity and/or wrapper value objects, no constructors should be hit
Assert.Equal(expectedResult, System.Text.Json.JsonSerializer.Serialize(new Dictionary<JsonTestingStringWrapper, bool>() { [new JsonTestingStringWrapper(value.ToString(), false)] = true }));
}
[Fact]
public void FormattableToString_InAllScenarios_ShouldReturnExpectedResult()
{
Assert.Equal("5", new IntValue(5).ToString(format: null, formatProvider: null));
Assert.Equal("5", new StringValue("5").ToString(format: null, formatProvider: null));
Assert.Equal("5", new FullySelfImplementedWrapperValueObject(5).ToString(format: null, formatProvider: null));
Assert.Equal("5", new FormatAndParseTestingStringWrapper("5").ToString(format: null, formatProvider: null));
Assert.Equal("", ((StringValue)RuntimeHelpers.GetUninitializedObject(typeof(StringValue))).ToString(format: null, formatProvider: null));
}
[Fact]
public void SpanFormattableTryFormat_InAllScenarios_ShouldReturnExpectedResult()
{
Span<char> result = stackalloc char[1];
Assert.True(new IntValue(5).TryFormat(result, out var charsWritten, format: null, provider: null));
Assert.Equal(1, charsWritten);
Assert.Equal("5".AsSpan(), result);
Assert.True(new StringValue("5").TryFormat(result, out charsWritten, format: null, provider: null));
Assert.Equal(1, charsWritten);
Assert.Equal("5".AsSpan(), result);
Assert.True(new FullySelfImplementedWrapperValueObject(5).TryFormat(result, out charsWritten, format: null, provider: null));
Assert.Equal(1, charsWritten);
Assert.Equal("5".AsSpan(), result);
Assert.True(new FormatAndParseTestingStringWrapper("5").TryFormat(result, out charsWritten, format: null, provider: null));
Assert.Equal(1, charsWritten);
Assert.Equal("5".AsSpan(), result);
Assert.True(((StringValue)RuntimeHelpers.GetUninitializedObject(typeof(StringValue))).TryFormat(result, out charsWritten, format: null, provider: null));
Assert.Equal(0, charsWritten);
}
[Fact]
public void UtfSpanFormattableTryFormat_InAllScenarios_ShouldReturnExpectedResult()
{
Span<byte> result = stackalloc byte[1];
Assert.True(new IntValue(5).TryFormat(result, out var bytesWritten, format: null, provider: null));
Assert.Equal(1, bytesWritten);
Assert.Equal("5"u8, result);
Assert.True(new StringValue("5").TryFormat(result, out bytesWritten, format: null, provider: null));
Assert.Equal(1, bytesWritten);
Assert.Equal("5"u8, result);
Assert.True(new FullySelfImplementedWrapperValueObject(5).TryFormat(result, out bytesWritten, format: null, provider: null));
Assert.Equal(1, bytesWritten);
Assert.Equal("5"u8, result);
Assert.True(new FormatAndParseTestingStringWrapper("5").TryFormat(result, out bytesWritten, format: null, provider: null));
Assert.Equal(1, bytesWritten);
Assert.Equal("5"u8, result);
Assert.True(((StringValue)RuntimeHelpers.GetUninitializedObject(typeof(StringValue))).TryFormat(result, out bytesWritten, format: null, provider: null));
Assert.Equal(0, bytesWritten);
}
[Fact]
public void ParsableTryParseAndParse_InAllScenarios_ShouldReturnExpectedResult()
{
var input = "5";
Assert.True(IntValue.TryParse(input, provider: null, out var result1));
Assert.Equal(5, result1.Value);
Assert.Equal(result1, IntValue.Parse(input, provider: null));
Assert.True(StringValue.TryParse(input, provider: null, out var result2));
Assert.Equal("5", result2.Value);
Assert.Equal(result2, StringValue.Parse(input, provider: null));
Assert.True(FullySelfImplementedWrapperValueObject.TryParse(input, provider: null, out var result3));
Assert.Equal(5, result3.Value);
Assert.Equal(result3, FullySelfImplementedWrapperValueObject.Parse(input, provider: null));
Assert.True(FormatAndParseTestingStringWrapper.TryParse(input, provider: null, out var result4));
Assert.Equal("5", result4.Value?.Value.Value?.Value);
Assert.Equal(result4, FormatAndParseTestingStringWrapper.Parse(input, provider: null));
}
[Fact]
public void SpanParsableTryParseAndParse_InAllScenarios_ShouldReturnExpectedResult()
{
var input = "5".AsSpan();
Assert.True(IntValue.TryParse(input, provider: null, out var result1));
Assert.Equal(5, result1.Value);
Assert.Equal(result1, IntValue.Parse(input, provider: null));
Assert.True(StringValue.TryParse(input, provider: null, out var result2));
Assert.Equal("5", result2.Value);
Assert.Equal(result2, StringValue.Parse(input, provider: null));
Assert.True(FullySelfImplementedWrapperValueObject.TryParse(input, provider: null, out var result3));
Assert.Equal(5, result3.Value);
Assert.Equal(result3, FullySelfImplementedWrapperValueObject.Parse(input, provider: null));
Assert.True(FormatAndParseTestingStringWrapper.TryParse(input, provider: null, out var result4));
Assert.Equal("5", result4.Value?.Value.Value?.Value);
Assert.Equal(result4, FormatAndParseTestingStringWrapper.Parse(input, provider: null));
}
[Fact]
public void Utf8SpanParsableTryParseAndParse_InAllScenarios_ShouldReturnExpectedResult()
{
var input = "5"u8;
Assert.True(IntValue.TryParse(input, provider: null, out var result1));
Assert.Equal(5, result1.Value);
Assert.Equal(result1, IntValue.Parse(input, provider: null));
Assert.True(StringValue.TryParse(input, provider: null, out var result2));
Assert.Equal("5", result2.Value);
Assert.Equal(result2, StringValue.Parse(input, provider: null));
Assert.True(FullySelfImplementedWrapperValueObject.TryParse(input, provider: null, out var result3));
Assert.Equal(5, result3.Value);
Assert.Equal(result3, FullySelfImplementedWrapperValueObject.Parse(input, provider: null));
Assert.True(FormatAndParseTestingStringWrapper.TryParse(input, provider: null, out var result4));
Assert.Equal("5", result4.Value?.Value.Value?.Value);
Assert.Equal(result4, FormatAndParseTestingStringWrapper.Parse(input, provider: null));
}
}
// Use a namespace, since our source generators dislike nested types
namespace WrapperValueObjectTestTypes
{
// Should compile in spite of already consisting of multiple partials, both with and without the attribute
[WrapperValueObject<int>]
public sealed partial class AlreadyPartial
{
}
// Should compile in spite of already consisting of multiple partials, both with and without the attribute
public sealed partial class AlreadyPartial : WrapperValueObject<int>
{
}
// Should compile in spite of already consisting of multiple partials, both with and without the attribute
public partial class AlreadyPartial
{
}
// Should be recognized in spite of the attribute and the base class to be defined on different partials
[WrapperValueObject<int>]
public sealed partial class OtherAlreadyPartial
{
}
// Should be recognized in spite of the attribute and the base class to be defined on different partials
public sealed partial class OtherAlreadyPartial : WrapperValueObject<int>
{
}
[WrapperValueObject<int>]
public sealed partial class WrapperValueObjectWithIIdentity : IIdentity<int>
{
}
[WrapperValueObject<int>]
public sealed partial class IntValue : WrapperValueObject<int>
{
public StringComparison GetStringComparison() => this.StringComparison;
public int Value { get; private init; }
}
[WrapperValueObject<string>]
public sealed partial class StringValue : IComparable<StringValue>
{
protected override StringComparison StringComparison => StringComparison.OrdinalIgnoreCase;
public StringComparison GetStringComparison() => this.StringComparison;
}
[WrapperValueObject<decimal>]
public sealed partial class DecimalValue
{
}
[WrapperValueObject<CustomCollection>]
public sealed partial class CustomCollectionWrapperValueObject
{
public class CustomCollection : IReadOnlyCollection<int>
{
public override int GetHashCode() => 1;
public override bool Equals(object? other) => true;
public int Count => throw new NotSupportedException();
public IEnumerator<int> GetEnumerator() => throw new NotSupportedException();
IEnumerator IEnumerable.GetEnumerator() => throw new NotSupportedException();
public string Value { get; }
public CustomCollection(string value)
{
this.Value = value ?? throw new ArgumentNullException(nameof(value));
}
}
}
/// <summary>
/// Should merely compile.
/// </summary>
[WrapperValueObject<string[]>]
public sealed partial class StringArrayValue
{
}
/// <summary>
/// Should merely compile.
/// </summary>
[WrapperValueObject<decimal?[]>]
public sealed partial class DecimalArrayValue : WrapperValueObject<decimal?[]>
{
}
[WrapperValueObject<FormatAndParseTestingNestedStringWrapper>]
internal partial class FormatAndParseTestingStringWrapper
{
public FormatAndParseTestingStringWrapper(string value)
{
this.Value = new FormatAndParseTestingNestedStringWrapper(new FormatAndParseTestingStringId(new StringValue(value)));
}
}
[WrapperValueObject<FormatAndParseTestingStringId>]
internal partial class FormatAndParseTestingNestedStringWrapper
{
}
[IdentityValueObject<StringValue>]
internal partial struct FormatAndParseTestingStringId : IComparable<FormatAndParseTestingStringId>
{
}
[WrapperValueObject<JsonTestingNestedStringWrapper>]
internal partial class JsonTestingStringWrapper
{
public JsonTestingStringWrapper(JsonTestingNestedStringWrapper _)
{
throw new Exception("This constructor should not be used. This lets tests confirm that concerns such as deserialization correctly avoid constructors.");
}
public JsonTestingStringWrapper(string value, bool _)
{
this.Value = new JsonTestingNestedStringWrapper(value, false);
}
public string ToString(string? format, IFormatProvider? formatProvider)
{
throw new Exception("Serialization should have delegated to the wrapped value.");
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
{
throw new Exception("Serialization should have delegated to the wrapped value.");
}
public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
{
throw new Exception("Serialization should have delegated to the wrapped value.");
}
}
[WrapperValueObject<JsonTestingStringId>]
internal partial class JsonTestingNestedStringWrapper
{
public JsonTestingNestedStringWrapper(JsonTestingStringId _)
{
throw new Exception("This constructor should not be used. This lets tests confirm that concerns such as deserialization correctly avoid constructors.");
}
public JsonTestingNestedStringWrapper(string value, bool _)
{
this.Value = new JsonTestingStringId(value, false);
}
public string ToString(string? format, IFormatProvider? formatProvider)
{
throw new Exception("Serialization should have delegated to the wrapped value.");
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
{
throw new Exception("Serialization should have delegated to the wrapped value.");
}
public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
{
throw new Exception("Serialization should have delegated to the wrapped value.");
}
}
[IdentityValueObject<StringValue>]
internal partial struct JsonTestingStringId : IComparable<JsonTestingStringId>
{
public JsonTestingStringId(StringValue? _)
{
throw new Exception("This constructor should not be used. This lets tests confirm that concerns such as deserialization correctly avoid constructors.");
}
public JsonTestingStringId(string value, bool _)
{
this.Value = new StringValue(value);
}
public string ToString(string? format, IFormatProvider? formatProvider)
{
throw new Exception("Serialization should have delegated to the wrapped value.");
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
{
throw new Exception("Serialization should have delegated to the wrapped value.");
}
public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten, ReadOnlySpan<char> format, IFormatProvider? provider)
{
throw new Exception("Serialization should have delegated to the wrapped value.");
}
}
/// <summary>
/// Should merely compile.
/// </summary>
[WrapperValueObject<int>]
[System.Text.Json.Serialization.JsonConverter(typeof(JsonConverter))]
[Newtonsoft.Json.JsonConverter(typeof(NewtonsoftJsonConverter))]
internal sealed partial class FullySelfImplementedWrapperValueObject
: WrapperValueObject<int>,
IComparable<FullySelfImplementedWrapperValueObject>,
#if NET7_0_OR_GREATER
ISpanFormattable,
ISpanParsable<FullySelfImplementedWrapperValueObject>,
#endif
#if NET8_0_OR_GREATER
IUtf8SpanFormattable,
IUtf8SpanParsable<FullySelfImplementedWrapperValueObject>,
#endif
ISerializableDomainObject<FullySelfImplementedWrapperValueObject, int>
{
protected sealed override StringComparison StringComparison => throw new NotSupportedException("This operation applies to string-based value objects only.");
public int Value { get; private init; }
public FullySelfImplementedWrapperValueObject(int value)
{
this.Value = value;
}
[Obsolete("This constructor exists for deserialization purposes only.")]
private FullySelfImplementedWrapperValueObject()
{
}
public sealed override int GetHashCode()
{
return this.Value.GetHashCode();
}
public sealed override bool Equals(object? other)
{
return other is FullySelfImplementedWrapperValueObject otherValue && this.Equals(otherValue);
}
public bool Equals(FullySelfImplementedWrapperValueObject? other)
{
return other is not null && this.Value.Equals(other.Value);
}
public int CompareTo(FullySelfImplementedWrapperValueObject? other)
{
return other is null
? +1
: this.Value.CompareTo(other.Value);
}
public sealed override string ToString()
{
return this.Value.ToString();
}
/// <summary>
/// Serializes a domain object as a plain value.
/// </summary>
int ISerializableDomainObject<FullySelfImplementedWrapperValueObject, int>.Serialize()
{
return this.Value;
}
/// <summary>
/// Deserializes a plain value back into a domain object without any validation.
/// </summary>
static FullySelfImplementedWrapperValueObject ISerializableDomainObject<FullySelfImplementedWrapperValueObject, int>.Deserialize(int value)
{
#pragma warning disable CS0618 // Obsolete constructor is intended for us
return new FullySelfImplementedWrapperValueObject() { Value = value };
#pragma warning restore CS0618
}
public static bool operator ==(FullySelfImplementedWrapperValueObject? left, FullySelfImplementedWrapperValueObject? right) => left is null ? right is null : left.Equals(right);
public static bool operator !=(FullySelfImplementedWrapperValueObject? left, FullySelfImplementedWrapperValueObject? right) => !(left == right);
public static bool operator >(FullySelfImplementedWrapperValueObject? left, FullySelfImplementedWrapperValueObject? right) => left is not null && left.CompareTo(right) > 0;
public static bool operator <(FullySelfImplementedWrapperValueObject? left, FullySelfImplementedWrapperValueObject? right) => left is null ? right is not null : left.CompareTo(right) < 0;
public static bool operator >=(FullySelfImplementedWrapperValueObject? left, FullySelfImplementedWrapperValueObject? right) => !(left < right);
public static bool operator <=(FullySelfImplementedWrapperValueObject? left, FullySelfImplementedWrapperValueObject? right) => !(left > right);
public static explicit operator FullySelfImplementedWrapperValueObject(int value) => new FullySelfImplementedWrapperValueObject(value);
public static implicit operator int(FullySelfImplementedWrapperValueObject instance) => instance.Value;
[return: NotNullIfNotNull(nameof(value))]
public static explicit operator FullySelfImplementedWrapperValueObject?(int? value) => value is null ? null : new FullySelfImplementedWrapperValueObject(value.Value);
[return: NotNullIfNotNull(nameof(instance))]
public static implicit operator int?(FullySelfImplementedWrapperValueObject? instance) => instance?.Value;
#region Formatting & Parsing
#if NET7_0_OR_GREATER
public string ToString(string? format, IFormatProvider? formatProvider) =>
FormattingHelper.ToString(this.Value, format, formatProvider);
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider) =>
FormattingHelper.TryFormat(this.Value, destination, out charsWritten, format, provider);
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [MaybeNullWhen(false)] out FullySelfImplementedWrapperValueObject result) =>
ParsingHelper.TryParse(s, provider, out int value)
? (result = (FullySelfImplementedWrapperValueObject)value) is var _
: !((result = default) is var _);
public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, [MaybeNullWhen(false)] out FullySelfImplementedWrapperValueObject result) =>
ParsingHelper.TryParse(s, provider, out int value)
? (result = (FullySelfImplementedWrapperValueObject)value) is var _
: !((result = default) is var _);
public static FullySelfImplementedWrapperValueObject Parse(string s, IFormatProvider? provider) =>
(FullySelfImplementedWrapperValueObject)ParsingHelper.Parse<int>(s, provider);
public static FullySelfImplementedWrapperValueObject Parse(ReadOnlySpan<char> s, IFormatProvider? provider) =>
(FullySelfImplementedWrapperValueObject)ParsingHelper.Parse<int>(s, provider);
#endif
#if NET8_0_OR_GREATER
public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten, ReadOnlySpan<char> format, IFormatProvider? provider) =>
FormattingHelper.TryFormat(this.Value, utf8Destination, out bytesWritten, format, provider);
public static bool TryParse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, [MaybeNullWhen(false)] out FullySelfImplementedWrapperValueObject result) =>
ParsingHelper.TryParse(utf8Text, provider, out int value)
? (result = (FullySelfImplementedWrapperValueObject)value) is var _
: !((result = default) is var _);
public static FullySelfImplementedWrapperValueObject Parse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider) =>
(FullySelfImplementedWrapperValueObject)ParsingHelper.Parse<int>(utf8Text, provider);
#endif
#endregion
private sealed class JsonConverter : System.Text.Json.Serialization.JsonConverter<FullySelfImplementedWrapperValueObject>
{
public override FullySelfImplementedWrapperValueObject Read(ref System.Text.Json.Utf8JsonReader reader, Type typeToConvert, System.Text.Json.JsonSerializerOptions options) =>
DomainObjectSerializer.Deserialize<FullySelfImplementedWrapperValueObject, int>(System.Text.Json.JsonSerializer.Deserialize<int>(ref reader, options)!);
public override void Write(System.Text.Json.Utf8JsonWriter writer, FullySelfImplementedWrapperValueObject value, System.Text.Json.JsonSerializerOptions options) =>
System.Text.Json.JsonSerializer.Serialize(writer, DomainObjectSerializer.Serialize<FullySelfImplementedWrapperValueObject, int>(value), options);
public override FullySelfImplementedWrapperValueObject ReadAsPropertyName(ref System.Text.Json.Utf8JsonReader reader, Type typeToConvert, System.Text.Json.JsonSerializerOptions options) =>
DomainObjectSerializer.Deserialize<FullySelfImplementedWrapperValueObject, int>(
((System.Text.Json.Serialization.JsonConverter<int>)options.GetConverter(typeof(int))).ReadAsPropertyName(ref reader, typeToConvert, options));
public override void WriteAsPropertyName(System.Text.Json.Utf8JsonWriter writer, FullySelfImplementedWrapperValueObject value, System.Text.Json.JsonSerializerOptions options) =>
((System.Text.Json.Serialization.JsonConverter<int>)options.GetConverter(typeof(int))).WriteAsPropertyName(
writer,
DomainObjectSerializer.Serialize<FullySelfImplementedWrapperValueObject, int>(value)!, options);
}
private sealed class NewtonsoftJsonConverter : Newtonsoft.Json.JsonConverter
{
public override bool CanConvert(Type objectType) =>
objectType == typeof(FullySelfImplementedWrapperValueObject);
public override object? ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object? existingValue, Newtonsoft.Json.JsonSerializer serializer) =>
reader.Value is null && (!typeof(FullySelfImplementedWrapperValueObject).IsValueType || objectType != typeof(FullySelfImplementedWrapperValueObject)) // Null data for a reference type or nullable value type
? (FullySelfImplementedWrapperValueObject?)null
: DomainObjectSerializer.Deserialize<FullySelfImplementedWrapperValueObject, int>(serializer.Deserialize<int>(reader)!);
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object? value, Newtonsoft.Json.JsonSerializer serializer) =>
serializer.Serialize(writer, value is not FullySelfImplementedWrapperValueObject instance ? (object?)null : DomainObjectSerializer.Serialize<FullySelfImplementedWrapperValueObject, int>(instance));
}
}
}
}