-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathEndToEndTests.cs
More file actions
1274 lines (1106 loc) · 73 KB
/
EndToEndTests.cs
File metadata and controls
1274 lines (1106 loc) · 73 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.Config.Converters;
using Azure.DataApiBuilder.Product;
using Cli.Constants;
using Microsoft.Data.SqlClient;
namespace Cli.Tests;
/// <summary>
/// End To End Tests for CLI.
/// </summary>
[TestClass]
public class EndToEndTests
: VerifyBase
{
private IFileSystem? _fileSystem;
private FileSystemRuntimeConfigLoader? _runtimeConfigLoader;
private ILogger<Program>? _cliLogger;
[TestInitialize]
public void TestInitialize()
{
MockFileSystem fileSystem = FileSystemUtils.ProvisionMockFileSystem();
// Mock GraphQL Schema File
fileSystem.AddFile(TEST_SCHEMA_FILE, new MockFileData(""));
// Empty runtime config file
fileSystem.AddFile("dab-config-empty.json", new MockFileData(""));
_fileSystem = fileSystem;
_runtimeConfigLoader = new FileSystemRuntimeConfigLoader(_fileSystem);
ILoggerFactory loggerFactory = TestLoggerSupport.ProvisionLoggerFactory();
_cliLogger = loggerFactory.CreateLogger<Program>();
SetLoggerForCliConfigGenerator(loggerFactory.CreateLogger<ConfigGenerator>());
SetCliUtilsLogger(loggerFactory.CreateLogger<Utils>());
Environment.SetEnvironmentVariable($"connection-string", TEST_CONNECTION_STRING);
}
[TestCleanup]
public void TestCleanup()
{
_fileSystem = null;
_runtimeConfigLoader = null;
_cliLogger = null;
}
/// <summary>
/// Initializing config for CosmosDB_NoSQL.
/// </summary>
[TestMethod]
public Task TestInitForCosmosDBNoSql()
{
string[] args = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "cosmosdb_nosql",
"--connection-string", TEST_ENV_CONN_STRING, "--cosmosdb_nosql-database",
"graphqldb", "--cosmosdb_nosql-container", "planet", "--graphql-schema", TEST_SCHEMA_FILE, "--cors-origin", "localhost:3000,www.nolocalhost.com:80" };
Program.Execute(args, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.IsTrue(runtimeConfig.AllowIntrospection);
Assert.AreEqual(DatabaseType.CosmosDB_NoSQL, runtimeConfig.DataSource!.DatabaseType);
CosmosDbNoSQLDataSourceOptions? cosmosDataSourceOptions = runtimeConfig.DataSource.GetTypedOptions<CosmosDbNoSQLDataSourceOptions>();
Assert.IsNotNull(cosmosDataSourceOptions);
Assert.AreEqual("graphqldb", cosmosDataSourceOptions.Database);
Assert.AreEqual("planet", cosmosDataSourceOptions.Container);
Assert.AreEqual(TEST_SCHEMA_FILE, cosmosDataSourceOptions.Schema);
Assert.IsNotNull(runtimeConfig.Runtime);
Assert.IsNotNull(runtimeConfig.Runtime.Host);
HostOptions hostGlobalSettings = runtimeConfig.Runtime.Host;
CollectionAssert.AreEqual(new string[] { "localhost:3000", "www.nolocalhost.com:80" }, hostGlobalSettings.Cors!.Origins);
return Verify(runtimeConfig);
}
/// <summary>
/// Initializing config for cosmosdb_postgresql.
/// </summary>
[TestMethod]
public void TestInitForCosmosDBPostgreSql()
{
string[] args = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "cosmosdb_postgresql", "--rest.path", "/rest-api",
"--graphql.path", "/graphql-api", "--connection-string", "localhost:5000", "--cors-origin", "localhost:3000,www.nolocalhost.com:80" };
Program.Execute(args, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(DatabaseType.CosmosDB_PostgreSQL, runtimeConfig.DataSource!.DatabaseType);
Assert.IsNotNull(runtimeConfig.Runtime);
Assert.IsNotNull(runtimeConfig.Runtime.Rest);
Assert.AreEqual("/rest-api", runtimeConfig.Runtime.Rest.Path);
Assert.IsTrue(runtimeConfig.Runtime.Rest.Enabled);
Assert.IsNotNull(runtimeConfig.Runtime.GraphQL);
Assert.AreEqual("/graphql-api", runtimeConfig.Runtime.GraphQL.Path);
Assert.IsTrue(runtimeConfig.Runtime.GraphQL.Enabled);
HostOptions? hostGlobalSettings = runtimeConfig.Runtime?.Host;
Assert.IsNotNull(hostGlobalSettings);
Assert.IsNotNull(hostGlobalSettings.Cors);
CollectionAssert.AreEqual(new string[] { "localhost:3000", "www.nolocalhost.com:80" }, hostGlobalSettings.Cors.Origins);
}
/// <summary>
/// Initializing config for REST and GraphQL global settings,
/// such as custom path and enabling/disabling endpoints.
/// </summary>
[TestMethod]
public void TestInitializingRestAndGraphQLGlobalSettings()
{
string[] args = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--connection-string", SAMPLE_TEST_CONN_STRING, "--database-type", "mssql", "--rest.path", "/rest-api", "--rest.enabled", "false", "--graphql.path", "/graphql-api" };
Program.Execute(args, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
DeserializationVariableReplacementSettings replacementSettings = new(azureKeyVaultOptions: null, doReplaceEnvVar: true, doReplaceAkvVar: true, envFailureMode: EnvironmentVariableReplacementFailureMode.Ignore);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(
TEST_RUNTIME_CONFIG_FILE,
out RuntimeConfig? runtimeConfig,
replacementSettings: replacementSettings));
SqlConnectionStringBuilder builder = new(runtimeConfig.DataSource!.ConnectionString);
Assert.AreEqual(ProductInfo.GetDataApiBuilderUserAgent(), builder.ApplicationName);
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(DatabaseType.MSSQL, runtimeConfig.DataSource.DatabaseType);
Assert.IsNotNull(runtimeConfig.Runtime);
Assert.AreEqual("/rest-api", runtimeConfig.Runtime.Rest?.Path);
Assert.IsFalse(runtimeConfig.Runtime.Rest?.Enabled);
Assert.AreEqual("/graphql-api", runtimeConfig.Runtime.GraphQL?.Path);
Assert.IsTrue(runtimeConfig.Runtime.GraphQL?.Enabled);
}
/// <summary>
/// Test to validate the usage of --graphql.multiple-create.enabled option of the init command for all database types.
///
/// 1. Behavior for database types other than MsSQL:
/// - Irrespective of whether the --graphql.multiple-create.enabled option is used or not, fields related to multiple-create will NOT be written to the config file.
/// - As a result, after deserialization of such a config file, the Runtime.GraphQL.MultipleMutationOptions is expected to be null.
/// 2. Behavior for MsSQL database type:
///
/// a. When --graphql.multiple-create.enabled option is used
/// - In this case, the fields related to multiple mutation and multiple create operations will be written to the config file.
/// "multiple-mutations": {
/// "create": {
/// "enabled": true/false
/// }
/// }
/// After deserializing such a config file, the Runtime.GraphQL.MultipleMutationOptions is expected to be non-null and the value of the "enabled" field is expected to be the same as the value passed in the init command.
///
/// b. When --graphql.multiple-create.enabled option is not used
/// - In this case, fields related to multiple mutation and multiple create operations will NOT be written to the config file.
/// - As a result, after deserialization of such a config file, the Runtime.GraphQL.MultipleMutationOptions is expected to be null.
///
/// </summary>
/// <param name="isMultipleCreateEnabled">Value interpreted by the CLI for '--graphql.multiple-create.enabled' option of the init command.
/// When not used, CLI interprets the value for the option as CliBool.None
/// When used with true/false, CLI interprets the value as CliBool.True/CliBool.False respectively.
/// </param>
/// <param name="expectedValueForMultipleCreateEnabledFlag"> Expected value for the multiple create enabled flag in the config file.</param>
[DataTestMethod]
[DataRow(CliBool.True, "mssql", DatabaseType.MSSQL, DisplayName = "Init command with '--graphql.multiple-create.enabled true' for MsSql database type")]
[DataRow(CliBool.False, "mssql", DatabaseType.MSSQL, DisplayName = "Init command with '--graphql.multiple-create.enabled false' for MsSql database type")]
[DataRow(CliBool.None, "mssql", DatabaseType.MSSQL, DisplayName = "Init command without '--graphql.multiple-create.enabled' option for MsSql database type")]
[DataRow(CliBool.True, "mysql", DatabaseType.MySQL, DisplayName = "Init command with '--graphql.multiple-create.enabled true' for MySql database type")]
[DataRow(CliBool.False, "mysql", DatabaseType.MySQL, DisplayName = "Init command with '--graphql.multiple-create.enabled false' for MySql database type")]
[DataRow(CliBool.None, "mysql", DatabaseType.MySQL, DisplayName = "Init command without '--graphql.multiple-create.enabled' option for MySql database type")]
[DataRow(CliBool.True, "postgresql", DatabaseType.PostgreSQL, DisplayName = "Init command with '--graphql.multiple-create.enabled true' for PostgreSql database type")]
[DataRow(CliBool.False, "postgresql", DatabaseType.PostgreSQL, DisplayName = "Init command with '--graphql.multiple-create.enabled false' for PostgreSql database type")]
[DataRow(CliBool.None, "postgresql", DatabaseType.PostgreSQL, DisplayName = "Init command without '--graphql.multiple-create.enabled' option for PostgreSql database type")]
[DataRow(CliBool.True, "dwsql", DatabaseType.DWSQL, DisplayName = "Init command with '--graphql.multiple-create.enabled true' for dwsql database type")]
[DataRow(CliBool.False, "dwsql", DatabaseType.DWSQL, DisplayName = "Init command with '--graphql.multiple-create.enabled false' for dwsql database type")]
[DataRow(CliBool.None, "dwsql", DatabaseType.DWSQL, DisplayName = "Init command without '--graphql.multiple-create.enabled' option for dwsql database type")]
[DataRow(CliBool.True, "cosmosdb_nosql", DatabaseType.CosmosDB_NoSQL, DisplayName = "Init command with '--graphql.multiple-create.enabled true' for cosmosdb_nosql database type")]
[DataRow(CliBool.False, "cosmosdb_nosql", DatabaseType.CosmosDB_NoSQL, DisplayName = "Init command with '--graphql.multiple-create.enabled false' for cosmosdb_nosql database type")]
[DataRow(CliBool.None, "cosmosdb_nosql", DatabaseType.CosmosDB_NoSQL, DisplayName = "Init command without '--graphql.multiple-create.enabled' option for cosmosdb_nosql database type")]
public void TestEnablingMultipleCreateOperation(CliBool isMultipleCreateEnabled, string dbType, DatabaseType expectedDbType)
{
List<string> args = new() { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--connection-string", dbType == "postgresql" ? SAMPLE_TEST_PGSQL_CONN_STRING : SAMPLE_TEST_CONN_STRING, "--database-type", dbType };
if (string.Equals("cosmosdb_nosql", dbType, StringComparison.OrdinalIgnoreCase))
{
List<string> cosmosNoSqlArgs = new() { "--cosmosdb_nosql-database",
"graphqldb", "--cosmosdb_nosql-container", "planet", "--graphql-schema", TEST_SCHEMA_FILE};
args.AddRange(cosmosNoSqlArgs);
}
if (isMultipleCreateEnabled is not CliBool.None)
{
args.Add("--graphql.multiple-create.enabled");
args.Add(isMultipleCreateEnabled.ToString()!);
}
Program.Execute(args.ToArray(), _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
DeserializationVariableReplacementSettings replacementSettings = new(azureKeyVaultOptions: null, doReplaceEnvVar: true, doReplaceAkvVar: true, envFailureMode: EnvironmentVariableReplacementFailureMode.Ignore);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(
TEST_RUNTIME_CONFIG_FILE,
out RuntimeConfig? runtimeConfig,
replacementSettings: replacementSettings));
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(expectedDbType, runtimeConfig.DataSource!.DatabaseType);
Assert.IsNotNull(runtimeConfig.Runtime);
Assert.IsNotNull(runtimeConfig.Runtime.GraphQL);
if (runtimeConfig.DataSource.DatabaseType is DatabaseType.MSSQL && isMultipleCreateEnabled is not CliBool.None)
{
Assert.IsNotNull(runtimeConfig.Runtime.GraphQL.MultipleMutationOptions);
Assert.IsNotNull(runtimeConfig.Runtime.GraphQL.MultipleMutationOptions.MultipleCreateOptions);
bool expectedValueForMultipleCreateEnabled = isMultipleCreateEnabled == CliBool.True;
Assert.AreEqual(expectedValueForMultipleCreateEnabled, runtimeConfig.Runtime.GraphQL.MultipleMutationOptions.MultipleCreateOptions.Enabled);
}
else
{
Assert.IsNull(runtimeConfig.Runtime.GraphQL.MultipleMutationOptions, message: "MultipleMutationOptions is expected to be null because a) DB type is not MsSQL or b) Either --graphql.multiple-create.enabled option was not used or no value was provided.");
}
}
/// <summary>
/// Test to verify adding a new Entity.
/// </summary>
[TestMethod]
public void TestAddEntity()
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--host-mode", "development", "--database-type",
"mssql", "--connection-string", TEST_ENV_CONN_STRING, "--auth.provider", "AppService" };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
// Perform assertions on various properties.
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(0, runtimeConfig.Entities.Count()); // No entities
Assert.AreEqual(HostMode.Development, runtimeConfig.Runtime?.Host?.Mode);
string[] addArgs = {"add", "todo", "-c", TEST_RUNTIME_CONFIG_FILE, "--source", "s001.todo",
"--rest", "todo", "--graphql", "todo", "--permissions", "anonymous:*"};
Program.Execute(addArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? addRuntimeConfig));
Assert.IsNotNull(addRuntimeConfig);
Assert.AreEqual(TEST_ENV_CONN_STRING, addRuntimeConfig.DataSource!.ConnectionString);
Assert.AreEqual(1, addRuntimeConfig.Entities.Count()); // 1 new entity added
Assert.IsTrue(addRuntimeConfig.Entities.ContainsKey("todo"));
Entity entity = addRuntimeConfig.Entities["todo"];
Assert.AreEqual("/todo", entity.Rest.Path);
Assert.AreEqual("todo", entity.GraphQL.Singular);
Assert.AreEqual("todos", entity.GraphQL.Plural);
Assert.AreEqual(1, entity.Permissions.Length);
Assert.AreEqual("anonymous", entity.Permissions[0].Role);
Assert.AreEqual(1, entity.Permissions[0].Actions.Length);
Assert.AreEqual(EntityActionOperation.All, entity.Permissions[0].Actions[0].Action);
}
/// <summary>
/// Test to verify telemetry details are added to the config.
/// </summary>
[DataTestMethod]
[DataRow("true", "InstrumentationKey=00000000", DisplayName = "Add Telemetry with connection string and enabled")]
[DataRow("false", "InstrumentationKey=00000000", DisplayName = "Add Telemetry with connection string and disabled")]
[DataRow(null, "InstrumentationKey=00000000", DisplayName = "Add Telemetry with connection string without enabled flag should default to enabled")]
public void TestAddTelemetry(string? appInsightsEnabled, string appInsightsConnString)
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--host-mode", "development", "--database-type",
"mssql", "--connection-string", TEST_ENV_CONN_STRING };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
// Perform assertions on various properties.
Assert.IsNotNull(runtimeConfig);
Assert.IsNotNull(runtimeConfig.Runtime);
Assert.IsNotNull(runtimeConfig.Runtime.Telemetry);
string[] addTelemetryArgs;
if (appInsightsEnabled is null)
{
addTelemetryArgs = new string[] { "add-telemetry", "-c", TEST_RUNTIME_CONFIG_FILE, "--app-insights-conn-string", appInsightsConnString };
}
else
{
addTelemetryArgs = new string[] { "add-telemetry", "-c", TEST_RUNTIME_CONFIG_FILE, "--app-insights-conn-string", appInsightsConnString, "--app-insights-enabled", appInsightsEnabled, };
}
Program.Execute(addTelemetryArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedConfig));
Assert.IsNotNull(updatedConfig);
Assert.IsNotNull(updatedConfig.Runtime);
Assert.IsNotNull(updatedConfig.Runtime.Telemetry);
Assert.IsNotNull(updatedConfig.Runtime.Telemetry.ApplicationInsights);
// if --app-insights-enabled is not provided, it will default to false
Assert.AreEqual(appInsightsEnabled is null ? false : Boolean.Parse(appInsightsEnabled), updatedConfig.Runtime.Telemetry.ApplicationInsights.Enabled);
Assert.AreEqual("InstrumentationKey=00000000", updatedConfig.Runtime.Telemetry.ApplicationInsights.ConnectionString);
}
/// <summary>
/// This test checks behavior of executing `dab configure --runtime.graphql.depth-limit {value}`.
/// Valid values are [1, INT32.MAX_VALUE], and -1 to remove depth limit.
/// </summary>
[DataTestMethod]
[DataRow("8", true, DisplayName = "Successful update with a valid value for depth limit")]
[DataRow("0", false, DisplayName = "Failure as depth limit cannot be set to 0.")]
[DataRow("-1", true, DisplayName = "Successful update to to remove depth limit using -1.")]
[DataRow("-15", false, DisplayName = "Failure as negative value other than -1 is invalid")]
[DataRow("2147483647", true, DisplayName = "Successful update setting value to INT32_MAX")]
[DataRow("2147483648", false, DisplayName = "Failure when using depth value greater than INT32_MAX")]
[DataRow("seven", false, DisplayName = "Failure when using string value for depth limit")]
public void TestUpdateDepthLimitInGraphQLRuntimeSettings(string depthLimit, bool isSuccess)
{
// Initialize the config file.
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--host-mode", "development", "--database-type",
"mssql", "--connection-string", TEST_ENV_CONN_STRING };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
// Act: Update the depth limit in the config file.
string[] runtimeArgs = { "configure", "-c", TEST_RUNTIME_CONFIG_FILE, "--runtime.graphql.depth-limit", depthLimit };
int isError = Program.Execute(runtimeArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
// Assert: Check if the depth limit was updated successfully.
Assert.AreEqual(isSuccess, isError == 0);
}
/// <summary>
/// This test checks behavior of executing `dab configure --runtime.graphql.path {value}`
/// Validates that path values with permitted characters result in DAB engine starting successfully.
/// Ensures that invalid characters provided for path result in failed engine startup
/// due to validation failure.
/// </summary>
[DataTestMethod]
[DataRow("/updatedPath", true, DisplayName = "Success in updated GraphQL Path to /updatedPath.")]
[DataRow("/updated-Path", true, DisplayName = "Success in updated GraphQL Path to /updated-Path.")]
[DataRow("/updated_Path", true, DisplayName = "Success in updated GraphQL Path to /updated_Path.")]
[DataRow("updatedPath", false, DisplayName = "Failure due to '/' missing.")]
[DataRow("/updated Path", false, DisplayName = "Failure due to white spaces.")]
[DataRow("/updated.Path", false, DisplayName = "Failure due to reserved char '.'.")]
[DataRow("/updated@Path", false, DisplayName = "Failure due reserved chars '@'.")]
[DataRow("/updated/Path", false, DisplayName = "Failure due reserved chars '/'.")]
public void TestUpdateGraphQLPathRuntimeSettings(string path, bool isSuccess)
{
// Initialize the config file.
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--host-mode", "development", "--database-type",
"mssql", "--connection-string", TEST_ENV_CONN_STRING };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
// Act: Update the Path in the config file.
string[] runtimeArgs = { "configure", "-c", TEST_RUNTIME_CONFIG_FILE, "--runtime.graphql.path", path };
int isError = Program.Execute(runtimeArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
// Assert: Check if the Path was updated successfully.
Assert.AreEqual(isSuccess, isError == 0);
}
/// <summary>
/// This test checks behavior of executing `dab configure --runtime.host.cors.origins {value}`
/// Validates that links provided for cors.origins result in DAB engine starting successfully.
/// Ensures that invalid links provided for Cors.Origins result in failed engine startup
/// due to validation failure.
/// </summary>
[Ignore]
[DataTestMethod]
[DataRow("http://locahost1 https://localhost2", true, DisplayName = "Success in updating Host.Cors.Origins.")]
public void TestUpdateHostCorsOriginsRuntimeSettings(string path, bool isSuccess)
{
// Initialize the config file.
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--host-mode", "development", "--database-type",
"mssql", "--connection-string", TEST_ENV_CONN_STRING };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
// Act: Update the Path in the config file.
string[] runtimeArgs = { "configure", "-c", TEST_RUNTIME_CONFIG_FILE, "--runtime.host.cors.origins", path };
int isError = Program.Execute(runtimeArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
// Assert: Check if the Path was updated successfully.
Assert.AreEqual(isSuccess, isError == 0);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedRuntimeConfig));
Assert.AreEqual(2, updatedRuntimeConfig.Runtime?.Host?.Cors?.Origins.Count());
}
/// <summary>
/// This test checks behavior of executing `dab configure --runtime.rest.path {value}`
/// Validates that path values with permitted characters result in DAB engine starting successfully.
/// Ensures that invalid characters provided for path result in failed engine startup
/// due to validation failure.
/// </summary>
[DataTestMethod]
[DataRow("/updatedPath", true, DisplayName = "Successfully updated Rest Path to /updatedPath.")]
[DataRow("/updated-Path", true, DisplayName = "Successfully updated Rest Path to /updated-Path.")]
[DataRow("/updated_Path", true, DisplayName = "Successfully updated Rest Path to /updated_Path.")]
[DataRow("updatedPath", false, DisplayName = "Failure due to '/' missing.")]
[DataRow("/updated Path", false, DisplayName = "Failure due to white spaces.")]
[DataRow("/updated.Path", false, DisplayName = "Failure due to reserved char '.'.")]
[DataRow("/updated@Path", false, DisplayName = "Failure due reserved chars '@'.")]
[DataRow("/updated/Path", false, DisplayName = "Failure due reserved chars '/'.")]
public void TestUpdateRestPathRuntimeSettings(string path, bool isSuccess)
{
// Initialize the config file.
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--host-mode", "development", "--database-type",
"mssql", "--connection-string", TEST_ENV_CONN_STRING };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
// Act: Update the Path in the config file.
string[] runtimeArgs = { "configure", "-c", TEST_RUNTIME_CONFIG_FILE, "--runtime.rest.path", path };
int isError = Program.Execute(runtimeArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
// Assert: Check if the Path was updated successfully.
Assert.AreEqual(isSuccess, isError == 0);
}
/// <summary>
/// This test checks behavior of executing `dab configure --runtime.cache.ttl-seconds {value}`
/// Validates that path values with permitted characters result in DAB engine starting successfully.
/// Ensures that invalid values provided for ttl-seconds result in failed engine startup
/// due to validation failure.
/// Valid values are [1, INT32.MAX_VALUE] Integer values.
/// </summary>
[DataTestMethod]
[DataRow("2", true, DisplayName = "Success in updating Cache TTL to 2.")]
[DataRow("10", true, DisplayName = "Success in updating Cache TTL to 10.")]
[DataRow("-2", false, DisplayName = "Failure to update cache ttl as value is negative.")]
[DataRow("2147483647", true, DisplayName = "Successful update to cache ttl value to INT32_MAX")]
[DataRow("2147483648", false, DisplayName = "Failure to update cache ttl as value greater than INT32_MAX")]
[DataRow("0", false, DisplayName = "Failure to update cache ttl as value is zero.")]
[DataRow("seven", false, DisplayName = "Failure to update cache ttl as a string value.")]
public void TestUpdateCacheTtlRuntimeSettings(string ttl, bool isSuccess)
{
// Initialize the config file.
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--host-mode", "development", "--database-type",
"mssql", "--connection-string", TEST_ENV_CONN_STRING };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
// Act: Update the Cache TTL in the config file.
string[] runtimeArgs = { "configure", "-c", TEST_RUNTIME_CONFIG_FILE, "--runtime.cache.ttl-seconds", ttl };
int isError = Program.Execute(runtimeArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
// Assert: Check if the Cache TTL was updated successfully.
Assert.AreEqual(isSuccess, isError == 0);
}
/// <summary>
/// Test to verify authentication options with init command containing
/// neither EasyAuth or Simulator as Authentication provider.
/// It checks correct generation of config with provider, audience and issuer.
/// </summary>
[DataTestMethod]
[DataRow("AzureAD")]
[DataRow("EntraID")]
public void TestVerifyAuthenticationOptions(string authenticationProvider)
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql",
"--auth.provider", authenticationProvider, "--auth.audience", "aud-xxx", "--auth.issuer", "issuer-xxx" };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.IsNotNull(runtimeConfig.Runtime);
Assert.IsNotNull(runtimeConfig.Runtime.Host);
Assert.AreEqual(authenticationProvider, runtimeConfig.Runtime.Host.Authentication?.Provider);
Assert.AreEqual("aud-xxx", runtimeConfig.Runtime.Host.Authentication?.Jwt?.Audience);
Assert.AreEqual("issuer-xxx", runtimeConfig.Runtime.Host.Authentication?.Jwt?.Issuer);
}
/// <summary>
/// Test to verify that --host-mode is case insensitive.
/// Short forms are not supported.
/// </summary>
[DataTestMethod]
[DataRow("production", HostMode.Production, true)]
[DataRow("Production", HostMode.Production, true)]
[DataRow("development", HostMode.Development, true)]
[DataRow("Development", HostMode.Development, true)]
[DataRow("developer", HostMode.Development, false)]
[DataRow("prod", HostMode.Production, false)]
public void EnsureHostModeEnumIsCaseInsensitive(string hostMode, HostMode hostModeEnumType, bool expectSuccess)
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--host-mode", hostMode, "--database-type", "mssql", "--connection-string", SAMPLE_TEST_CONN_STRING };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig);
if (expectSuccess)
{
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(hostModeEnumType, runtimeConfig.Runtime?.Host?.Mode);
}
else
{
Assert.IsNull(runtimeConfig);
}
}
/// <summary>
/// Test to verify adding a new Entity without IEnumerable options.
/// </summary>
[TestMethod]
public void TestAddEntityWithoutIEnumerable()
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql", "--connection-string", SAMPLE_TEST_CONN_STRING };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig), "Expected to parse the config file.");
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(0, runtimeConfig.Entities.Count()); // No entities
Assert.AreEqual(HostMode.Production, runtimeConfig.Runtime?.Host?.Mode);
string[] addArgs = { "add", "book", "-c", TEST_RUNTIME_CONFIG_FILE, "--source", "s001.book", "--permissions", "anonymous:*" };
Program.Execute(addArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? addRuntimeConfig));
Assert.IsNotNull(addRuntimeConfig);
Assert.AreEqual(1, addRuntimeConfig.Entities.Count()); // 1 new entity added
Assert.IsTrue(addRuntimeConfig.Entities.ContainsKey("book"));
Entity entity = addRuntimeConfig.Entities["book"];
Assert.IsTrue(entity.Rest.Enabled, "REST expected be to enabled");
Assert.IsTrue(entity.GraphQL.Enabled, "GraphQL expected to be enabled");
Assert.AreEqual(1, entity.Permissions.Length);
Assert.AreEqual("anonymous", entity.Permissions[0].Role);
Assert.AreEqual(1, entity.Permissions[0].Actions.Length);
Assert.AreEqual(EntityActionOperation.All, entity.Permissions[0].Actions[0].Action);
Assert.IsNull(entity.Mappings);
Assert.IsNull(entity.Relationships);
}
/// <summary>
/// Test the exact config json generated to verify adding a new Entity without IEnumerable options.
/// </summary>
[TestMethod]
public Task TestConfigGeneratedAfterAddingEntityWithoutIEnumerables()
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql", "--connection-string", SAMPLE_TEST_CONN_STRING,
"--set-session-context", "true" };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(0, runtimeConfig.Entities.Count()); // No entities
string[] addArgs = { "add", "book", "-c", TEST_RUNTIME_CONFIG_FILE, "--source", "s001.book", "--permissions", "anonymous:*" };
Program.Execute(addArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedRuntimeConfig));
Assert.AreNotSame(runtimeConfig, updatedRuntimeConfig);
return Verify(updatedRuntimeConfig);
}
/// <summary>
/// Test the exact config json generated to verify adding source as stored-procedure.
/// </summary>
[TestMethod]
public Task TestConfigGeneratedAfterAddingEntityWithSourceAsStoredProcedure()
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql",
"--host-mode", "Development", "--connection-string", SAMPLE_TEST_CONN_STRING, "--set-session-context", "true" };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(0, runtimeConfig.Entities.Count()); // No entities
string[] addArgs = { "add", "MyEntity", "-c", TEST_RUNTIME_CONFIG_FILE, "--source", "s001.book", "--permissions", "anonymous:execute", "--source.type", "stored-procedure", "--source.params", "param1:123,param2:hello,param3:true" };
Program.Execute(addArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedRuntimeConfig));
Assert.AreNotSame(runtimeConfig, updatedRuntimeConfig);
return Verify(updatedRuntimeConfig);
}
/// <summary>
/// Validate update command for stored procedures by verifying the config json generated
/// </summary>
[TestMethod]
public Task TestConfigGeneratedAfterUpdatingEntityWithSourceAsStoredProcedure()
{
string runtimeConfigJson = AddPropertiesToJson(INITIAL_CONFIG, SINGLE_ENTITY_WITH_STORED_PROCEDURE);
_fileSystem!.File.WriteAllText(TEST_RUNTIME_CONFIG_FILE, runtimeConfigJson);
// args for update command to update the source name from "s001.book" to "dbo.books"
string[] updateArgs = { "update", "MyEntity", "-c", TEST_RUNTIME_CONFIG_FILE, "--source", "dbo.books" };
_ = Program.Execute(updateArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig), "Failed to load config.");
Entity entity = runtimeConfig.Entities["MyEntity"];
return Verify(entity);
}
/// <summary>
/// Validates the config json generated when a stored procedure is added with both
/// --rest.methods and --graphql.operation options.
/// </summary>
[TestMethod]
public Task TestAddingStoredProcedureWithRestMethodsAndGraphQLOperations()
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql",
"--host-mode", "Development", "--connection-string", SAMPLE_TEST_CONN_STRING, "--set-session-context", "true" };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(0, runtimeConfig.Entities.Count()); // No entities
string[] addArgs = { "add", "MyEntity", "-c", TEST_RUNTIME_CONFIG_FILE, "--source", "s001.book", "--permissions", "anonymous:execute", "--source.type", "stored-procedure", "--source.params", "param1:123,param2:hello,param3:true", "--rest.methods", "post,put,patch", "--graphql.operation", "query" };
Program.Execute(addArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedRuntimeConfig));
Assert.AreNotSame(runtimeConfig, updatedRuntimeConfig);
return Verify(updatedRuntimeConfig);
}
/// <summary>
/// Validates that CLI execution of the add/update commands results in a stored procedure entity
/// with explicit rest method GET and GraphQL endpoint disabled.
/// </summary>
[TestMethod]
public Task TestUpdatingStoredProcedureWithRestMethodsAndGraphQLOperations()
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql",
"--host-mode", "Development", "--connection-string", SAMPLE_TEST_CONN_STRING, "--set-session-context", "true" };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(0, runtimeConfig.Entities.Count()); // No entities
string[] addArgs = { "add", "MyEntity", "-c", TEST_RUNTIME_CONFIG_FILE, "--source", "s001.book", "--permissions", "anonymous:execute", "--source.type", "stored-procedure", "--source.params", "param1:123,param2:hello,param3:true", "--rest.methods", "post,put,patch", "--graphql.operation", "query" };
Program.Execute(addArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedRuntimeConfig));
Assert.AreNotSame(runtimeConfig, updatedRuntimeConfig);
string[] updateArgs = { "update", "MyEntity", "-c", TEST_RUNTIME_CONFIG_FILE, "--rest.methods", "get", "--graphql", "false" };
Program.Execute(updateArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedRuntimeConfig2));
Assert.AreNotSame(updatedRuntimeConfig, updatedRuntimeConfig2);
return Verify(updatedRuntimeConfig2);
}
/// <summary>
/// Test the exact config json generated to verify adding a new Entity with default source type and given key-fields.
/// </summary>
[TestMethod]
public Task TestConfigGeneratedAfterAddingEntityWithSourceWithDefaultType()
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql", "--host-mode", "Development",
"--connection-string", SAMPLE_TEST_CONN_STRING, "--set-session-context", "true" };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(0, runtimeConfig.Entities.Count()); // No entities
string[] addArgs = { "add", "MyEntity", "-c", TEST_RUNTIME_CONFIG_FILE, "--source", "s001.book", "--permissions", "anonymous:*", "--source.key-fields", "id,name" };
Program.Execute(addArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedRuntimeConfig));
Assert.AreNotSame(runtimeConfig, updatedRuntimeConfig);
return Verify(updatedRuntimeConfig);
}
/// <summary>
/// Test to verify updating an existing Entity.
/// It tests updating permissions as well as relationship
/// </summary>
[TestMethod]
public void TestUpdateEntity()
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type",
"mssql", "--connection-string", TEST_ENV_CONN_STRING };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(0, runtimeConfig.Entities.Count()); // No entities
string[] addArgs = {"add", "todo", "-c", TEST_RUNTIME_CONFIG_FILE,
"--source", "s001.todo", "--rest", "todo",
"--graphql", "todo", "--permissions", "anonymous:*"};
Program.Execute(addArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? addRuntimeConfig));
Assert.IsNotNull(addRuntimeConfig);
Assert.AreEqual(1, addRuntimeConfig.Entities.Count()); // 1 new entity added
// Adding another entity
//
string[] addArgs_2 = {"add", "books", "-c", TEST_RUNTIME_CONFIG_FILE,
"--source", "s001.books", "--rest", "books",
"--graphql", "books", "--permissions", "anonymous:*"};
Program.Execute(addArgs_2, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? addRuntimeConfig2));
Assert.IsNotNull(addRuntimeConfig2);
Assert.AreEqual(2, addRuntimeConfig2.Entities.Count()); // 1 more entity added
string[] updateArgs = {"update", "todo", "-c", TEST_RUNTIME_CONFIG_FILE,
"--source", "s001.todos","--graphql", "true",
"--permissions", "anonymous:create,delete",
"--fields.include", "id,content", "--fields.exclude", "rating,level",
"--relationship", "r1", "--cardinality", "one",
"--target.entity", "books", "--relationship.fields", "id:book_id",
"--linking.object", "todo_books",
"--linking.source.fields", "todo_id",
"--linking.target.fields", "id",
"--map", "id:identity,name:Company Name"};
Program.Execute(updateArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updateRuntimeConfig));
Assert.IsNotNull(updateRuntimeConfig);
Assert.AreEqual(TEST_ENV_CONN_STRING, updateRuntimeConfig.DataSource.ConnectionString);
Assert.AreEqual(2, updateRuntimeConfig.Entities.Count()); // No new entity added
Assert.IsTrue(updateRuntimeConfig.Entities.ContainsKey("todo"));
Entity entity = updateRuntimeConfig.Entities["todo"];
Assert.AreEqual("/todo", entity.Rest.Path);
Assert.IsNotNull(entity.GraphQL);
Assert.IsTrue(entity.GraphQL.Enabled);
//The value in entity.GraphQL is true/false, we expect the serialization to be a string.
Assert.AreEqual(true, entity.GraphQL.Enabled);
Assert.AreEqual(1, entity.Permissions.Length);
Assert.AreEqual("anonymous", entity.Permissions[0].Role);
Assert.AreEqual(4, entity.Permissions[0].Actions.Length);
//Only create and delete are updated.
EntityAction action = entity.Permissions[0].Actions.First(a => a.Action == EntityActionOperation.Create);
Assert.AreEqual(2, action.Fields?.Include?.Count);
Assert.AreEqual(2, action.Fields?.Exclude?.Count);
Assert.IsTrue(action.Fields?.Include?.Contains("id"));
Assert.IsTrue(action.Fields?.Include?.Contains("content"));
Assert.IsTrue(action.Fields?.Exclude?.Contains("rating"));
Assert.IsTrue(action.Fields?.Exclude?.Contains("level"));
action = entity.Permissions[0].Actions.First(a => a.Action == EntityActionOperation.Delete);
Assert.AreEqual(2, action.Fields?.Include?.Count);
Assert.AreEqual(2, action.Fields?.Exclude?.Count);
Assert.IsTrue(action.Fields?.Include?.Contains("id"));
Assert.IsTrue(action.Fields?.Include?.Contains("content"));
Assert.IsTrue(action.Fields?.Exclude?.Contains("rating"));
Assert.IsTrue(action.Fields?.Exclude?.Contains("level"));
action = entity.Permissions[0].Actions.First(a => a.Action == EntityActionOperation.Read);
Assert.IsNull(action.Fields?.Include);
Assert.IsNull(action.Fields?.Exclude);
action = entity.Permissions[0].Actions.First(a => a.Action == EntityActionOperation.Update);
Assert.IsNull(action.Fields?.Include);
Assert.IsNull(action.Fields?.Exclude);
Assert.IsTrue(entity.Relationships!.ContainsKey("r1"));
EntityRelationship relationship = entity.Relationships["r1"];
Assert.AreEqual(1, entity.Relationships.Count);
Assert.AreEqual(Cardinality.One, relationship.Cardinality);
Assert.AreEqual("books", relationship.TargetEntity);
Assert.AreEqual("todo_books", relationship.LinkingObject);
CollectionAssert.AreEqual(new string[] { "id" }, relationship.SourceFields);
CollectionAssert.AreEqual(new string[] { "book_id" }, relationship.TargetFields);
CollectionAssert.AreEqual(new string[] { "todo_id" }, relationship.LinkingSourceFields);
CollectionAssert.AreEqual(new string[] { "id" }, relationship.LinkingTargetFields);
Assert.IsNotNull(entity.Fields);
Assert.AreEqual(2, entity.Fields.Count);
Assert.AreEqual(entity.Fields[0].Alias, "identity");
Assert.AreEqual(entity.Fields[1].Alias, "Company Name");
Assert.IsNull(entity.Mappings);
}
/// <summary>
/// Validates the updation of REST Methods for a stored procedure entity
/// </summary>
[TestMethod]
public Task TestUpdatingStoredProcedureWithRestMethods()
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql",
"--host-mode", "Development", "--connection-string", SAMPLE_TEST_CONN_STRING, "--set-session-context", "true" };
Program.Execute(initArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? runtimeConfig));
Assert.IsNotNull(runtimeConfig);
Assert.AreEqual(0, runtimeConfig.Entities.Count()); // No entities
string[] addArgs = { "add", "MyEntity", "-c", TEST_RUNTIME_CONFIG_FILE, "--source", "s001.book", "--permissions", "anonymous:execute", "--source.type", "stored-procedure", "--source.params", "param1:123,param2:hello,param3:true", "--rest.methods", "post,put,patch", "--graphql.operation", "query" };
Program.Execute(addArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedRuntimeConfig));
Assert.AreNotSame(runtimeConfig, updatedRuntimeConfig);
string[] updateArgs = { "update", "MyEntity", "-c", TEST_RUNTIME_CONFIG_FILE, "--rest.methods", "get" };
Program.Execute(updateArgs, _cliLogger!, _fileSystem!, _runtimeConfigLoader!);
Assert.IsTrue(_runtimeConfigLoader!.TryLoadConfig(TEST_RUNTIME_CONFIG_FILE, out RuntimeConfig? updatedRuntimeConfig2));
Assert.AreNotSame(updatedRuntimeConfig, updatedRuntimeConfig2);
return Verify(updatedRuntimeConfig2);
}
/// <summary>
/// Test to validate that the engine starts successfully when --verbose and --LogLevel
/// options are used with the start command
/// This test does not validate whether the engine logs messages at the specified log level
/// </summary>
/// <param name="logLevelOption">Log level options</param>
[DataTestMethod]
[DataRow("", DisplayName = "No logging from command line.")]
[DataRow("--verbose", DisplayName = "Verbose logging from command line.")]
[DataRow("--LogLevel 0", DisplayName = "LogLevel 0 from command line.")]
[DataRow("--LogLevel 1", DisplayName = "LogLevel 1 from command line.")]
[DataRow("--LogLevel 2", DisplayName = "LogLevel 2 from command line.")]
[DataRow("--LogLevel 3", DisplayName = "LogLevel 3 from command line.")]
[DataRow("--LogLevel 4", DisplayName = "LogLevel 4 from command line.")]
[DataRow("--LogLevel 5", DisplayName = "LogLevel 5 from command line.")]
[DataRow("--LogLevel 6", DisplayName = "LogLevel 6 from command line.")]
[DataRow("--LogLevel Trace", DisplayName = "LogLevel Trace from command line.")]
[DataRow("--LogLevel Debug", DisplayName = "LogLevel Debug from command line.")]
[DataRow("--LogLevel Information", DisplayName = "LogLevel Information from command line.")]
[DataRow("--LogLevel Warning", DisplayName = "LogLevel Warning from command line.")]
[DataRow("--LogLevel Error", DisplayName = "LogLevel Error from command line.")]
[DataRow("--LogLevel Critical", DisplayName = "LogLevel Critical from command line.")]
[DataRow("--LogLevel None", DisplayName = "LogLevel None from command line.")]
[DataRow("--LogLevel tRace", DisplayName = "Case sensitivity: LogLevel Trace from command line.")]
[DataRow("--LogLevel DebUG", DisplayName = "Case sensitivity: LogLevel Debug from command line.")]
[DataRow("--LogLevel information", DisplayName = "Case sensitivity: LogLevel Information from command line.")]
[DataRow("--LogLevel waRNing", DisplayName = "Case sensitivity: LogLevel Warning from command line.")]
[DataRow("--LogLevel eRROR", DisplayName = "Case sensitivity: LogLevel Error from command line.")]
[DataRow("--LogLevel CrItIcal", DisplayName = "Case sensitivity: LogLevel Critical from command line.")]
[DataRow("--LogLevel NONE", DisplayName = "Case sensitivity: LogLevel None from command line.")]
public void TestEngineStartUpWithVerboseAndLogLevelOptions(string logLevelOption)
{
_fileSystem!.File.WriteAllText(TEST_RUNTIME_CONFIG_FILE, INITIAL_CONFIG);
using Process process = ExecuteDabCommand(
command: $"start --config {TEST_RUNTIME_CONFIG_FILE}",
logLevelOption
);
string? output = process.StandardOutput.ReadLine();
Assert.IsNotNull(output);
StringAssert.Contains(output, $"{Program.PRODUCT_NAME} {ProductInfo.GetProductVersion()}", StringComparison.Ordinal);
output = process.StandardOutput.ReadLine();
process.Kill();
Assert.IsNotNull(output);
StringAssert.Contains(output, $"User provided config file: {TEST_RUNTIME_CONFIG_FILE}", StringComparison.Ordinal);
}
/// <summary>
/// Validates that valid usage of verbs and associated options produce exit code 0 (CliReturnCode.SUCCESS).
/// Verifies that explicitly implemented verbs (add, update, init, start) and appropriately
/// supplied options produce exit code 0.
/// Verifies that non-explicitly implemented DAB CLI options `--help` and `--version` produce exit code 0.
/// init --config "dab-config.MsSql.json" --database-type mssql --connection-string "InvalidConnectionString"
/// </summary>
[DataTestMethod]
[DataRow(new string[] { "--version" }, DisplayName = "Checking version.")]
[DataRow(new string[] { "--help" }, DisplayName = "Valid verbs with help.")]
[DataRow(new string[] { "add", "--help" }, DisplayName = "Valid options with help.")]
[DataRow(new string[] { "init", "--database-type", "mssql", "-c", TEST_RUNTIME_CONFIG_FILE }, DisplayName = "Valid verb with supported option.")]
public void ValidVerbsAndOptionsReturnZero(string[] cliArguments)
{
Assert.AreEqual(expected: CliReturnCode.SUCCESS, actual: Program.Execute(cliArguments, _cliLogger!, _fileSystem!, _runtimeConfigLoader!));
}
/// <summary>
/// Validates that invalid verbs and options produce exit code -1 (CliReturnCode.GENERAL_ERROR).
/// </summary>
/// <param name="cliArguments">cli verbs, options, and option values</param>
[DataTestMethod]
[DataRow(new string[] { "--remove-telemetry" }, DisplayName = "Usage of non-existent verb remove-telemetry")]
[DataRow(new string[] { "--initialize" }, DisplayName = "Usage of invalid verb (longform of init not supported) initialize")]
[DataRow(new string[] { "init", "--database-name", "mssql" }, DisplayName = "Invalid init options database-name")]
public void InvalidVerbsAndOptionsReturnNonZeroExitCode(string[] cliArguments)
{
Assert.AreEqual(expected: CliReturnCode.GENERAL_ERROR, actual: Program.Execute(cliArguments, _cliLogger!, _fileSystem!, _runtimeConfigLoader!));
}
/// <summary>
/// Usage of valid verbs and options with values triggering exceptions should produce a non-zero exit code.
/// - File read/write issues when reading/writing to the config file.
/// - DAB engine failure.
/// </summary>
/// <param name="cliArguments">cli verbs, options, and option values</param>
[DataTestMethod]
[DataRow(new string[] { "init", "--config", "dab-config-empty.json", "--database-type", "mssql", "--connection-string", "SampleValue" },
DisplayName = "Config file value used already exists on the file system and results in init failure.")]
[DataRow(new string[] { "start", "--config", "dab-config-empty.json" }, DisplayName = "Config file value used is empty and engine startup fails")]
public void CliAndEngineFailuresReturnNonZeroExitCode(string[] cliArguments)
{
Assert.AreEqual(expected: CliReturnCode.GENERAL_ERROR, actual: Program.Execute(cliArguments, _cliLogger!, _fileSystem!, _runtimeConfigLoader!));
}
/// <summary>
/// Test to verify that if entity is not specified in the add/update
/// command, a custom (more user friendly) message is displayed.
/// NOTE: Below order of execution is important, changing the order for DataRow might result in test failures.
/// The below order makes sure entity is added before update.
/// </summary>
[DataRow("add", "", "-s my_entity --permissions anonymous:create", false)]
[DataRow("add", "MyEntity", "-s my_entity --permissions anonymous:create", true)]
[DataRow("update", "", "-s my_entity --permissions authenticate:*", false)]
[DataRow("update", "MyEntity", "-s my_entity --permissions authenticate:*", true)]
[DataTestMethod]
public void TestMissingEntityFromCommand(
string command,
string entityName,
string flags,
bool expectSuccess)
{
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql" };
StringLogger logger = new();
Program.Execute(initArgs, logger, _fileSystem!, _runtimeConfigLoader!);
logger = new();
string[] args = $"{command} {entityName} -c {TEST_RUNTIME_CONFIG_FILE} {flags}".Split(' ');
Program.Execute(args, logger, _fileSystem!, _runtimeConfigLoader!);
if (!expectSuccess)
{
string output = logger.GetLog();
StringAssert.Contains(output, $"Entity name is missing. Usage: dab {command} [entity-name] [{command}-options]", StringComparison.Ordinal);
}
}
/// <summary>
/// Test to verify that help writer window generates output on the console.
/// Every test here validates that the first line of the output contains the product name and version.
/// </summary>
[DataTestMethod]
[DataRow("", "", new string[] { "ERROR" }, DisplayName = "No flags provided.")]
[DataRow("initialize", "", new string[] { "ERROR", "Verb 'initialize' is not recognized." }, DisplayName = "Wrong Command provided.")]
[DataRow("", "--help", new string[] { "init", "add", "update", "start" }, DisplayName = "Checking output for --help.")]
public void TestHelpWriterOutput(string command, string flags, string[] expectedOutputArray)
{
using Process process = ExecuteDabCommand(command, flags);
string? output = process.StandardOutput.ReadToEnd();
Assert.IsNotNull(output);
StringAssert.Contains(output, $"{Program.PRODUCT_NAME} {ProductInfo.GetProductVersion(includeCommitHash: true)}", StringComparison.Ordinal);
foreach (string expectedOutput in expectedOutputArray)
{
StringAssert.Contains(output, expectedOutput, StringComparison.Ordinal);
}
process.Kill();
}
/// <summary>
/// When CLI is started via: dab --version, it should print the version number
/// which includes the commit hash. For example:
/// Microsoft.DataApiBuilder 0.12+2d181463e5dd46cf77fea31b7295c4e02e8ef031
/// </summary>
[TestMethod]
public void TestVersionHasBuildHash()
{
_fileSystem!.File.WriteAllText(TEST_RUNTIME_CONFIG_FILE, INITIAL_CONFIG);
using Process process = ExecuteDabCommand(
command: string.Empty,
flags: $"--config {TEST_RUNTIME_CONFIG_FILE} --version"
);
string? output = process.StandardOutput.ReadLine();
Assert.IsNotNull(output);
// Check that the build hash is returned as part of the version number.
string[] versionParts = output.Split('+');
Assert.AreEqual(2, versionParts.Length, "Build hash not returned as part of version number.");
Assert.AreEqual(40, versionParts[1].Length, "Build hash is not of expected length.");
process.Kill();
}
/// <summary>
/// For valid CLI commands (Valid verbs and options) validate that the correct
/// version is logged (without commit hash) and that the config file name is printed to console.
/// </summary>
[DataRow("init", "--database-type mssql", DisplayName = "Version printed with valid command init.")]
[DataRow("add", "MyEntity -s my_entity --permissions \"anonymous:*\"", DisplayName = "Version printed with valid command add.")]
[DataRow("update", "MyEntity -s my_entity", DisplayName = "Version printed with valid command update.")]
[DataRow("start", "", DisplayName = "Version printed with valid command start.")]
[DataTestMethod]
public void ValidCliVerbsAndOptions_DisplayVersionAndConfigFileName(
string command,
string options)
{
_fileSystem!.File.WriteAllText(TEST_RUNTIME_CONFIG_FILE, INITIAL_CONFIG);