-
Notifications
You must be signed in to change notification settings - Fork 349
Expand file tree
/
Copy pathValidateConfigTests.cs
More file actions
1069 lines (920 loc) · 45.4 KB
/
Copy pathValidateConfigTests.cs
File metadata and controls
1069 lines (920 loc) · 45.4 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Core.Models;
using Serilog;
namespace Cli.Tests;
/// <summary>
/// Test for config file initialization.
/// </summary>
[TestClass]
public class ValidateConfigTests
: VerifyBase
{
private MockFileSystem? _fileSystem;
private FileSystemRuntimeConfigLoader? _runtimeConfigLoader;
[TestInitialize]
public void TestInitialize()
{
_fileSystem = FileSystemUtils.ProvisionMockFileSystem();
_runtimeConfigLoader = new FileSystemRuntimeConfigLoader(_fileSystem);
ILoggerFactory loggerFactory = TestLoggerSupport.ProvisionLoggerFactory();
SetLoggerForCliConfigGenerator(loggerFactory.CreateLogger<ConfigGenerator>());
SetCliUtilsLogger(loggerFactory.CreateLogger<Utils>());
}
[TestCleanup]
public void TestCleanup()
{
_fileSystem = null;
_runtimeConfigLoader = null;
// Clear environment variables set in tests.
Environment.SetEnvironmentVariable($"connection-string", null);
Environment.SetEnvironmentVariable($"database-type", null);
Environment.SetEnvironmentVariable($"sp_param1_int", null);
Environment.SetEnvironmentVariable($"sp_param2_bool", null);
// Set output back to the default for other tests.
Console.SetOut(new StreamWriter(Console.OpenStandardOutput())
{
AutoFlush = true
});
Console.SetError(new StreamWriter(Console.OpenStandardError())
{
AutoFlush = true
});
}
/// <summary>
/// This method validates that the IsConfigValid method returns false when the config is invalid.
/// </summary>
[TestMethod]
public void TestConfigWithCustomPropertyAsInvalid()
{
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, CONFIG_WITH_CUSTOM_PROPERTIES);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
bool isConfigValid = ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!);
Assert.IsFalse(isConfigValid);
}
/// <summary>
/// This method verifies that the relationship validation does not cause unhandled
/// exceptions, and that the errors generated include the expected messaging.
/// This case is a regression test due to the metadata needed not always being
/// populated in the SqlMetadataProvider if for example a bad connection string
/// is given.
/// </summary>
[TestMethod]
public void TestErrorHandlingForRelationshipValidationWithNonWorkingConnectionString()
{
// Arrange
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, COMPLETE_CONFIG_WITH_RELATIONSHIPS_NON_WORKING_CONN_STRING);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
StringWriter writer = new();
// Capture console output to get error messaging.
Console.SetError(writer);
// Act
ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!);
string errorMessage = writer.ToString();
// Assert
Assert.IsTrue(errorMessage.Contains(DataApiBuilderException.CONNECTION_STRING_ERROR_MESSAGE));
}
/// <summary>
/// Validates that the IsConfigValid method returns false when a config is passed with
/// both rest and graphQL disabled globally.
/// </summary>
[TestMethod]
public void TestConfigWithInvalidConfigProperties()
{
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, CONFIG_WITH_DISABLED_GLOBAL_REST_GRAPHQL);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
bool isConfigValid = ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!);
Assert.IsFalse(isConfigValid);
}
/// <summary>
/// This method validates that the IsConfigValid method returns false when the config is empty.
/// This is to validate that no exceptions are thrown with validate for failures during config deserialization.
/// </summary>
[TestMethod]
public void TestValidateWithEmptyConfig()
{
// create an empty config file
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, string.Empty);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
try
{
Assert.IsFalse(ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!));
}
catch (Exception ex)
{
Assert.Fail($"Unexpected Exception thrown: {ex.Message}");
}
}
/// <summary>
/// This Test is used to verify that the validate command is able to catch invalid values for the depth-limit property.
/// </summary>
[DataTestMethod]
[DataRow("null", true, DisplayName = "Invalid Value: 'null'. Only integer values are allowed.")]
[DataRow("20", true, DisplayName = "Invalid Value: '20'. Integer values provided as strings are not allowed.")]
[DataRow(0, false, DisplayName = "Invalid Value: 0. Only values between 1 and 2147483647 are allowed along with -1.")]
[DataRow(-2, false, DisplayName = "Invalid Value: -2. Negative values are not allowed except -1.")]
[DataRow(2147483648, false, DisplayName = "Invalid Value: 2147483648. Only values between 1 and 2147483647 are allowed along with -1.")]
[DataRow("seven", true, DisplayName = "Invalid Value: 'seven'. Only integer values are allowed.")]
public void TestValidateConfigFailsWithInvalidGraphQLDepthLimit(object? depthLimit, bool isStringValue)
{
string depthLimitSection = isStringValue ? $@"""depth-limit"": ""{depthLimit}""" : $@"""depth-limit"": {depthLimit}";
string jsonData = TestHelper.GenerateConfigWithGivenDepthLimit(depthLimitSection);
// create an empty config file
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, jsonData);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
try
{
Assert.IsFalse(ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!));
}
catch (Exception ex)
{
Assert.Fail($"Unexpected Exception thrown: {ex.Message}");
}
}
/// <summary>
/// This Test is used to verify that DAB fails when the JWT properties are missing for OAuth based providers
/// </summary>
[DataTestMethod]
[DataRow("AzureAD")]
[DataRow("EntraID")]
[DataRow("Custom")]
public void TestMissingJwtProperties(string authScheme)
{
string ConfigWithJwtAuthentication = $"{{{SAMPLE_SCHEMA_DATA_SOURCE}, {RUNTIME_SECTION_JWT_AUTHENTICATION_PLACEHOLDER}, \"entities\": {{ }}}}";
ConfigWithJwtAuthentication = ConfigWithJwtAuthentication.Replace("<>", authScheme, StringComparison.OrdinalIgnoreCase);
// create an empty config file
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, ConfigWithJwtAuthentication);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
try
{
Assert.IsFalse(ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!));
}
catch (Exception ex)
{
Assert.Fail($"Unexpected Exception thrown: {ex.Message}");
}
}
/// <summary>
/// This Test is used to verify that the validate command is able to catch when data source field or entities field is missing.
/// </summary>
[TestMethod]
public void TestValidateConfigFailsWithNoEntities()
{
string ConfigWithoutEntities = $"{{{SAMPLE_SCHEMA_DATA_SOURCE},{RUNTIME_SECTION}}}";
// create an empty config file
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, ConfigWithoutEntities);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
try
{
Assert.IsFalse(ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!));
}
catch (Exception ex)
{
Assert.Fail($"Unexpected Exception thrown: {ex.Message}");
}
}
/// <summary>
/// Validates that when the config has no entities or autoentities, the config
/// still parses successfully (constructor no longer throws), and IsConfigValid
/// returns false without throwing.
/// Adapted for https://github.com/Azure/data-api-builder/issues/3268
/// </summary>
[TestMethod]
public void TestValidateConfigWithNoEntitiesProducesCleanError()
{
string configWithoutEntities = $"{{{SAMPLE_SCHEMA_DATA_SOURCE},{RUNTIME_SECTION}}}";
// Config with no entities should now parse successfully (validation catches it downstream).
bool parsed = RuntimeConfigLoader.TryParseConfig(configWithoutEntities, out _);
Assert.IsTrue(parsed, "Config with datasource and no entities should parse successfully.");
// IsConfigValid should return false cleanly (no exception thrown).
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, configWithoutEntities);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
Assert.IsFalse(ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!));
}
/// <summary>
/// This Test is used to verify that the validate command is able to catch when data source field is missing.
/// </summary>
[TestMethod]
public void TestValidateConfigFailsWithNoDataSource()
{
string ConfigWithoutDataSource = $"{{{SCHEMA_PROPERTY},{RUNTIME_SECTION_WITH_EMPTY_ENTITIES}}}";
// create an empty config file
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, ConfigWithoutDataSource);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
try
{
Assert.IsFalse(ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!));
}
catch (Exception ex)
{
Assert.Fail($"Unexpected Exception thrown: {ex.Message}");
}
}
/// <summary>
/// This method implicitly validates that RuntimeConfigValidator::ValidateConfigSchema(...) successfully
/// executes against a config file referencing environment variables.
/// [CLI] ConfigGenerator::IsConfigValid(...)
/// |_ [Engine] RuntimeConfigValidator::TryValidateConfig(...)
/// |_ [Engine] RuntimeConfigValidator::ValidateConfigSchema(...)
/// ValidateConfigSchema(...) doesn't execute successfully when a RuntimeConfig object has unresolved environment variables.
/// Example:
/// Input file snipppet:
/// "data-source": {
/// "database-type": "@env('DATABASE_TYPE')", // ENUM
/// "connection-string": "@env('CONN_STRING')" // STRING
/// }
/// ...
/// "source": {
/// "type": ""stored-procedure",
/// "object": "s001.book",
/// "parameters": {
/// "param1": "@env('sp_param1_int')", // INT
/// "param2": "@env('sp_param3_bool')" // BOOL
/// }
/// }
/// </summary>
[TestMethod]
public void ValidateConfigSchemaWhereConfigReferencesEnvironmentVariables()
{
// Arrange
Environment.SetEnvironmentVariable($"connection-string", SAMPLE_TEST_CONN_STRING);
Environment.SetEnvironmentVariable($"database-type", "mssql");
Environment.SetEnvironmentVariable($"sp_param1_int", "123");
Environment.SetEnvironmentVariable($"sp_param3_bool", "true");
// Capture console output to get error messaging.
StringWriter writer = new();
Console.SetOut(writer);
((MockFileSystem)_fileSystem!).AddFile(
path: TEST_RUNTIME_CONFIG_FILE,
mockFile: CONFIG_ENV_VARS);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
// Act
Utils.LoggerFactoryForCli = Utils.GetLoggerFactoryForCli();
ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!);
// Assert
string loggerOutput = writer.ToString();
Assert.IsFalse(
condition: loggerOutput.Contains("Failed to validate config against schema due to"),
message: "Unexpected errors encountered when validating config schema in RuntimeConfigValidator::ValidateConfigSchema(...).");
}
/// <summary>
/// Tests that validation fails when AKV options are configured without an endpoint.
/// </summary>
[TestMethod]
public async Task TestValidateAKVOptionsWithoutEndpointFails()
{
// Arrange
ConfigureOptions options = new(
azureKeyVaultRetryPolicyMaxCount: 1,
azureKeyVaultRetryPolicyDelaySeconds: 1,
azureKeyVaultRetryPolicyMaxDelaySeconds: 1,
azureKeyVaultRetryPolicyMode: AKVRetryPolicyMode.Exponential,
azureKeyVaultRetryPolicyNetworkTimeoutSeconds: 1,
config: TEST_RUNTIME_CONFIG_FILE
);
// Act
await ValidatePropertyOptionsFails(options);
}
/// <summary>
/// Tests that validation fails when Azure Log Analytics options are configured without the Auth options.
/// </summary>
[TestMethod]
public async Task TestValidateAzureLogAnalyticsOptionsWithoutAuthFails()
{
// Arrange
ConfigureOptions options = new(
azureLogAnalyticsEnabled: CliBool.True,
azureLogAnalyticsDabIdentifier: "dab-identifier-test",
azureLogAnalyticsFlushIntervalSeconds: 1,
config: TEST_RUNTIME_CONFIG_FILE
);
// Act
await ValidatePropertyOptionsFails(options);
}
/// <summary>
/// Tests that validation fails when File Sink options are configured without the 'path' property.
/// </summary>
[TestMethod]
public async Task TestValidateFileSinkOptionsWithoutPathFails()
{
// Arrange
ConfigureOptions options = new(
fileSinkEnabled: CliBool.True,
fileSinkRollingInterval: RollingInterval.Day,
fileSinkRetainedFileCountLimit: 1,
fileSinkFileSizeLimitBytes: 1024,
config: TEST_RUNTIME_CONFIG_FILE
);
// Act
await ValidatePropertyOptionsFails(options);
}
/// <summary>
/// Helper function that ensures properties with missing options fail validation.
/// </summary>
private async Task ValidatePropertyOptionsFails(ConfigureOptions options)
{
_fileSystem!.AddFile(TEST_RUNTIME_CONFIG_FILE, new MockFileData(INITIAL_CONFIG));
Assert.IsTrue(_fileSystem!.File.Exists(TEST_RUNTIME_CONFIG_FILE));
Mock<RuntimeConfigProvider> mockRuntimeConfigProvider = new(_runtimeConfigLoader);
RuntimeConfigValidator validator = new(mockRuntimeConfigProvider.Object, _fileSystem, new Mock<ILogger<RuntimeConfigValidator>>().Object);
Mock<ILoggerFactory> mockLoggerFactory = new();
Mock<ILogger<JsonConfigSchemaValidator>> mockLogger = new();
mockLoggerFactory
.Setup(factory => factory.CreateLogger(typeof(JsonConfigSchemaValidator).FullName!))
.Returns(mockLogger.Object);
// Act: Attempts to add File Sink options without empty path
bool isSuccess = TryConfigureSettings(options, _runtimeConfigLoader!, _fileSystem!);
// Assert: Settings are configured, config parses, validation fails.
Assert.IsTrue(isSuccess);
string updatedConfig = _fileSystem!.File.ReadAllText(TEST_RUNTIME_CONFIG_FILE);
Assert.IsTrue(RuntimeConfigLoader.TryParseConfig(updatedConfig, out RuntimeConfig? config));
JsonSchemaValidationResult result = await validator.ValidateConfigSchema(config, TEST_RUNTIME_CONFIG_FILE, mockLoggerFactory.Object);
Assert.IsFalse(result.IsValid);
}
/// <summary>
/// Validates that a non-root config (has data-source but no data-source-files) with zero entities
/// and an invalid connection string gets a connection string validation error.
/// Entity validation is gated on successful DB connectivity, so no entity error fires.
/// The validation still returns false due to the connection string error.
/// Regression test for https://github.com/Azure/data-api-builder/issues/3267
/// </summary>
[TestMethod]
public void TestValidateNonRootZeroEntitiesWithInvalidConnectionString()
{
((MockFileSystem)_fileSystem!).AddFile(TEST_RUNTIME_CONFIG_FILE, INVALID_INTIAL_CONFIG);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
Mock<ILogger<ConfigGenerator>> mockLogger = new();
SetLoggerForCliConfigGenerator(mockLogger.Object);
bool isValid = ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!);
// Validation should fail due to the empty connection string.
Assert.IsFalse(isValid);
}
/// <summary>
/// Tests that logs related to suppressed messages do not appear.
/// </summary>
[TestMethod]
public async Task TestValidateSuppressedLogsDoNotAppear()
{
// Arrange
StringWriter writer = new();
Console.SetOut(writer);
string config = AddPropertiesToJson(INITIAL_CONFIG, SINGLE_ENTITY);
((MockFileSystem)_fileSystem!).AddFile(
path: TEST_RUNTIME_CONFIG_FILE,
mockFile: config);
ValidateOptions validateOptions = new(TEST_RUNTIME_CONFIG_FILE);
// Act
Utils.LoggerFactoryForCli = Utils.GetLoggerFactoryForCli();
ConfigGenerator.IsConfigValid(validateOptions, _runtimeConfigLoader!, _fileSystem!);
// Assert
string loggerOutput = writer.ToString();
Assert.IsTrue(
condition: !loggerOutput.Contains("REST path:"),
message: "RuntimeConfigValidator should not contain any messages indicating REST path for individual entities");
Assert.IsTrue(
condition: !loggerOutput.Contains("REST calls are disabled for the entity:"),
message: "RuntimeConfigValidator should not contain any messages related to REST calls for individual entities");
}
/// <summary>
/// Validates that a root config (with data-source-files pointing to children)
/// that has no data-source and no entities is considered structurally valid
/// for parsing. The root config delegates entity requirements to children.
/// </summary>
[TestMethod]
public void TestRootConfigWithNoDataSourceAndNoEntitiesParses()
{
string rootConfig = @"
{
""$schema"": """ + DAB_DRAFT_SCHEMA_TEST_PATH + @""",
""runtime"": {
""rest"": { ""enabled"": true },
""graphql"": { ""enabled"": true },
""host"": { ""mode"": ""development"" }
},
""data-source-files"": [""child1.json""],
""entities"": {}
}";
// The root config should parse without error (no data-source required for root).
Assert.IsTrue(RuntimeConfigLoader.TryParseConfig(rootConfig, out RuntimeConfig? config));
Assert.IsNotNull(config);
Assert.IsTrue(config.IsRootConfig);
}
/// <summary>
/// Validates that a non-root config with a data-source and no entities parses
/// successfully. Validation of entity presence happens during dab validate,
/// not during parsing.
/// </summary>
[TestMethod]
public void TestNonRootConfigWithDataSourceAndNoEntitiesParses()
{
Assert.IsTrue(RuntimeConfigLoader.TryParseConfig(INITIAL_CONFIG, out RuntimeConfig? config));
Assert.IsNotNull(config);
Assert.IsFalse(config.IsRootConfig);
}
/// <summary>
/// Non-root with datasource and zero entities → error.
/// </summary>
[TestMethod]
public void TestNonRootWithDataSourceAndNoEntitiesProducesError()
{
RuntimeConfig config = BuildTestConfig(hasDataSource: true, entities: new());
RuntimeConfigValidator validator = BuildValidator(config);
validator.ValidateDataSourceAndEntityPresence(config);
Assert.IsTrue(validator.ConfigValidationExceptions.Count > 0,
"Expected validation error for non-root config with datasource but no entities.");
}
/// <summary>
/// Non-root with no datasource → error.
/// </summary>
[TestMethod]
public void TestNonRootWithNoDataSourceProducesError()
{
RuntimeConfig config = BuildTestConfig(hasDataSource: false, entities: new());
RuntimeConfigValidator validator = BuildValidator(config);
validator.ValidateDataSourceAndEntityPresence(config);
Assert.AreEqual(1, validator.ConfigValidationExceptions.Count);
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("data source is required"));
}
/// <summary>
/// Non-root with datasource and entities → valid.
/// </summary>
[TestMethod]
public void TestNonRootWithDataSourceAndEntitiesIsValid()
{
RuntimeConfig config = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Book", BuildSimpleEntity("dbo.books") } });
RuntimeConfigValidator validator = BuildValidator(config);
validator.ValidateDataSourceAndEntityPresence(config);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count);
}
/// <summary>
/// Root with no datasource and no entities → valid (children carry the load).
/// </summary>
[TestMethod]
public void TestRootWithNoDataSourceAndNoEntitiesIsValid()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Book", BuildSimpleEntity("dbo.books") } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false, entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child.json" }));
rootConfig.ChildConfigs.Add(("child.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count);
}
/// <summary>
/// Root with no datasource but with entities → error (entities need a datasource).
/// </summary>
[TestMethod]
public void TestRootWithNoDataSourceButEntitiesProducesError()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Author", BuildSimpleEntity("dbo.authors") } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false,
entities: new() { { "Book", BuildSimpleEntity("dbo.books") } },
dataSourceFiles: new DataSourceFiles(new[] { "child.json" }));
rootConfig.ChildConfigs.Add(("child.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.IsTrue(validator.ConfigValidationExceptions.Count > 0);
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("must not define entities"));
}
/// <summary>
/// Root with datasource and entities → valid (follows normal entity rules).
/// </summary>
[TestMethod]
public void TestRootWithDataSourceAndEntitiesIsValid()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Author", BuildSimpleEntity("dbo.authors") } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Book", BuildSimpleEntity("dbo.books") } },
dataSourceFiles: new DataSourceFiles(new[] { "child.json" }));
rootConfig.ChildConfigs.Add(("child.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count);
}
/// <summary>
/// Child config with datasource but no entities → error naming the child file.
/// </summary>
[TestMethod]
public void TestChildWithDataSourceAndNoEntitiesProducesNamedError()
{
RuntimeConfig childConfig = BuildTestConfig(hasDataSource: true, entities: new());
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false, entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child-db.json" }));
rootConfig.ChildConfigs.Add(("child-db.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(1, validator.ConfigValidationExceptions.Count);
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("child-db.json"),
"Error should name the child config file.");
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("No entities found"),
"Error should mention no entities found.");
}
/// <summary>
/// Child config with no datasource → error naming the child file.
/// </summary>
[TestMethod]
public void TestChildWithNoDataSourceProducesNamedError()
{
RuntimeConfig childConfig = BuildTestConfig(hasDataSource: false, entities: new());
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false, entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child-db.json" }));
rootConfig.ChildConfigs.Add(("child-db.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(1, validator.ConfigValidationExceptions.Count);
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("child-db.json"));
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("data source is required"));
}
/// <summary>
/// Non-root with datasource and only autoentities that resolve zero entities → error
/// ("No entities found"). Covers truth-table row 6 (DSF=0, DS=1, E=0, AE=1, resolved=0).
/// </summary>
[TestMethod]
public void TestNonRootWithDataSourceAndAutoentitiesResolvingZeroProducesError()
{
RuntimeConfig config = BuildTestConfig(
hasDataSource: true,
entities: new(),
autoentities: new() { { "ae1", BuildSimpleAutoentity() } },
autoentityResolutionCounts: new() { { "ae1", 0 } });
RuntimeConfigValidator validator = BuildValidator(config);
validator.ValidateDataSourceAndEntityPresence(config);
Assert.AreEqual(1, validator.ConfigValidationExceptions.Count);
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("No entities found"));
}
/// <summary>
/// Non-root with datasource and only autoentities that resolve to >0 entities → valid.
/// Covers truth-table row 6 (DSF=0, DS=1, E=0, AE=1, resolved>0).
/// </summary>
[TestMethod]
public void TestNonRootWithDataSourceAndAutoentitiesResolvingEntitiesIsValid()
{
RuntimeConfig config = BuildTestConfig(
hasDataSource: true,
entities: new(),
autoentities: new() { { "ae1", BuildSimpleAutoentity() } },
autoentityResolutionCounts: new() { { "ae1", 3 } });
RuntimeConfigValidator validator = BuildValidator(config);
validator.ValidateDataSourceAndEntityPresence(config);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count);
}
/// <summary>
/// Non-root with manual entities AND autoentities that resolve zero → valid, but a warning
/// is emitted. Covers truth-table row 8 (DSF=0, DS=1, E=1, AE=1, resolved=0).
/// </summary>
[TestMethod]
public void TestNonRootWithEntitiesAndAutoentitiesResolvingZeroLogsWarning()
{
RuntimeConfig config = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Book", BuildSimpleEntity("dbo.books") } },
autoentities: new() { { "ae1", BuildSimpleAutoentity() } },
autoentityResolutionCounts: new() { { "ae1", 0 } });
RuntimeConfigValidator validator = BuildValidator(config, out Mock<ILogger<RuntimeConfigValidator>> loggerMock);
validator.ValidateDataSourceAndEntityPresence(config);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count);
VerifyAutoentityZeroDiscoveredWarning(loggerMock, expectedFileNameInMessage: null);
}
/// <summary>
/// Root config (DSF=1) with no data-source but with autoentities defined → error.
/// Covers truth-table row 10 (DSF=1, DS=0, E=0, AE=1).
/// </summary>
[TestMethod]
public void TestRootWithNoDataSourceButAutoentitiesProducesError()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Author", BuildSimpleEntity("dbo.authors") } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false,
entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child.json" }),
autoentities: new() { { "ae1", BuildSimpleAutoentity() } });
rootConfig.ChildConfigs.Add(("child.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.IsTrue(validator.ConfigValidationExceptions.Count > 0);
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("must not define entities"));
}
/// <summary>
/// Root config with its own data-source but zero entities and zero autoentities → error.
/// When a root config defines a data-source, normal entity rules apply at the root.
/// Covers truth-table row 13 (DSF=1, DS=1, E=0, AE=0).
/// </summary>
[TestMethod]
public void TestRootWithDataSourceAndNoEntitiesProducesError()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Author", BuildSimpleEntity("dbo.authors") } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: true,
entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child.json" }));
rootConfig.ChildConfigs.Add(("child.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.IsTrue(validator.ConfigValidationExceptions.Any(e => e.Message.Contains("No entities found")),
"Expected 'No entities found' error on root with own data-source and zero entities.");
}
/// <summary>
/// Root config with its own data-source and autoentities that resolve zero → error.
/// Covers truth-table row 14 (DSF=1, DS=1, E=0, AE=1, resolved=0).
/// </summary>
[TestMethod]
public void TestRootWithDataSourceAndAutoentitiesResolvingZeroProducesError()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Author", BuildSimpleEntity("dbo.authors") } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: true,
entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child.json" }),
autoentities: new() { { "ae1", BuildSimpleAutoentity() } },
autoentityResolutionCounts: new() { { "ae1", 0 } });
rootConfig.ChildConfigs.Add(("child.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.IsTrue(validator.ConfigValidationExceptions.Any(e => e.Message.Contains("No entities found")));
}
/// <summary>
/// Root config with its own data-source and autoentities that resolve to >0 entities → valid.
/// Covers truth-table row 14 (DSF=1, DS=1, E=0, AE=1, resolved>0).
/// </summary>
[TestMethod]
public void TestRootWithDataSourceAndAutoentitiesResolvingEntitiesIsValid()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Author", BuildSimpleEntity("dbo.authors") } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: true,
entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child.json" }),
autoentities: new() { { "ae1", BuildSimpleAutoentity() } },
autoentityResolutionCounts: new() { { "ae1", 5 } });
rootConfig.ChildConfigs.Add(("child.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count);
}
/// <summary>
/// Root config with manual entities AND autoentities that resolve zero → valid, but a warning
/// is emitted at the root level. Covers truth-table row 16 (DSF=1, DS=1, E=1, AE=1, resolved=0).
/// </summary>
[TestMethod]
public void TestRootWithEntitiesAndAutoentitiesResolvingZeroLogsWarning()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Author", BuildSimpleEntity("dbo.authors") } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Book", BuildSimpleEntity("dbo.books") } },
dataSourceFiles: new DataSourceFiles(new[] { "child.json" }),
autoentities: new() { { "ae1", BuildSimpleAutoentity() } },
autoentityResolutionCounts: new() { { "ae1", 0 } });
rootConfig.ChildConfigs.Add(("child.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig, out Mock<ILogger<RuntimeConfigValidator>> loggerMock);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count);
VerifyAutoentityZeroDiscoveredWarning(loggerMock, expectedFileNameInMessage: null);
}
/// <summary>
/// Child config with its own data-source and only autoentities that resolve zero → error
/// naming the child file. Covers child truth-table row C4 (DS=1, E=0, AE=1, resolved=0).
/// </summary>
[TestMethod]
public void TestChildWithDataSourceAndAutoentitiesResolvingZeroProducesNamedError()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new(),
autoentities: new() { { "ae1", BuildSimpleAutoentity() } },
autoentityResolutionCounts: new() { { "ae1", 0 } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false, entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child-db.json" }));
rootConfig.ChildConfigs.Add(("child-db.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(1, validator.ConfigValidationExceptions.Count);
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("child-db.json"),
"Error should name the child config file.");
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("No entities found"),
"Error should mention no entities found.");
}
/// <summary>
/// Child config with manual entities AND autoentities that resolve zero → valid, but a
/// warning naming the child file is emitted. Covers child truth-table row C6
/// (DS=1, E=1, AE=1, resolved=0).
/// </summary>
[TestMethod]
public void TestChildWithEntitiesAndAutoentitiesResolvingZeroLogsNamedWarning()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new() { { "Book", BuildSimpleEntity("dbo.books") } },
autoentities: new() { { "ae1", BuildSimpleAutoentity() } },
autoentityResolutionCounts: new() { { "ae1", 0 } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false, entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child-db.json" }));
rootConfig.ChildConfigs.Add(("child-db.json", childConfig));
RuntimeConfigValidator validator = BuildValidator(rootConfig, out Mock<ILogger<RuntimeConfigValidator>> loggerMock);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count);
VerifyAutoentityZeroDiscoveredWarning(loggerMock, expectedFileNameInMessage: "child-db.json");
}
/// <summary>
/// Child config with only autoentities that resolve to >0 entities is valid.
/// Simulates the production code path where the metadata provider stores resolution
/// counts on the root (merged) config rather than on the child config directly.
/// This is the regression test for the bug where child-config autoentities caused
/// "No entities found" even when they were expanded successfully.
/// Covers child truth-table row C5 (DS=1, E=0, AE=1, resolved>0, counts on root).
/// </summary>
[TestMethod]
public void TestChildWithDataSourceAndAutoentitiesResolvingEntitiesIsValid()
{
// Child has no explicit entities; only autoentities.
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new(),
autoentities: new() { { "ae1", BuildSimpleAutoentity() } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false, entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child-db.json" }));
rootConfig.ChildConfigs.Add(("child-db.json", childConfig));
// Simulate production: metadata provider stores counts in the root config,
// NOT directly on the child config.
rootConfig.AutoentityResolutionCounts["ae1"] = 3;
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count,
"Child config with autoentities that resolved entities should pass validation.");
}
/// <summary>
/// Both root and child configs have autoentities that resolve to >0 entities.
/// Resolution counts for both are stored only on the root config (as the metadata
/// provider does at runtime). Validation must pass for both configs.
/// </summary>
[TestMethod]
public void TestRootAndChildBothWithAutoentitiesResolvingEntitiesIsValid()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new(),
autoentities: new() { { "child-ae", BuildSimpleAutoentity() } });
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: true,
entities: new(),
dataSourceFiles: new DataSourceFiles(new[] { "child-db.json" }),
autoentities: new() { { "root-ae", BuildSimpleAutoentity() } });
rootConfig.ChildConfigs.Add(("child-db.json", childConfig));
// Simulate production: metadata provider stores ALL counts in the root config.
rootConfig.AutoentityResolutionCounts["root-ae"] = 2;
rootConfig.AutoentityResolutionCounts["child-ae"] = 4;
RuntimeConfigValidator validator = BuildValidator(rootConfig);
validator.ValidateDataSourceAndEntityPresence(rootConfig);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count,
"Root and child configs both with autoentities that resolved entities should pass validation.");
}
/// <summary>
/// Helper: verifies that the autoentity-discovered-zero warning was logged at least once,
/// optionally also checking that the formatted message contains a child config file name.
/// </summary>
private static void VerifyAutoentityZeroDiscoveredWarning(
Mock<ILogger<RuntimeConfigValidator>> loggerMock,
string? expectedFileNameInMessage)
{
const string FRAGMENT = "Autoentities are configured but no entities were discovered";
// Using string.Empty when no file name is expected makes Contains() always true,
// letting us keep a single Moq expression tree (which can't use 'is null').
string fileFragment = expectedFileNameInMessage ?? string.Empty;
loggerMock.Verify(
x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((o, t) =>
o.ToString()!.Contains(FRAGMENT)
&& o.ToString()!.Contains(fileFragment)),
It.IsAny<Exception>(),
(Func<It.IsAnyType, Exception?, string>)It.IsAny<object>()),
Times.AtLeastOnce);
}
/// <summary>
/// Helper: builds a RuntimeConfigValidator in validate-only mode over the given config.
/// </summary>
private static RuntimeConfigValidator BuildValidator(RuntimeConfig config)
=> BuildValidator(config, out _);
/// <summary>
/// Helper: builds a RuntimeConfigValidator in validate-only mode and exposes its logger mock
/// so the test can verify warning calls.
/// </summary>
private static RuntimeConfigValidator BuildValidator(
RuntimeConfig config,
out Mock<ILogger<RuntimeConfigValidator>> loggerMock)
{
MockFileSystem fs = new();
FileSystemRuntimeConfigLoader loader = new(fs) { RuntimeConfig = config };
RuntimeConfigProvider provider = new(loader);
loggerMock = new();
return new RuntimeConfigValidator(provider, fs, loggerMock.Object, isValidateOnly: true);
}
/// <summary>
/// Helper: builds a minimal RuntimeConfig for testing.
/// </summary>