-
Notifications
You must be signed in to change notification settings - Fork 349
Expand file tree
/
Copy pathHealthEndpointTests.cs
More file actions
754 lines (669 loc) · 36.5 KB
/
Copy pathHealthEndpointTests.cs
File metadata and controls
754 lines (669 loc) · 36.5 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions.TestingHelpers;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Config;
using Azure.DataApiBuilder.Config.DatabasePrimitives;
using Azure.DataApiBuilder.Config.HealthCheck;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core.Authorization;
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Core.Services;
using Azure.DataApiBuilder.Core.Services.MetadataProviders;
using Azure.DataApiBuilder.Product;
using Azure.DataApiBuilder.Service.HealthCheck;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Moq.Protected;
namespace Azure.DataApiBuilder.Service.Tests.Configuration
{
[TestClass]
public class HealthEndpointTests
{
private const string CUSTOM_CONFIG_FILENAME = "custom_config.json";
private const string BASE_DAB_URL = "http://localhost:5000";
[TestCleanup]
public void CleanupAfterEachTest()
{
if (File.Exists(CUSTOM_CONFIG_FILENAME))
{
File.Delete(CUSTOM_CONFIG_FILENAME);
}
TestHelper.UnsetAllDABEnvironmentVariables();
}
/// <summary>
/// Simulates a GET request to DAB's comprehensive health check endpoint ('/health') and validates the contents of the response.
/// The expected format of the response is the comprehensive health check response.
/// </summary>
[TestMethod]
[TestCategory(TestCategory.MSSQL)]
[DataRow(true, true, true, true, true, true, true, true, DisplayName = "Validate Health Report all enabled.")]
[DataRow(false, true, true, true, true, true, true, true, DisplayName = "Validate when Comprehensive Health Report is disabled")]
[DataRow(true, true, true, false, true, true, true, true, DisplayName = "Validate Health Report when global MCP health is disabled")]
[DataRow(true, true, true, true, false, true, true, true, DisplayName = "Validate Health Report when data-source health is disabled")]
[DataRow(true, true, true, true, true, false, true, true, DisplayName = "Validate Health Report when entity health is disabled")]
[DataRow(true, false, true, true, true, true, true, true, DisplayName = "Validate Health Report when global REST health is disabled")]
[DataRow(true, true, false, true, true, true, true, true, DisplayName = "Validate Health Report when global GraphQL health is disabled")]
[DataRow(true, true, true, true, true, true, false, true, DisplayName = "Validate Health Report when entity REST health is disabled")]
[DataRow(true, true, true, true, true, true, true, false, DisplayName = "Validate Health Report when entity GraphQL health is disabled")]
public async Task ComprehensiveHealthEndpoint_ValidateContents(
bool enableGlobalHealth,
bool enableGlobalRest,
bool enableGlobalGraphql,
bool enableGlobalMcp,
bool enableDatasourceHealth,
bool enableEntityHealth,
bool enableEntityRest,
bool enableEntityGraphQL)
{
// The body remains exactly the same except passing enableGlobalMcp
RuntimeConfig runtimeConfig = SetupCustomConfigFile(
enableGlobalHealth,
enableGlobalRest,
enableGlobalGraphql,
enableGlobalMcp,
enableDatasourceHealth,
enableEntityHealth,
enableEntityRest,
enableEntityGraphQL);
WriteToCustomConfigFile(runtimeConfig);
string[] args = new[]
{
$"--ConfigFileName={CUSTOM_CONFIG_FILENAME}"
};
using (TestServer server = new(Program.CreateWebHostBuilder(args)))
using (HttpClient client = server.CreateClient())
{
HttpRequestMessage healthRequest = new(HttpMethod.Get, $"{BASE_DAB_URL}/health");
HttpResponseMessage response = await client.SendAsync(healthRequest);
if (!enableGlobalHealth)
{
Assert.AreEqual(expected: HttpStatusCode.NotFound, actual: response.StatusCode, message: "Received unexpected HTTP code from health check endpoint.");
}
else
{
string responseBody = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement> responseProperties = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseBody);
Assert.AreEqual(expected: HttpStatusCode.OK, actual: response.StatusCode, message: "Received unexpected HTTP code from health check endpoint.");
ValidateBasicDetailsHealthCheckResponse(responseProperties);
ValidateConfigurationDetailsHealthCheckResponse(responseProperties, enableGlobalRest, enableGlobalGraphql, enableGlobalMcp);
ValidateIfAttributePresentInResponse(responseProperties, enableDatasourceHealth, HealthCheckConstants.DATASOURCE);
ValidateIfAttributePresentInResponse(responseProperties, enableEntityHealth, HealthCheckConstants.ENDPOINT);
ValidateIfAttributePresentInResponse(responseProperties, enableGlobalMcp, HealthCheckConstants.MCP);
if (enableEntityHealth)
{
ValidateEntityRestAndGraphQLResponse(responseProperties, enableEntityRest, enableEntityGraphQL, enableGlobalRest, enableGlobalGraphql);
}
}
}
}
/// <summary>
/// Simulates the function call to HttpUtilities.ExecuteRestQueryAsync.
/// while setting up mock HTTP client to simulate the response from the server to send OK code.
/// Validates the response to ensure no error message is received.
/// </summary>
[TestMethod]
public async Task TestHealthCheckRestResponseAsync()
{
// Arrange
RuntimeConfig runtimeConfig = SetupCustomConfigFile(true, true, true, true, true, true, true, true);
HttpUtilities httpUtilities = SetupRestTest(runtimeConfig);
// Act
// Call the ExecuteRestQuery method with the mock HttpClient
// Simulate a REST API call to the endpoint
// Response should be null as error message is not expected to be returned
string errorMessageFromRest = await httpUtilities.ExecuteRestQueryAsync(
restUriSuffix: runtimeConfig.RestPath,
entityName: runtimeConfig.Entities.First().Key,
first: runtimeConfig.Entities.First().Value.Health.First,
incomingRoleHeader: string.Empty,
incomingRoleToken: string.Empty
);
// Assert
// Validate the null response from the REST API call
Assert.IsNull(errorMessageFromRest);
}
/// <summary>
/// Simulates the function call to HttpUtilities.ExecuteRestQueryAsync.
/// while setting up mock HTTP client to simulate the response from the server to send BadRequest code.
/// Validates the response to ensure error message is received.
/// </summary>
[TestMethod]
public async Task TestFailureHealthCheckRestResponseAsync()
{
// Arrange
RuntimeConfig runtimeConfig = SetupCustomConfigFile(true, true, true, true, true, true, true, true);
HttpUtilities httpUtilities = SetupGraphQLTest(runtimeConfig, HttpStatusCode.BadRequest);
// Act
// Call the ExecuteRestQuery method with the mock HttpClient
// Simulate a REST API call to the endpoint
// Response should be null as error message is not expected to be returned
string errorMessageFromRest = await httpUtilities.ExecuteRestQueryAsync(
restUriSuffix: runtimeConfig.RestPath,
entityName: runtimeConfig.Entities.First().Key,
first: runtimeConfig.Entities.First().Value.Health.First,
incomingRoleHeader: string.Empty,
incomingRoleToken: string.Empty
);
// Assert
Assert.IsNotNull(errorMessageFromRest);
}
/// <summary>
/// Simulates the function call to HttpUtilities.ExecuteGraphQLQueryAsync.
/// while setting up mock HTTP client to simulate the response from the server to send OK code.
/// Validates the response to ensure no error message is received.
/// </summary>
[TestMethod]
public async Task TestHealthCheckGraphQLResponseAsync()
{
// Arrange
RuntimeConfig runtimeConfig = SetupCustomConfigFile(true, true, true, true, true, true, true, true);
HttpUtilities httpUtilities = SetupGraphQLTest(runtimeConfig);
// Act
string errorMessageFromGraphQL = await httpUtilities.ExecuteGraphQLQueryAsync(
graphqlUriSuffix: "/graphql",
entityName: runtimeConfig.Entities.First().Key,
entity: runtimeConfig.Entities.First().Value,
incomingRoleHeader: string.Empty,
incomingRoleToken: string.Empty);
// Assert
Assert.IsNull(errorMessageFromGraphQL);
}
/// <summary>
/// Simulates the function call to HttpUtilities.ExecuteGraphQLQueryAsync.
/// while setting up mock HTTP client to simulate the response from the server to send InternalServerError code.
/// Validates the response to ensure error message is received.
/// </summary>
[TestMethod]
public async Task TestFailureHealthCheckGraphQLResponseAsync()
{
// Arrange
RuntimeConfig runtimeConfig = SetupCustomConfigFile(true, true, true, true, true, true, true, true);
HttpUtilities httpUtilities = SetupGraphQLTest(runtimeConfig, HttpStatusCode.InternalServerError);
// Act
string errorMessageFromGraphQL = await httpUtilities.ExecuteGraphQLQueryAsync(
graphqlUriSuffix: "/graphql",
entityName: runtimeConfig.Entities.First().Key,
entity: runtimeConfig.Entities.First().Value,
incomingRoleHeader: string.Empty,
incomingRoleToken: string.Empty);
// Assert
Assert.IsNotNull(errorMessageFromGraphQL);
}
/// <summary>
/// Simulates the function call to HttpUtilities.ExecuteMcpQueryAsync.
/// while setting up mock HTTP client to simulate the response from the server to send OK code.
/// Validates the response to ensure no error message is received.
/// </summary>
[TestMethod]
public async Task TestHealthCheckMcpResponseAsync()
{
// Arrange
RuntimeConfig runtimeConfig = SetupCustomConfigFile(true, true, true, true, true, true, true, true);
HttpUtilities httpUtilities = SetupMcpTest(runtimeConfig);
// Act
// Simulate an MCP initialize POST request to the endpoint.
// Response should be null as error message is not expected to be returned.
string errorMessageFromMcp = await httpUtilities.ExecuteMcpQueryAsync(
mcpUriSuffix: runtimeConfig.McpPath,
incomingRoleHeader: string.Empty,
incomingRoleToken: string.Empty);
// Assert
Assert.IsNull(errorMessageFromMcp);
}
/// <summary>
/// Simulates the function call to HttpUtilities.ExecuteMcpQueryAsync.
/// while setting up mock HTTP client to simulate the response from the server to send InternalServerError code.
/// Validates the response to ensure error message is received.
/// </summary>
[TestMethod]
public async Task TestFailureHealthCheckMcpResponseAsync()
{
// Arrange
RuntimeConfig runtimeConfig = SetupCustomConfigFile(true, true, true, true, true, true, true, true);
HttpUtilities httpUtilities = SetupMcpTest(runtimeConfig, HttpStatusCode.InternalServerError);
// Act
string errorMessageFromMcp = await httpUtilities.ExecuteMcpQueryAsync(
mcpUriSuffix: runtimeConfig.McpPath,
incomingRoleHeader: string.Empty,
incomingRoleToken: string.Empty);
// Assert
Assert.IsNotNull(errorMessageFromMcp);
}
/// <summary>
/// Tests the serialization behavior of <see cref="RuntimeHealthCheckConfig"/> for the <see cref="RuntimeHealthCheckConfig.MaxQueryParallelism"/> property."
/// </summary>
/// <remarks>This test ensures that the JSON serialization behavior of <see
/// cref="RuntimeHealthCheckConfig"/> adheres to the expected behavior where default values are omitted from
/// the output.</remarks>
[TestMethod]
public void MaxQueryParallelismSerializationDependsOnUserInput()
{
// Case 1: default value NOT explicitly provided => should NOT serialize
RuntimeHealthCheckConfig configWithDefault = new(
enabled: true,
roles: null,
cacheTtlSeconds: null,
maxQueryParallelism: null // implicit default
);
Assert.IsFalse(configWithDefault.UserProvidedMaxQueryParallelism, "UserProvidedMaxQueryParallelism should be false for default value.");
// Case 2: default value EXPLICITLY provided => should serialize
RuntimeHealthCheckConfig configWithExplicitDefault = new(
enabled: true,
roles: null,
cacheTtlSeconds: null,
maxQueryParallelism: RuntimeHealthCheckConfig.DEFAULT_MAX_QUERY_PARALLELISM
);
Assert.IsTrue(configWithExplicitDefault.UserProvidedMaxQueryParallelism, "UserProvidedMaxQueryParallelism should be true for explicit default value.");
// Case 3: non-default value => should serialize
RuntimeHealthCheckConfig configWithCustomValue = new(
enabled: true,
roles: null,
cacheTtlSeconds: null,
maxQueryParallelism: RuntimeHealthCheckConfig.DEFAULT_MAX_QUERY_PARALLELISM + 1
);
Assert.IsTrue(configWithCustomValue.UserProvidedMaxQueryParallelism, "UserProvidedMaxQueryParallelism should be true for custom value.");
}
#region Helper Methods
private static HttpUtilities SetupRestTest(RuntimeConfig runtimeConfig, HttpStatusCode httpStatusCode = HttpStatusCode.OK)
{
// Arrange
// Create a mock entity map with a single entity for testing and load in RuntimeConfigProvider
Mock<IMetadataProviderFactory> metadataProviderFactory = new();
MockFileSystem fileSystem = new();
fileSystem.AddFile(FileSystemRuntimeConfigLoader.DEFAULT_CONFIG_FILE_NAME, new MockFileData(runtimeConfig.ToJson()));
FileSystemRuntimeConfigLoader loader = new(fileSystem);
RuntimeConfigProvider provider = new(loader);
// Create a Mock of HttpMessageHandler
Mock<HttpMessageHandler> mockHandler = new();
// Mocking the handler to return a specific response for SendAsync
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == HttpMethod.Get
&& req.RequestUri.Equals($"{BASE_DAB_URL}/{runtimeConfig.RestPath.Trim('/')}/{runtimeConfig.Entities.First().Key}?$first={runtimeConfig.Entities.First().Value.Health.First}")),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage(httpStatusCode)
{
Content = new StringContent("{\"message\":\"Rest response\"}")
});
// Mocking IHttpClientFactory
Mock<IHttpClientFactory> mockHttpClientFactory = new();
mockHttpClientFactory.Setup(x => x.CreateClient("ContextConfiguredHealthCheckClient"))
.Returns(new HttpClient(mockHandler.Object)
{
BaseAddress = new Uri($"{BASE_DAB_URL}")
});
Mock<ILogger<HttpUtilities>> _logger = new();
// Create the mock HttpContext to return the expected scheme and host
// when the ConfigureApiRoute method is called.
Mock<HttpContext> mockHttpContext = new();
Mock<HttpRequest> mockHttpRequest = new();
mockHttpRequest.Setup(r => r.Scheme).Returns("http");
mockHttpRequest.Setup(r => r.Host).Returns(new HostString("localhost", 5000));
mockHttpContext.Setup(c => c.Request).Returns(mockHttpRequest.Object);
return new(
_logger.Object,
metadataProviderFactory.Object,
provider,
mockHttpClientFactory.Object);
}
private static HttpUtilities SetupGraphQLTest(RuntimeConfig runtimeConfig, HttpStatusCode httpStatusCode = HttpStatusCode.OK)
{
// Arrange
// Create a mock entity map with a single entity for testing and load in RuntimeConfigProvider
MockFileSystem fileSystem = new();
fileSystem.AddFile(FileSystemRuntimeConfigLoader.DEFAULT_CONFIG_FILE_NAME, new MockFileData(runtimeConfig.ToJson()));
FileSystemRuntimeConfigLoader loader = new(fileSystem);
RuntimeConfigProvider provider = new(loader);
Mock<IMetadataProviderFactory> metadataProviderFactory = new();
Mock<ISqlMetadataProvider> sqlMetadataProvider = new();
// Setup the mock database object with a source definition
SourceDefinition sourceDef = new();
sourceDef.Columns.Add("id", new ColumnDefinition());
sourceDef.Columns.Add("title", new ColumnDefinition());
// Mock DB Object to return the source definition
Mock<DatabaseObject> mockDbObject = new();
mockDbObject.SetupGet(x => x.SourceDefinition).Returns(sourceDef);
// Mocking the metadata provider to return the mock database object
sqlMetadataProvider.Setup(x => x.GetDatabaseObjectByKey(runtimeConfig.Entities.First().Key)).Returns(mockDbObject.Object);
metadataProviderFactory.Setup(x => x.GetMetadataProvider(It.IsAny<string>())).Returns(sqlMetadataProvider.Object);
Mock<HttpMessageHandler> mockHandler = new();
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == HttpMethod.Post &&
req.RequestUri == new Uri($"{BASE_DAB_URL}/graphql") &&
req.Content.ReadAsStringAsync().Result.Equals("{\"query\":\"{bookLists (first: 100) {items { id title }}}\"}")), // Use the correct GraphQL query format
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage(httpStatusCode)
{
Content = new StringContent("{\"errors\":[{\"message\":\"Internal Server Error\"}]}")
});
Mock<IHttpClientFactory> mockHttpClientFactory = new();
mockHttpClientFactory.Setup(x => x.CreateClient("ContextConfiguredHealthCheckClient"))
.Returns(new HttpClient(mockHandler.Object)
{
BaseAddress = new Uri($"{BASE_DAB_URL}")
});
Mock<ILogger<HttpUtilities>> logger = new();
return new(
logger.Object,
metadataProviderFactory.Object,
provider,
mockHttpClientFactory.Object);
}
private static HttpUtilities SetupMcpTest(RuntimeConfig runtimeConfig, HttpStatusCode httpStatusCode = HttpStatusCode.OK)
{
// Arrange
// Create a mock entity map with a single entity for testing and load in RuntimeConfigProvider
MockFileSystem fileSystem = new();
fileSystem.AddFile(FileSystemRuntimeConfigLoader.DEFAULT_CONFIG_FILE_NAME, new MockFileData(runtimeConfig.ToJson()));
FileSystemRuntimeConfigLoader loader = new(fileSystem);
RuntimeConfigProvider provider = new(loader);
Mock<IMetadataProviderFactory> metadataProviderFactory = new();
// Mock the handler to return the supplied status code for the MCP initialize POST request.
Mock<HttpMessageHandler> mockHandler = new();
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == HttpMethod.Post &&
req.RequestUri == new Uri($"{BASE_DAB_URL}{runtimeConfig.McpPath}") &&
req.Content != null &&
req.Content.ReadAsStringAsync().Result.Contains("\"method\":\"initialize\"") &&
req.Headers.TryGetValues("Accept", out IEnumerable<string>? acceptValues) &&
acceptValues.Any(v => v.Contains("application/json") && v.Contains("text/event-stream"))),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage(httpStatusCode)
{
Content = new StringContent("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}")
});
Mock<IHttpClientFactory> mockHttpClientFactory = new();
mockHttpClientFactory.Setup(x => x.CreateClient("ContextConfiguredHealthCheckClient"))
.Returns(new HttpClient(mockHandler.Object)
{
BaseAddress = new Uri($"{BASE_DAB_URL}")
});
Mock<ILogger<HttpUtilities>> logger = new();
return new(
logger.Object,
metadataProviderFactory.Object,
provider,
mockHttpClientFactory.Object);
}
private static void ValidateEntityRestAndGraphQLResponse(
Dictionary<string, JsonElement> responseProperties,
bool enableEntityRest,
bool enableEntityGraphQL,
bool enableGlobalRest,
bool enableGlobalGraphQL)
{
bool hasRestTag = false, hasGraphQLTag = false;
if (responseProperties.TryGetValue("checks", out JsonElement checksElement) && checksElement.ValueKind == JsonValueKind.Array)
{
checksElement.EnumerateArray().ToList().ForEach(entityCheck =>
{
// Check if the 'tags' property exists and is of type array
if (entityCheck.TryGetProperty("tags", out JsonElement tagsElement) && tagsElement.ValueKind == JsonValueKind.Array)
{
hasRestTag = hasRestTag || tagsElement.EnumerateArray().Any(tag => tag.ToString() == HealthCheckConstants.REST);
hasGraphQLTag = hasGraphQLTag || tagsElement.EnumerateArray().Any(tag => tag.ToString() == HealthCheckConstants.GRAPHQL);
}
});
if (enableGlobalRest)
{
// When both enableEntityRest and hasRestTag match the same value
Assert.AreEqual(enableEntityRest, hasRestTag);
}
else
{
Assert.IsFalse(hasRestTag);
}
if (enableGlobalGraphQL)
{
// When both enableEntityGraphQL and hasGraphQLTag match the same value
Assert.AreEqual(enableEntityGraphQL, hasGraphQLTag);
}
else
{
Assert.IsFalse(hasGraphQLTag);
}
}
}
private static void ValidateIfAttributePresentInResponse(
Dictionary<string, JsonElement> responseProperties,
bool enableFlag,
string checkString)
{
if (responseProperties.TryGetValue("checks", out JsonElement checksElement) && checksElement.ValueKind == JsonValueKind.Array)
{
bool checksTags = checksElement.EnumerateArray().Any(entityCheck =>
{
if (entityCheck.TryGetProperty("tags", out JsonElement tagsElement) && tagsElement.ValueKind == JsonValueKind.Array)
{
return tagsElement.EnumerateArray().Any(tag => tag.ToString() == checkString);
}
return false;
});
Assert.AreEqual(enableFlag, checksTags);
}
else
{
Assert.Fail("Checks array is not present in the Comprehensive Health Check Report.");
}
}
private static void ValidateConfigurationIsNotNull(Dictionary<string, JsonElement> configPropertyValues, string objectKey)
{
Assert.IsTrue(configPropertyValues.ContainsKey(objectKey), $"Expected {objectKey} to be present in the configuration object.");
Assert.IsNotNull(configPropertyValues[objectKey], $"Expected {objectKey} to be non-null.");
}
private static void ValidateConfigurationIsCorrectFlag(Dictionary<string, JsonElement> configElement, string objectKey, bool enableFlag)
{
Assert.AreEqual(enableFlag, configElement[objectKey].GetBoolean(), $"Expected {objectKey} to be set to {enableFlag}.");
}
private static void ValidateConfigurationDetailsHealthCheckResponse(Dictionary<string, JsonElement> responseProperties, bool enableGlobalRest, bool enableGlobalGraphQL, bool enableGlobalMcp)
{
if (responseProperties.TryGetValue("configuration", out JsonElement configElement) && configElement.ValueKind == JsonValueKind.Object)
{
Dictionary<string, JsonElement> configPropertyValues = new();
// Enumerate through the configProperty's object properties and add them to the dictionary
foreach (JsonProperty property in configElement.EnumerateObject().ToList())
{
configPropertyValues[property.Name] = property.Value;
}
ValidateConfigurationIsNotNull(configPropertyValues, "rest");
ValidateConfigurationIsCorrectFlag(configPropertyValues, "rest", enableGlobalRest);
ValidateConfigurationIsNotNull(configPropertyValues, "graphql");
ValidateConfigurationIsCorrectFlag(configPropertyValues, "graphql", enableGlobalGraphQL);
ValidateConfigurationIsNotNull(configPropertyValues, "mcp");
ValidateConfigurationIsCorrectFlag(configPropertyValues, "mcp", enableGlobalMcp);
ValidateConfigurationIsNotNull(configPropertyValues, "caching");
ValidateConfigurationIsNotNull(configPropertyValues, "telemetry");
ValidateConfigurationIsNotNull(configPropertyValues, "mode");
}
else
{
Assert.Fail("Missing 'configuration' object in Health Check Response.");
}
}
public static void ValidateBasicDetailsHealthCheckResponse(Dictionary<string, JsonElement> responseProperties)
{
// Validate value of 'status' property in response.
if (responseProperties.TryGetValue(key: "status", out JsonElement statusValue))
{
Assert.IsTrue(statusValue.ValueKind == JsonValueKind.String, "Unexpected or missing status value as string.");
}
else
{
Assert.Fail();
}
// Validate value of 'version' property in response.
if (responseProperties.TryGetValue(key: BasicHealthCheck.DAB_VERSION_KEY, out JsonElement versionValue))
{
Assert.AreEqual(
expected: ProductInfo.GetProductVersion(),
actual: versionValue.ToString(),
message: "Unexpected or missing version value.");
}
else
{
Assert.Fail();
}
// Validate value of 'app-name' property in response.
if (responseProperties.TryGetValue(key: BasicHealthCheck.DAB_APPNAME_KEY, out JsonElement appNameValue))
{
Assert.AreEqual(
expected: ProductInfo.GetDataApiBuilderUserAgent(),
actual: appNameValue.ToString(),
message: "Unexpected or missing DAB user agent string.");
}
else
{
Assert.Fail();
}
}
private static RuntimeConfig SetupCustomConfigFile(bool enableGlobalHealth, bool enableGlobalRest, bool enableGlobalGraphql, bool enabledGlobalMcp, bool enableDatasourceHealth, bool enableEntityHealth, bool enableEntityRest, bool enableEntityGraphQL)
{
// At least one entity is required in the runtime config for the engine to start.
// Even though this entity is not under test, it must be supplied enable successful
// config file creation.
Entity requiredEntity = new(
Health: new(enabled: enableEntityHealth),
Source: new("books", EntitySourceType.Table, null, null),
Fields: null,
Rest: new(Enabled: enableEntityRest),
GraphQL: new("book", "bookLists", enableEntityGraphQL),
Permissions: new[] { ConfigurationTests.GetMinimalPermissionConfig(AuthorizationResolver.ROLE_ANONYMOUS) },
Relationships: null,
Mappings: null);
Dictionary<string, Entity> entityMap = new()
{
{ "Book", requiredEntity }
};
return CreateRuntimeConfig(entityMap, enableGlobalRest, enableGlobalGraphql, enabledGlobalMcp, enableGlobalHealth, enableDatasourceHealth, HostMode.Development);
}
/// <summary>
/// Helper function to write custom configuration file. with minimal REST/GraphQL global settings
/// using the supplied entities.
/// </summary>
/// <param name="entityMap">Collection of entityName -> Entity object.</param>
/// <param name="enableGlobalRest">flag to enable or disabled REST globally.</param>
private static RuntimeConfig CreateRuntimeConfig(Dictionary<string, Entity> entityMap, bool enableGlobalRest = true, bool enableGlobalGraphql = true, bool enabledGlobalMcp = true, bool enableGlobalHealth = true, bool enableDatasourceHealth = true, HostMode hostMode = HostMode.Production)
{
DataSource dataSource = new(
DatabaseType.MSSQL,
ConfigurationTests.GetConnectionStringFromEnvironmentConfig(environment: TestCategory.MSSQL),
Options: null,
Health: new(enableDatasourceHealth));
HostOptions hostOptions = new(Mode: hostMode, Cors: null, Authentication: new() { Provider = nameof(EasyAuthType.AppService) });
RuntimeConfig runtimeConfig = new(
Schema: string.Empty,
DataSource: dataSource,
Runtime: new(
Health: new(enabled: enableGlobalHealth),
Rest: new(Enabled: enableGlobalRest),
GraphQL: new(Enabled: enableGlobalGraphql),
Mcp: new(Enabled: enabledGlobalMcp),
Host: hostOptions
),
Entities: new(entityMap));
return runtimeConfig;
}
/// <summary>
/// Verifies that stored procedures are excluded from health check results.
/// Creates a config with both a table entity and a stored procedure entity,
/// then validates that only the table entity appears in the health endpoint response.
/// </summary>
[TestMethod]
[TestCategory(TestCategory.MSSQL)]
public async Task HealthEndpoint_ExcludesStoredProcedures()
{
// Create a table entity
Entity tableEntity = new(
Health: new(enabled: true),
Source: new("books", EntitySourceType.Table, null, null),
Fields: null,
Rest: new(Enabled: true),
GraphQL: new("book", "bookLists", true),
Permissions: new[] { ConfigurationTests.GetMinimalPermissionConfig(AuthorizationResolver.ROLE_ANONYMOUS) },
Relationships: null,
Mappings: null);
// Create a stored procedure entity - using an actual stored procedure from test schema
Entity storedProcEntity = new(
Health: new(enabled: true),
Source: new("get_books", EntitySourceType.StoredProcedure, null, null),
Fields: null,
Rest: new(Enabled: true),
GraphQL: new("executeGetBooks", "executeGetBooksList", true),
Permissions: new[] { ConfigurationTests.GetMinimalPermissionConfig(AuthorizationResolver.ROLE_ANONYMOUS) },
Relationships: null,
Mappings: null);
Dictionary<string, Entity> entityMap = new()
{
{ "Book", tableEntity },
{ "GetBooks", storedProcEntity }
};
RuntimeConfig runtimeConfig = CreateRuntimeConfig(
entityMap,
enableGlobalRest: true,
enableGlobalGraphql: true,
enabledGlobalMcp: true,
enableGlobalHealth: true,
enableDatasourceHealth: true,
hostMode: HostMode.Development);
WriteToCustomConfigFile(runtimeConfig);
string[] args = new[]
{
$"--ConfigFileName={CUSTOM_CONFIG_FILENAME}"
};
using (TestServer server = new(Program.CreateWebHostBuilder(args)))
using (HttpClient client = server.CreateClient())
{
HttpRequestMessage healthRequest = new(HttpMethod.Get, $"{BASE_DAB_URL}/health");
HttpResponseMessage response = await client.SendAsync(healthRequest);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Health endpoint should return OK");
string responseBody = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement> responseProperties = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseBody);
// Get the checks array
Assert.IsTrue(responseProperties.TryGetValue("checks", out JsonElement checksElement), "Response should contain 'checks' property");
Assert.AreEqual(JsonValueKind.Array, checksElement.ValueKind, "Checks should be an array");
// Get all entity names from the health check results
List<string> entityNamesInHealthCheck = new();
foreach (JsonElement check in checksElement.EnumerateArray())
{
if (check.TryGetProperty("name", out JsonElement nameElement))
{
entityNamesInHealthCheck.Add(nameElement.GetString());
}
}
// Verify that the table entity (Book) appears in health checks
Assert.IsTrue(entityNamesInHealthCheck.Contains("Book"),
"Table entity 'Book' should be included in health check results");
// Verify that the stored procedure entity (GetBooks) does NOT appear in health checks
Assert.IsFalse(entityNamesInHealthCheck.Contains("GetBooks"),
"Stored procedure entity 'GetBooks' should be excluded from health check results");
}
}
private static void WriteToCustomConfigFile(RuntimeConfig runtimeConfig)
{
File.WriteAllText(
path: CUSTOM_CONFIG_FILENAME,
contents: runtimeConfig.ToJson());
}
}
#endregion
}