-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCodeGroupCacheServiceTests.cs
More file actions
1331 lines (1114 loc) · 54.7 KB
/
Copy pathCodeGroupCacheServiceTests.cs
File metadata and controls
1331 lines (1114 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
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.Globalization;
using CsvHelper;
using CsvHelper.Configuration;
using LantanaGroup.Link.Terminology.Application.Exceptions;
using LantanaGroup.Link.Terminology.Application.Models;
using LantanaGroup.Link.Terminology.Application.Settings;
using LantanaGroup.Link.Terminology.Services;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using Task = System.Threading.Tasks.Task;
namespace UnitTests.Terminology;
public class CodeGroupCacheServiceTests
{
private readonly Mock<ILogger<CodeGroupCacheService>> _loggerMock;
private readonly TerminologyConfig _config;
public CodeGroupCacheServiceTests()
{
_loggerMock = new Mock<ILogger<CodeGroupCacheService>>();
_config = new TerminologyConfig { Path = "/test/path" };
}
// Mirrors the reader LoadCache builds: the optional trailing status column means a
// 2-column CSV has no field at index 2, so missing fields must not be treated as errors.
private static CsvReader CreateCsvReader(string csvData)
{
var config = new CsvConfiguration(CultureInfo.InvariantCulture) { MissingFieldFound = null };
return new CsvReader(new StringReader(csvData), config);
}
[Fact]
public async Task LoadCache_ShouldAttemptToLoadFilesFromEachDirectory()
{
var mockCache = new Mock<IMemoryCache>();
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
// Create test service with mocked file system methods
var mockService = new Mock<CodeGroupCacheService>(
_loggerMock.Object,
mockCache.Object,
mockConfig.Object)
{
CallBase = true
};
mockService
.Setup(s => s.DirectoryExists(It.IsAny<string>()))
.Returns(true);
// Mock directories to return
var testDirectories = new[]
{
"/test/path/dir1",
"/test/path/dir2",
"/test/path/dir3"
};
mockService
.Setup(s => s.GetDirectories(It.IsAny<string>()))
.Returns(testDirectories);
// Setup mock responses for GetFiles to simulate both JSON and CSV files exist
mockService
.Setup(s => s.GetFiles(It.IsAny<string>(), "*.json"))
.Returns(new[] { "test.json" });
mockService
.Setup(s => s.GetFiles(It.IsAny<string>(), "*.csv"))
.Returns(new[] { "test.csv" });
// Mock file content reading to return empty content
mockService
.Setup(s => s.ReadAllTextAsync("test.json"))
.ReturnsAsync("{ \"resourceType\": \"ValueSet\", \"id\": \"valueset\" }");
mockService
.Setup(s => s.ReadAllTextAsync("test.csv"))
.ReturnsAsync("system,code,display\r\n" +
"http://somesystem.com,abcd,Some Code\r\n");
// Act
await mockService.Object.LoadCache();
mockService.Verify(
s => s.DirectoryExists(mockConfig.Object.Value.Path),
Times.Once);
// Assert
// Verify that GetDirectories was called once with the config path
mockService.Verify(
s => s.GetDirectories(mockConfig.Object.Value.Path),
Times.Once);
// Verify that for each directory, both JSON and CSV files were searched
foreach (var dir in testDirectories)
{
mockService.Verify(
s => s.GetFiles(dir, "*.json"),
Times.Once,
$"Failed to search for JSON files in {dir}");
mockService.Verify(
s => s.GetFiles(dir, "*.csv"),
Times.Once,
$"Failed to search for CSV files in {dir}");
}
// Verify that ReadAllTextAsync was called for both file types in each directory
mockService.Verify(
s => s.ReadAllTextAsync(It.IsAny<string>()),
Times.Exactly(testDirectories.Length * 2));
}
[Fact]
public void ProcessCodeSystemCsv_InvalidColumnCount_ThrowsException()
{
var mockCache = new Mock<IMemoryCache>();
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
// Create test service with mocked file system methods
var mockService = new Mock<CodeGroupCacheService>(
_loggerMock.Object,
mockCache.Object,
mockConfig.Object)
{
CallBase = true
};
mockService
.Setup(x => x.SetCodeGroup(It.IsAny<CodeGroup>()));
mockService
.Setup(x => x.SetCodeGroup(It.IsAny<CodeGroup>()));
// Arrange
var codeGroup = new CodeGroup
{
Id = "test-cs",
Type = CodeGroup.CodeGroupTypes.CodeSystem,
Url = "http://test.com/cs",
Version = "1.0"
};
var csvContent = @"code,display,status,extra
123,Test Display,Active,Extra Column";
using var reader = new StringReader(csvContent);
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() =>
mockService.Object.ProcessCodeSystemCsv(codeGroup, csv, CancellationToken.None));
Assert.Contains("CodeSystem CSV must have", ex.Message);
}
[Fact]
public void ProcessValueSetCsv_InvalidColumnCount_ThrowsException()
{
var mockCache = new Mock<IMemoryCache>();
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
// Create test service with mocked file system methods
var mockService = new Mock<CodeGroupCacheService>(
_loggerMock.Object,
mockCache.Object,
mockConfig.Object)
{
CallBase = true
};
// Arrange
var codeGroup = new CodeGroup
{
Id = "test-vs",
Type = CodeGroup.CodeGroupTypes.ValueSet,
Url = "http://test.com/vs",
Version = "1.0"
};
// Four columns (system,code,display,status) is now valid; five columns is not.
var csvContent = @"system,code,display,status,extra
http://test.system,123,Test Display,Active,Extra Value";
using var reader = new StringReader(csvContent);
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() =>
mockService.Object.ProcessValueSetCsv(codeGroup, csv, CancellationToken.None));
Assert.Contains("ValueSet CSV must have", ex.Message);
}
[Fact]
public void ProcessValueSetCsv_WithValidData_CallsSetCodeGroup()
{
var mockCache = new Mock<IMemoryCache>();
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
// Create test service with mocked file system methods
var mockService = new Mock<CodeGroupCacheService>(
_loggerMock.Object,
mockCache.Object,
mockConfig.Object)
{
CallBase = true
};
mockService
.Setup(x => x.SetCodeGroup(It.IsAny<CodeGroup>()))
.Verifiable();
var csvData = "system,code,display\r\n" +
"http://test.system,123,Test Display\r\n" +
"http://test.system,456,Another Display";
// Use the same reader configuration LoadCache builds (MissingFieldFound tolerated), since a
// 3-column value set has no field at the optional status index.
using var csv = CreateCsvReader(csvData);
var codeGroup = new CodeGroup
{
Id = "test-id",
Type = CodeGroup.CodeGroupTypes.ValueSet,
Url = "http://test.valueset",
Version = "1.0",
Resource = new ValueSet
{
Id = "test-id",
Url = "http://test.valueset",
Version = "1.0"
}
};
// Act
mockService.Object.ProcessValueSetCsv(codeGroup, csv, CancellationToken.None);
// Verify that processing resulted in calling SetGroup with correct CodeGroup
mockService.Verify(x => x.SetCodeGroup(It.Is<CodeGroup>(cg =>
cg.Id == "test-id" &&
cg.Type == CodeGroup.CodeGroupTypes.ValueSet &&
cg.Url == "http://test.valueset" &&
cg.Version == "1.0" &&
cg.Codes.ContainsKey("http://test.system") &&
cg.Codes["http://test.system"].Count == 2 &&
cg.Codes["http://test.system"][0].Value == "123" &&
cg.Codes["http://test.system"][0].Display == "Test Display" &&
cg.Codes["http://test.system"][1].Value == "456" &&
cg.Codes["http://test.system"][1].Display == "Another Display")),
Times.Once);
}
[Fact]
public void ProcessValueSetCsv_WithScientificNotationCodes_LogsSingleAggregatedWarning()
{
var mockCache = new Mock<IMemoryCache>();
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var mockService = new Mock<CodeGroupCacheService>(
_loggerMock.Object,
mockCache.Object,
mockConfig.Object)
{
CallBase = true
};
mockService
.Setup(x => x.SetCodeGroup(It.IsAny<CodeGroup>()));
var csvData = "system,code,display\r\n" +
"http://test.system,1e10,One\r\n" +
"http://test.system,123,Two\r\n" +
"http://test.system,2E+05,Three";
using var reader = new StringReader(csvData);
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
var codeGroup = new CodeGroup
{
Id = "test-id",
Type = CodeGroup.CodeGroupTypes.ValueSet,
Url = "http://test.valueset",
Version = "1.0",
Resource = new ValueSet
{
Id = "test-id",
Url = "http://test.valueset",
Version = "1.0"
}
};
mockService.Object.ProcessValueSetCsv(codeGroup, csv, CancellationToken.None);
VerifyScientificNotationWarning(2, "test-id");
}
[Theory]
[InlineData("code,display\r\n" +
"123,Test Display\r\n" +
"456,Another Display")]
[InlineData("code,display,status\r\n" +
"123,Test Display,Active\r\n" +
"456,Another Display,")]
public void ProcessCodeSystemCsv_WithTwoOrThreeColumnHeader_CallsSetCodeGroup(string csvData)
{
var mockCache = new Mock<IMemoryCache>();
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
// Create test service with mocked file system methods
var mockService = new Mock<CodeGroupCacheService>(
_loggerMock.Object,
mockCache.Object,
mockConfig.Object)
{
CallBase = true
};
mockService
.Setup(x => x.SetCodeGroup(It.IsAny<CodeGroup>()))
.Verifiable();
using var csv = CreateCsvReader(csvData);
var codeGroup = new CodeGroup
{
Id = "test-id",
Type = CodeGroup.CodeGroupTypes.CodeSystem,
Url = "http://test.codesystem",
Version = "1.0",
Resource = new CodeSystem
{
Id = "test-id",
Url = "http://test.codesystem",
Version = "1.0"
}
};
// Act
mockService.Object.ProcessCodeSystemCsv(codeGroup, csv, CancellationToken.None);
// Assert - both header shapes yield the same code/display parsing
mockService.Verify(x => x.SetCodeGroup(It.Is<CodeGroup>(cg =>
cg.Id == "test-id" &&
cg.Type == CodeGroup.CodeGroupTypes.CodeSystem &&
cg.Url == "http://test.codesystem" &&
cg.Version == "1.0" &&
cg.Codes.ContainsKey("http://test.codesystem") &&
cg.Codes["http://test.codesystem"].Count == 2 &&
cg.Codes["http://test.codesystem"][0].Value == "123" &&
cg.Codes["http://test.codesystem"][0].Display == "Test Display" &&
cg.Codes["http://test.codesystem"][1].Value == "456" &&
cg.Codes["http://test.codesystem"][1].Display == "Another Display")),
Times.Once);
}
[Fact]
public void ProcessCodeSystemCsv_WithValidData_CallsSetCodeGroup()
{
var mockCache = new Mock<IMemoryCache>();
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
// Create test service with mocked file system methods
var mockService = new Mock<CodeGroupCacheService>(
_loggerMock.Object,
mockCache.Object,
mockConfig.Object)
{
CallBase = true
};
mockService
.Setup(x => x.SetCodeGroup(It.IsAny<CodeGroup>()))
.Verifiable();
var csvData = @"code,display
123,Test Display
456,Another Display";
using var csv = CreateCsvReader(csvData);
var codeGroup = new CodeGroup
{
Id = "test-id",
Type = CodeGroup.CodeGroupTypes.CodeSystem,
Url = "http://test.codesystem",
Version = "1.0",
Resource = new CodeSystem
{
Id = "test-id",
Url = "http://test.codesystem",
Version = "1.0"
}
};
// Act
mockService.Object.ProcessCodeSystemCsv(codeGroup, csv, CancellationToken.None);
// Verify that processing resulted in calling SetGroup with correct CodeGroup
mockService.Verify(x => x.SetCodeGroup(It.Is<CodeGroup>(cg =>
cg.Id == "test-id" &&
cg.Type == CodeGroup.CodeGroupTypes.CodeSystem &&
cg.Url == "http://test.codesystem" &&
cg.Version == "1.0" &&
cg.Codes.ContainsKey("http://test.codesystem") &&
cg.Codes["http://test.codesystem"].Count == 2 &&
cg.Codes["http://test.codesystem"][0].Value == "123" &&
cg.Codes["http://test.codesystem"][0].Display == "Test Display" &&
cg.Codes["http://test.codesystem"][1].Value == "456" &&
cg.Codes["http://test.codesystem"][1].Display == "Another Display")),
Times.Once);
}
[Fact]
public void ProcessCodeSystemCsv_WithScientificNotationCodes_LogsSingleAggregatedWarning()
{
var mockCache = new Mock<IMemoryCache>();
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var mockService = new Mock<CodeGroupCacheService>(
_loggerMock.Object,
mockCache.Object,
mockConfig.Object)
{
CallBase = true
};
mockService
.Setup(x => x.SetCodeGroup(It.IsAny<CodeGroup>()));
var csvData = "code,display\r\n" +
"1e10,One\r\n" +
"123,Two\r\n" +
"2E+05,Three";
using var csv = CreateCsvReader(csvData);
var codeGroup = new CodeGroup
{
Id = "test-id",
Type = CodeGroup.CodeGroupTypes.CodeSystem,
Url = "http://test.codesystem",
Version = "1.0",
Resource = new CodeSystem
{
Id = "test-id",
Url = "http://test.codesystem",
Version = "1.0"
}
};
mockService.Object.ProcessCodeSystemCsv(codeGroup, csv, CancellationToken.None);
VerifyScientificNotationWarning(2, "test-id");
}
[Fact]
public async Task LoadCache_PopulatesCacheWithRetrievableCodeSystem()
{
// Use a real memory cache and the real service (only the file-system seams are
// overridden) so LoadCache/ProcessCodeSystemCsv/SetCodeGroup are all exercised.
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/cs"] = new[] { "cs.json", "cs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["cs.json"] = "{ \"resourceType\": \"CodeSystem\", \"id\": \"test-cs\", " +
"\"url\": \"http://test.codesystem\", \"version\": \"1.0\" }",
["cs.csv"] = "code,display,status\r\n" +
"123,Test Display,Active\r\n" +
"456,Another Display,Inactive\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert - the code group is retrievable from the cache with all its codes.
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.CodeSystem, "http://test.codesystem");
Assert.NotNull(codeGroup);
Assert.Equal("test-cs", codeGroup.Id);
Assert.Equal("1.0", codeGroup.Version);
Assert.True(codeGroup.Codes.ContainsKey("http://test.codesystem"));
var codes = codeGroup.Codes["http://test.codesystem"];
Assert.Equal(2, codes.Count);
Assert.Equal("123", codes[0].Value);
Assert.Equal("Test Display", codes[0].Display);
Assert.Equal(CodeStatus.Active, ((CodeSystemCode)codes[0]).Status);
Assert.Equal("456", codes[1].Value);
Assert.Equal("Another Display", codes[1].Display);
Assert.Equal(CodeStatus.Inactive, ((CodeSystemCode)codes[1]).Status);
}
[Theory]
[InlineData("http://test.codesystem")] // no version
[InlineData("http://test.codesystem|1.0")] // exact version suffix
[InlineData("http://test.codesystem|9.9")] // unknown version -> falls back to latest loaded
public async Task GetCodeGroup_ResolvesCanonicalUrlWithVersionSuffix(string lookupUrl)
{
// HAPI sends versioned canonical URLs (e.g. ".../identifier-use|4.0.1"); the version
// suffix must not prevent the URL from resolving to the cached code group.
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/cs"] = new[] { "cs.json", "cs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["cs.json"] = "{ \"resourceType\": \"CodeSystem\", \"id\": \"test-cs\", " +
"\"url\": \"http://test.codesystem\", \"version\": \"1.0\" }",
["cs.csv"] = "code,display,status\r\n123,Test Display,Active\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
await service.LoadCache();
var codeGroup = service.GetCodeGroup(CodeGroup.CodeGroupTypes.CodeSystem, lookupUrl);
Assert.NotNull(codeGroup);
Assert.Equal("http://test.codesystem", codeGroup.Url);
Assert.Equal("1.0", codeGroup.Version);
}
[Fact]
public async Task LoadCache_BlankStatus_DefaultsToActive()
{
// Use a real memory cache and the real service (only the file-system seams are
// overridden) so LoadCache/ProcessCodeSystemCsv/SetCodeGroup are all exercised.
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/cs"] = new[] { "cs.json", "cs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["cs.json"] = "{ \"resourceType\": \"CodeSystem\", \"id\": \"test-cs\", " +
"\"url\": \"http://test.codesystem\", \"version\": \"1.0\" }",
// Second row has a blank status column, which should default to Active.
["cs.csv"] = "code,display,status\r\n" +
"123,Test Display,Inactive\r\n" +
"456,Another Display,\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert - the blank-status row is loaded as Active.
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.CodeSystem, "http://test.codesystem");
Assert.NotNull(codeGroup);
var codes = codeGroup.Codes["http://test.codesystem"];
Assert.Equal(2, codes.Count);
Assert.Equal("456", codes[1].Value);
Assert.Equal(CodeStatus.Active, ((CodeSystemCode)codes[1]).Status);
}
[Fact]
public async Task LoadCache_NoStatusColumn_AllRowsDefaultToActive()
{
// Use a real memory cache and the real service (only the file-system seams are
// overridden) so LoadCache/ProcessCodeSystemCsv/SetCodeGroup are all exercised.
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/cs"] = new[] { "cs.json", "cs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["cs.json"] = "{ \"resourceType\": \"CodeSystem\", \"id\": \"test-cs\", " +
"\"url\": \"http://test.codesystem\", \"version\": \"1.0\" }",
// No status column at all - every row should default to Active.
["cs.csv"] = "code,display\r\n" +
"123,Test Display\r\n" +
"456,Another Display\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert - every code is loaded as Active.
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.CodeSystem, "http://test.codesystem");
Assert.NotNull(codeGroup);
var codes = codeGroup.Codes["http://test.codesystem"];
Assert.Equal(2, codes.Count);
Assert.All(codes, code => Assert.Equal(CodeStatus.Active, ((CodeSystemCode)code).Status));
}
[Fact]
public async Task LoadCache_MixedCaseStatus_ParsesCaseInsensitively()
{
// Use a real memory cache and the real service (only the file-system seams are
// overridden) so LoadCache/ProcessCodeSystemCsv/SetCodeGroup are all exercised.
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/cs"] = new[] { "cs.json", "cs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["cs.json"] = "{ \"resourceType\": \"CodeSystem\", \"id\": \"test-cs\", " +
"\"url\": \"http://test.codesystem\", \"version\": \"1.0\" }",
// Status values in varied casing must all parse and canonicalize to the enum.
["cs.csv"] = "code,display,status\r\n" +
"123,Test Display,active\r\n" +
"456,Another Display,INACTIVE\r\n" +
"789,Third Display,Inactive\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert - lowercase/uppercase/mixed-case status all load and normalize correctly.
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.CodeSystem, "http://test.codesystem");
Assert.NotNull(codeGroup);
var codes = codeGroup.Codes["http://test.codesystem"];
Assert.Equal(3, codes.Count);
Assert.Equal(CodeStatus.Active, ((CodeSystemCode)codes[0]).Status);
Assert.Equal(CodeStatus.Inactive, ((CodeSystemCode)codes[1]).Status);
Assert.Equal(CodeStatus.Inactive, ((CodeSystemCode)codes[2]).Status);
}
[Theory]
[InlineData("Retired")] // a plausible-looking status that is not one of the two
[InlineData("7")] // numeric: parses as an enum but is not a defined member
[InlineData("!!")]
public async Task LoadCache_CodeSystemUnrecognizedStatus_KeepsTheCodeSystemAndDefaultsTheRow(string badStatus)
{
// Regression guard. The status column used to be read straight into the enum by CsvHelper, whose
// converter throws on anything else - and because the records are enumerated lazily that throw
// escaped ProcessCodeSystemCsv, was swallowed by LoadCache's catch, and cost the WHOLE code system.
// One malformed cell must not delete thousands of good codes, so the row defaults to Active instead
// and the rest of the file loads normally.
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/cs"] = new[] { "cs.json", "cs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["cs.json"] = "{ \"resourceType\": \"CodeSystem\", \"id\": \"test-cs\", " +
"\"url\": \"http://test.codesystem\", \"version\": \"1.0\" }",
["cs.csv"] = "code,display,status\r\n" +
"123,Test Display,Inactive\r\n" +
$"456,Another Display,{badStatus}\r\n" +
"789,Third Display,Inactive\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert - the code system is still cached, and the rows either side of the bad one kept their status.
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.CodeSystem, "http://test.codesystem");
Assert.NotNull(codeGroup);
var codes = codeGroup.Codes["http://test.codesystem"];
Assert.Equal(3, codes.Count);
Assert.Equal(CodeStatus.Inactive, ((CodeSystemCode)codes[0]).Status);
Assert.Equal(CodeStatus.Active, ((CodeSystemCode)codes[1]).Status);
Assert.Equal(CodeStatus.Inactive, ((CodeSystemCode)codes[2]).Status);
VerifyUnrecognizedStatusWarning();
}
[Fact]
public async Task LoadCache_ValueSetUnrecognizedStatus_DefaultsTheRowAndWarns()
{
// The value set loader already defaulted a bad status to Active, but did so silently, so a typo in
// the membership column looked exactly like a code that was meant to stay active. Both loaders now
// default the row AND say what they saw.
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/vs"] = new[] { "vs.json", "vs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["vs.json"] = "{ \"resourceType\": \"ValueSet\", \"id\": \"test-vs\", " +
"\"url\": \"http://test.valueset\", \"version\": \"1.0\" }",
["vs.csv"] = "system,code,display,status\r\n" +
"http://test.system,123,Test Display,Inactive\r\n" +
"http://test.system,456,Another Display,Retired\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.ValueSet, "http://test.valueset");
Assert.NotNull(codeGroup);
var codes = codeGroup.Codes["http://test.system"];
Assert.Equal(2, codes.Count);
Assert.Equal(CodeStatus.Inactive, ((ValueSetCode)codes[0]).Status);
Assert.Equal(CodeStatus.Active, ((ValueSetCode)codes[1]).Status);
VerifyUnrecognizedStatusWarning();
}
/// <summary>
/// Asserts the single per-file warning that names the unparseable status values. It is logged once per
/// code group rather than once per row: these loops run over every code in the file, and a large code
/// system carries hundreds of thousands of them.
/// </summary>
private void VerifyUnrecognizedStatusWarning() =>
_loggerMock.Verify(
x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, _) => v.ToString()!.Contains("unrecognized status")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
[Fact]
public async Task LoadCache_ValueSetWithStatusColumn_LoadsValueSetCodeWithStatus()
{
// A four-column value set file (system,code,display,status) carries its own membership
// status, which is loaded as a ValueSetCode and is authoritative over the code system.
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/vs"] = new[] { "vs.json", "vs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["vs.json"] = "{ \"resourceType\": \"ValueSet\", \"id\": \"test-vs\", " +
"\"url\": \"http://test.valueset\", \"version\": \"1.0\" }",
["vs.csv"] = "system,code,display,status\r\n" +
"http://test.system,123,Test Display,Active\r\n" +
"http://test.system,456,Another Display,Inactive\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert - members are ValueSetCode instances carrying the file's membership status.
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.ValueSet, "http://test.valueset");
Assert.NotNull(codeGroup);
Assert.Equal("test-vs", codeGroup.Id);
var codes = codeGroup.Codes["http://test.system"];
Assert.Equal(2, codes.Count);
Assert.Equal(CodeStatus.Active, ((ValueSetCode)codes[0]).Status);
Assert.Equal(CodeStatus.Inactive, ((ValueSetCode)codes[1]).Status);
}
[Fact]
public async Task LoadCache_ValueSetBlankStatus_DefaultsToActive()
{
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/vs"] = new[] { "vs.json", "vs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["vs.json"] = "{ \"resourceType\": \"ValueSet\", \"id\": \"test-vs\", " +
"\"url\": \"http://test.valueset\", \"version\": \"1.0\" }",
// Second row has a blank status column, which should default to Active.
["vs.csv"] = "system,code,display,status\r\n" +
"http://test.system,123,Test Display,Inactive\r\n" +
"http://test.system,456,Another Display,\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert - the blank-status member is loaded as an Active ValueSetCode.
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.ValueSet, "http://test.valueset");
Assert.NotNull(codeGroup);
var codes = codeGroup.Codes["http://test.system"];
Assert.Equal(2, codes.Count);
Assert.Equal("456", codes[1].Value);
Assert.Equal(CodeStatus.Active, ((ValueSetCode)codes[1]).Status);
}
[Fact]
public async Task LoadCache_ValueSetNoStatusColumn_LoadsPlainCode()
{
// A three-column value set file has no membership status, so its members are plain Code
// instances (not ValueSetCode) and fall back to the code system status when validated.
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/vs"] = new[] { "vs.json", "vs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["vs.json"] = "{ \"resourceType\": \"ValueSet\", \"id\": \"test-vs\", " +
"\"url\": \"http://test.valueset\", \"version\": \"1.0\" }",
["vs.csv"] = "system,code,display\r\n" +
"http://test.system,123,Test Display\r\n" +
"http://test.system,456,Another Display\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert - members are plain Code (no membership status), not ValueSetCode.
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.ValueSet, "http://test.valueset");
Assert.NotNull(codeGroup);
var codes = codeGroup.Codes["http://test.system"];
Assert.Equal(2, codes.Count);
Assert.All(codes, code => Assert.Equal(
typeof(LantanaGroup.Link.Terminology.Application.Models.Code), code.GetType()));
}
[Fact]
public async Task LoadCache_ValueSetMixedCaseStatus_ParsesCaseInsensitively()
{
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/vs"] = new[] { "vs.json", "vs.csv" }
};
var fileContents = new Dictionary<string, string>
{
["vs.json"] = "{ \"resourceType\": \"ValueSet\", \"id\": \"test-vs\", " +
"\"url\": \"http://test.valueset\", \"version\": \"1.0\" }",
["vs.csv"] = "system,code,display,status\r\n" +
"http://test.system,123,Test Display,active\r\n" +
"http://test.system,456,Another Display,INACTIVE\r\n" +
"http://test.system,789,Third Display,Inactive\r\n"
};
var service = new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
// Act
await service.LoadCache();
// Assert - lowercase/uppercase/mixed-case status all load and normalize correctly.
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.ValueSet, "http://test.valueset");
Assert.NotNull(codeGroup);
var codes = codeGroup.Codes["http://test.system"];
Assert.Equal(3, codes.Count);
Assert.Equal(CodeStatus.Active, ((ValueSetCode)codes[0]).Status);
Assert.Equal(CodeStatus.Inactive, ((ValueSetCode)codes[1]).Status);
Assert.Equal(CodeStatus.Inactive, ((ValueSetCode)codes[2]).Status);
}
// Loads two versions of the same code group into a real cache. Defaults to "4.0.9" and
// "4.0.10", where string ordering would wrongly rank "4.0.9" above "4.0.10" but semantic
// ordering ranks "4.0.10" as the latest. Callers can supply other version strings (including
// null, blank, or non-numeric) to exercise the CompareVersions fallback path. Used by the
// "latest version" resolution tests below.
private TestableCodeGroupCacheService BuildTwoVersionService(
IMemoryCache memoryCache, string? versionA = "4.0.9", string? versionB = "4.0.10")
{
var mockConfig = new Mock<IOptions<TerminologyConfig>>();
mockConfig.Setup(x => x.Value).Returns(_config);
var directoryFiles = new Dictionary<string, string[]>
{
["/test/path/v9"] = new[] { "v9.json", "v9.csv" },
["/test/path/v10"] = new[] { "v10.json", "v10.csv" }
};
var fileContents = new Dictionary<string, string>
{
["v9.json"] = BuildCodeSystemJson(versionA),
["v9.csv"] = "code,display,status\r\n123,Test Display,Active\r\n",
["v10.json"] = BuildCodeSystemJson(versionB),
["v10.csv"] = "code,display,status\r\n123,Test Display,Active\r\n"
};
return new TestableCodeGroupCacheService(
_loggerMock.Object, memoryCache, mockConfig.Object, directoryFiles, fileContents);
}
// Builds a minimal CodeSystem document with the given version. A null version omits the
// "version" field entirely (FHIR version is optional), yielding a null CodeGroup.Version.
private static string BuildCodeSystemJson(string? version)
{
var versionField = version is null ? "" : $", \"version\": \"{version}\"";
return "{ \"resourceType\": \"CodeSystem\", \"id\": \"test-cs\", " +
"\"url\": \"http://test.codesystem\"" + versionField + " }";
}
private void VerifyScientificNotationWarning(int expectedCount, string expectedCodeGroupId)
{
_loggerMock.Verify(
x => x.Log(
It.Is<LogLevel>(level => level == LogLevel.Warning),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((state, _) =>
state.ToString()!.Contains($"Found {expectedCount} code(s)") &&
state.ToString()!.Contains($"code group {expectedCodeGroupId}")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
}
[Fact]
public async Task GetCodeGroup_NoVersion_ReturnsSemanticallyLatestVersion()
{
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var service = BuildTwoVersionService(memoryCache);
await service.LoadCache();
var codeGroup = service.GetCodeGroup(
CodeGroup.CodeGroupTypes.CodeSystem, "http://test.codesystem");