-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathValidateConfigTests.cs
More file actions
612 lines (527 loc) · 24.4 KB
/
ValidateConfigTests.cs
File metadata and controls
612 lines (527 loc) · 24.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
// 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);
}
/// <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.SetOut(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>
/// 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
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(...).");
Assert.IsTrue(
condition: loggerOutput.Contains("The config satisfies the schema requirements."),
message: "RuntimeConfigValidator::ValidateConfigSchema(...) didn't communicate successful config schema validation.");
}
/// <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>
/// 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>
/// Validates that a non-root config with a data source but no entities
/// produces a validation error from ValidateDataSourceAndEntityPresence.
/// </summary>
[TestMethod]
public void TestNonRootWithDataSourceAndNoEntitiesProducesError()
{
RuntimeConfig config = BuildTestConfig(
hasDataSource: true,
entities: new Dictionary<string, Entity>());
RuntimeConfigValidator validator = BuildValidator(config);
validator.ValidateDataSourceAndEntityPresence(config);
Assert.AreEqual(1, validator.ConfigValidationExceptions.Count);
Assert.IsTrue(validator.ConfigValidationExceptions[0].Message.Contains("no entities found"));
}
/// <summary>
/// Validates that a non-root config with no data source
/// produces a validation error requiring a data source.
/// </summary>
[TestMethod]
public void TestNonRootWithNoDataSourceProducesError()
{
RuntimeConfig config = BuildTestConfig(
hasDataSource: false,
entities: new Dictionary<string, Entity>());
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>
/// Validates that a non-root config with a data source and entities passes validation.
/// </summary>
[TestMethod]
public void TestNonRootWithDataSourceAndEntitiesIsValid()
{
Dictionary<string, Entity> entities = new()
{
{ "Book", BuildSimpleEntity("dbo.books") }
};
RuntimeConfig config = BuildTestConfig(hasDataSource: true, entities: entities);
RuntimeConfigValidator validator = BuildValidator(config);
validator.ValidateDataSourceAndEntityPresence(config);
Assert.AreEqual(0, validator.ConfigValidationExceptions.Count);
}
/// <summary>
/// Validates that a root config with no data source and no entities is valid
/// (children carry the load).
/// </summary>
[TestMethod]
public void TestRootWithNoDataSourceAndNoEntitiesIsValid()
{
// Build a child config with a data source and entity.
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new Dictionary<string, Entity>
{
{ "Book", BuildSimpleEntity("dbo.books") }
});
childConfig.IsChildConfig = true;
// Build a root config with no data source, pointing to the child.
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false,
entities: new Dictionary<string, Entity>(),
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>
/// Validates that a child config with a data source but no entities produces
/// an error that names the child file.
/// </summary>
[TestMethod]
public void TestChildWithDataSourceAndNoEntitiesProducesNamedError()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: true,
entities: new Dictionary<string, Entity>());
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false,
entities: new Dictionary<string, Entity>(),
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("no entities found"));
}
/// <summary>
/// Validates that a child config with no data source produces
/// an error that names the child file.
/// </summary>
[TestMethod]
public void TestChildWithNoDataSourceProducesNamedError()
{
RuntimeConfig childConfig = BuildTestConfig(
hasDataSource: false,
entities: new Dictionary<string, Entity>());
childConfig.IsChildConfig = true;
RuntimeConfig rootConfig = BuildTestConfig(
hasDataSource: false,
entities: new Dictionary<string, Entity>(),
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>
/// Helper: builds a RuntimeConfigValidator in validate-only mode over the given config.
/// </summary>
private static RuntimeConfigValidator BuildValidator(RuntimeConfig config)
{
MockFileSystem fs = new();
FileSystemRuntimeConfigLoader loader = new(fs)
{
RuntimeConfig = config
};
RuntimeConfigProvider provider = new(loader);
return new RuntimeConfigValidator(provider, fs, new Mock<ILogger<RuntimeConfigValidator>>().Object, isValidateOnly: true);
}
/// <summary>
/// Helper: builds a minimal RuntimeConfig for testing.
/// </summary>
private static RuntimeConfig BuildTestConfig(
bool hasDataSource,
Dictionary<string, Entity> entities,
DataSourceFiles? dataSourceFiles = null)
{
DataSource? ds = hasDataSource
? new DataSource(DatabaseType.MSSQL, "Server=localhost;Database=test;", Options: null)
: null;
return new RuntimeConfig(
Schema: null,
DataSource: ds,
Runtime: new(
Rest: new(),
GraphQL: new(),
Mcp: new(),
Host: new(Cors: null, Authentication: null, Mode: HostMode.Development)),
Entities: new RuntimeEntities(entities),
DataSourceFiles: dataSourceFiles);
}
/// <summary>
/// Helper: builds a simple entity for testing.
/// </summary>
private static Entity BuildSimpleEntity(string source)
{
return new Entity(
Source: new EntitySource(Object: source, Type: EntitySourceType.Table, Parameters: null, KeyFields: null),
GraphQL: new(Singular: null, Plural: null),
Fields: null,
Rest: new(EntityRestOptions.DEFAULT_SUPPORTED_VERBS),
Permissions: new[] { new EntityPermission("anonymous", new[] { new EntityAction(EntityActionOperation.Read, null, null) }) },
Relationships: null,
Mappings: null);
}
}