-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathEnvironmentTests.cs
More file actions
197 lines (168 loc) · 7.91 KB
/
EnvironmentTests.cs
File metadata and controls
197 lines (168 loc) · 7.91 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Azure.DataApiBuilder.Config.Converters;
namespace Cli.Tests;
/// <summary>
/// Contains test involving environment variables.
/// </summary>
[TestClass]
public class EnvironmentTests
: VerifyBase
{
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
private JsonSerializerOptions _options;
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
[TestInitialize]
public void TestInitialize()
{
DeserializationVariableReplacementSettings replacementSettings = new(
azureKeyVaultOptions: null,
doReplaceEnvVar: true,
doReplaceAkvVar: false,
envFailureMode: EnvironmentVariableReplacementFailureMode.Throw);
StringJsonConverterFactory converterFactory = new(replacementSettings);
_options = new()
{
PropertyNameCaseInsensitive = true
};
_options.Converters.Add(converterFactory);
}
record TestObject(string? EnvValue, string? HostingEnvValue);
public const string TEST_ENV_VARIABLE = "DAB_TEST_ENVIRONMENT";
/// <summary>
/// Test to verify that environment variable setup in the system is picked up correctly
/// when no .env file is present.
/// </summary>
[TestMethod]
public async Task TestEnvironmentVariableIsConsumedCorrectly()
{
string jsonWithEnvVariable = @"{""envValue"": ""@env('DAB_TEST_ENVIRONMENT')""}";
// No environment File, No environment variable set in the system
Assert.AreEqual(null, Environment.GetEnvironmentVariable(TEST_ENV_VARIABLE));
// Configuring environment variable in the system
Environment.SetEnvironmentVariable(TEST_ENV_VARIABLE, "TEST");
// Test environment variable is correctly resolved in the config file
TestObject? result = JsonSerializer.Deserialize<TestObject>(jsonWithEnvVariable, _options);
await Verify(result);
// removing Environment variable from the System
Environment.SetEnvironmentVariable(TEST_ENV_VARIABLE, null);
Assert.ThrowsException<DataApiBuilderException>(() =>
JsonSerializer.Deserialize<TestObject>(jsonWithEnvVariable, _options),
$"Environmental Variable, {TEST_ENV_VARIABLE}, not found.");
}
/// <summary>
/// This test creates a .env file and adds a variable and verifies that the variable is
/// correctly consumed.
/// For this test there were no existing environment variables. The values are picked up
/// directly from the `.env` file.
/// </summary>
[TestMethod]
public Task TestEnvironmentFileIsConsumedCorrectly()
{
string jsonWithEnvVariable = @"{""envValue"": ""@env('DAB_TEST_ENVIRONMENT')""}";
// No environment File, no environment variable set in the system
Assert.IsNull(Environment.GetEnvironmentVariable(TEST_ENV_VARIABLE));
// Creating environment variable file
File.Create(".env").Close();
File.WriteAllText(".env", $"{TEST_ENV_VARIABLE}=DEVELOPMENT");
DotNetEnv.Env.Load();
// Test environment variable is picked up from the .env file and is correctly resolved in the config file.
Assert.AreEqual("DEVELOPMENT", Environment.GetEnvironmentVariable(TEST_ENV_VARIABLE));
TestObject? result = JsonSerializer.Deserialize<TestObject>(jsonWithEnvVariable, _options);
return Verify(result);
}
/// <summary>
/// This test setups an environment variable in the system and also creates a .env file containing
/// the same variable with different value. In such a case, the value stored for variable in .env file is given
/// precedence over the value specified in the system.
/// </summary>
[TestMethod]
public Task TestPrecedenceOfEnvironmentFileOverExistingVariables()
{
// The variable set in the .env file takes precedence over the environment value set in the system.
Environment.SetEnvironmentVariable(TEST_ENV_VARIABLE, "TEST");
// Creating environment variable file
File.Create(".env").Close();
File.WriteAllText(".env", $"{TEST_ENV_VARIABLE}=DEVELOPMENT");
DotNetEnv.Env.Load(); // It contains value DEVELOPMENT
Assert.AreEqual("DEVELOPMENT", Environment.GetEnvironmentVariable(TEST_ENV_VARIABLE));
// If a variable is not present in the .env file then the system defined variable would be used if defined.
Environment.SetEnvironmentVariable("HOSTING_TEST_ENVIRONMENT", "PHOENIX_TEST");
TestObject? result = JsonSerializer.Deserialize<TestObject>(
@"{
""envValue"": ""@env('DAB_TEST_ENVIRONMENT')"",
""hostingEnvValue"": ""@env('HOSTING_TEST_ENVIRONMENT')""
}", options: _options);
return Verify(result);
}
/// <summary>
/// Test to verify that no error is thrown if .env file is not present, and existing system variables are used.
/// </summary>
[TestMethod]
public void TestSystemEnvironmentVariableIsUsedInAbsenceOfEnvironmentFile()
{
Environment.SetEnvironmentVariable(TEST_ENV_VARIABLE, "TEST");
Assert.IsFalse(File.Exists(".env"));
DotNetEnv.Env.Load(); // No error is thrown
Assert.AreEqual("TEST", Environment.GetEnvironmentVariable(TEST_ENV_VARIABLE));
}
[TestMethod]
public void TestStartWithEnvFileIsSuccessful()
{
string expectedEnvVarName = "CONN_STRING";
BootstrapTestEnvironment(expectedEnvVarName + "=test_connection_string", expectedEnvVarName);
// Trying to start the runtime engine
using Process process = ExecuteDabCommand(
"start",
$"-c {TEST_RUNTIME_CONFIG_FILE}"
);
Assert.IsFalse(process.StandardError.BaseStream.CanSeek, "Should not be able to seek stream as there should be no errors.");
process.Kill();
}
/// <summary>
/// Validates that engine startup fails when the CONN_STRING environment
/// variable is not found. This test simulates this by defining the
/// environment variable COMM_STRINGX and not setting the expected
/// variable CONN_STRING. This will cause an exception during the post
/// processing of the deserialization of the config. We verify the expected
/// error message returns.
/// </summary>
[TestMethod]
public async Task FailureToStartEngineWhenEnvVarNamedWrong()
{
string expectedEnvVarName = "WRONG_CONN_STRING";
BootstrapTestEnvironment("COMM_STRINX=test_connection_string", expectedEnvVarName);
// Trying to start the runtime engine
using Process process = ExecuteDabCommand(
"start",
$"-c {TEST_RUNTIME_CONFIG_FILE}"
);
string? output = await process.StandardError.ReadLineAsync();
Assert.IsNotNull(output);
// Clean error message on stderr with no stack trace.
StringAssert.Contains(output, "A valid Connection String should be provided.", StringComparison.Ordinal);
process.Kill();
}
private static void BootstrapTestEnvironment(string envFileContents, string connStringEnvName)
{
// Creating environment variable file
File.Create(".env").Close();
File.WriteAllText(".env", envFileContents);
if (File.Exists(TEST_RUNTIME_CONFIG_FILE))
{
File.Delete(TEST_RUNTIME_CONFIG_FILE);
}
string[] initArgs = { "init", "-c", TEST_RUNTIME_CONFIG_FILE, "--database-type", "mssql",
"--connection-string", "@env('" + connStringEnvName + "')" };
Program.Main(initArgs);
}
[TestCleanup]
public void CleanUp()
{
if (File.Exists(".env"))
{
File.Delete(".env");
}
Environment.SetEnvironmentVariable(TEST_ENV_VARIABLE, null);
}
}