-
Notifications
You must be signed in to change notification settings - Fork 773
/
Copy pathBuildParamsCommandTests.cs
546 lines (447 loc) · 23.2 KB
/
BuildParamsCommandTests.cs
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Azure;
using Azure.Containers.ContainerRegistry;
using Bicep.Cli.Models;
using Bicep.Cli.UnitTests.Assertions;
using Bicep.Core.Configuration;
using Bicep.Core.Extensions;
using Bicep.Core.Registry;
using Bicep.Core.Samples;
using Bicep.Core.UnitTests.Assertions;
using Bicep.Core.UnitTests.Baselines;
using Bicep.Core.UnitTests.Mock;
using Bicep.Core.UnitTests.Utils;
using FluentAssertions;
using FluentAssertions.Execution;
using Microsoft.CodeAnalysis.Sarif;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.ResourceStack.Common.Json;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Bicep.Cli.IntegrationTests
{
[TestClass]
public class BuildParamsCommandTests : TestBase
{
private InvocationSettings Settings
=> new()
{
Environment = TestEnvironment.Create(
("stringEnvVariableName", "test"),
("intEnvVariableName", "100"),
("boolEnvironmentVariable", "true")
)
};
[TestMethod]
public async Task Build_Params_With_Incorrect_Bicep_File_Extension_ShouldFail_WithExpectedErrorMessage()
{
var bicepparamsPath = FileHelper.SaveResultFile(TestContext, "input.bicepparam", "using './main.bicep'");
var bicepPath = FileHelper.SaveResultFile(TestContext, "main.wrongExt", "", Path.GetDirectoryName(bicepparamsPath));
var outputFilePath = FileHelper.GetResultFilePath(TestContext, "output.json");
File.Exists(outputFilePath).Should().BeFalse();
var (output, error, result) = await Bicep(Settings, "build-params", bicepparamsPath, "--bicep-file", bicepPath, "--outfile", outputFilePath);
result.Should().Be(1);
output.Should().BeEmpty();
error.Should().Contain($"\"{bicepPath}\" was not recognized as a Bicep file.");
}
[TestMethod]
public async Task Build_Params_With_CLI_Input_And_Using_Declaration_Bicep_File_Reference_Mismatch_ShouldFail_WithExpectedErrorMessage()
{
var bicepparamsPath = FileHelper.SaveResultFile(TestContext, "input.bicepparam", "using './main.bicep'");
var bicepPath = FileHelper.SaveResultFile(TestContext, "main.bicep", "", Path.GetDirectoryName(bicepparamsPath));
var otherBicepPath = FileHelper.SaveResultFile(TestContext, "otherMain.bicep", "", Path.GetDirectoryName(bicepparamsPath));
var outputFilePath = FileHelper.GetResultFilePath(TestContext, "output.json");
File.Exists(outputFilePath).Should().BeFalse();
var result = await Bicep(Settings, "build-params", bicepparamsPath, "--bicep-file", otherBicepPath, "--outfile", outputFilePath);
result.Should().Fail().And.HaveStderrMatch($"Bicep file {otherBicepPath} provided with --bicep-file option doesn't match the Bicep file {bicepPath} referenced by the \"using\" declaration in the parameters file.*");
}
[TestMethod]
public async Task Build_Params_Bicep_File_Reference_Mismatch_And_Other_Diagnostics_ShouldFail_WithAllExpectedErrorMessages()
{
var bicepparamsPath = FileHelper.SaveResultFile(TestContext, "input.bicepparam",
@"
using './main.bicep'
param foo = 'bar'
");
var bicepPath = FileHelper.SaveResultFile(TestContext, "main.bicep", "param foo object", Path.GetDirectoryName(bicepparamsPath));
var otherBicepPath = FileHelper.SaveResultFile(TestContext, "otherMain.bicep", "", Path.GetDirectoryName(bicepparamsPath));
var outputFilePath = FileHelper.GetResultFilePath(TestContext, "output.json");
var result = await Bicep(Settings, "build-params", bicepparamsPath, "--bicep-file", otherBicepPath, "--outfile", outputFilePath);
result.Should().Fail().And.HaveStderrMatch($"Bicep file {otherBicepPath} provided with --bicep-file option doesn't match the Bicep file {bicepPath} referenced by the \"using\" declaration in the parameters file.*");
File.Exists(outputFilePath).Should().BeFalse();
}
[TestMethod]
public async Task Build_params_with_correct_overrides_succeeds_with_values_overridden()
{
var bicepparamsPath = FileHelper.SaveResultFile(
TestContext,
"input.bicepparam",
"""
using './main.bicep'
param strParam = 'foo'
param intParam = 0
param boolParam = false
param arrParam = [1, 2]
param objParam = {
someProp: 'someValue'
}
""");
FileHelper.SaveResultFile(
TestContext,
"main.bicep",
"""
param strParam string
param intParam int
param boolParam bool
param arrParam array
param objParam object
""",
Path.GetDirectoryName(bicepparamsPath));
var paramsOverrides = """
{
"strParam" : "bar",
"intParam" : 1,
"boolParam" : true,
"arrParam" : [3, 4],
"objParam" : {
otherProp: "otherValue"
}
}
""";
var settings = Settings with
{
Environment = TestEnvironment.Create(
("BICEP_PARAMETERS_OVERRIDES", paramsOverrides)
)
};
var outputFilePath = FileHelper.GetResultFilePath(TestContext, "output.json");
File.Exists(outputFilePath).Should().BeFalse();
var result = await Bicep(settings, "build-params", bicepparamsPath, "--stdout");
result.Should().Succeed();
var parametersStdout = result.Stdout.FromJson<BuildParamsStdout>();
var paramsObject = parametersStdout.parametersJson.FromJson<JToken>();
paramsObject.Should().HaveValueAtPath("parameters.strParam.value", "bar");
paramsObject.Should().HaveValueAtPath("parameters.intParam.value", 1);
paramsObject.Should().HaveValueAtPath("parameters.boolParam.value", true);
paramsObject.Should().HaveValueAtPath("parameters.arrParam.value", JToken.Parse("[3, 4]"));
paramsObject.Should().HaveValueAtPath("parameters.objParam.value", JToken.Parse(
"""
{
otherProp: "otherValue"
}
"""));
}
[TestMethod]
public async Task Build_params_with_default_value_override_succeeds()
{
var bicepparamsPath = FileHelper.SaveResultFile(
TestContext,
"input.bicepparam", """
using 'main.bicep'
""");
FileHelper.SaveResultFile(
TestContext,
"main.bicep", """
param foo string = 'default'
output foo string = foo
""",
Path.GetDirectoryName(bicepparamsPath));
var environment = TestEnvironment.Create(("BICEP_PARAMETERS_OVERRIDES", new
{
foo = "bar"
}.ToJson()));
var settings = Settings with { Environment = environment };
var result = await Bicep(settings, "build-params", bicepparamsPath, "--stdout");
result.Should().NotHaveStderr();
result.Should().Succeed();
var parametersStdout = result.Stdout.FromJson<BuildParamsStdout>();
var paramsObject = parametersStdout.parametersJson.FromJson<JToken>();
paramsObject.Should().DeepEqual(JToken.Parse("""
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"foo": {
"value": "bar"
}
}
}
"""));
}
[TestMethod]
public async Task Build_params_with_incorrect_default_value_override_fails()
{
var bicepparamsPath = FileHelper.SaveResultFile(
TestContext,
"input.bicepparam", """
using 'main.bicep'
""");
FileHelper.SaveResultFile(
TestContext,
"main.bicep", """
param foo string = 'default'
output foo string = foo
""",
Path.GetDirectoryName(bicepparamsPath));
var environment = TestEnvironment.Create(("BICEP_PARAMETERS_OVERRIDES", new
{
wrongName = "bar"
}.ToJson()));
var settings = Settings with { Environment = environment };
var result = await Bicep(settings, "build-params", bicepparamsPath, "--stdout");
result.Should().Fail().And.HaveStderrMatch($"*Error BCP259: The parameter \"wrongName\" is assigned in the params file without being declared in the Bicep file.*");
}
[TestMethod]
public async Task Build_params_with_overrides_with_mismatch_type_fails_with_error()
{
var bicepparamsPath = FileHelper.SaveResultFile(
TestContext,
"input.bicepparam",
"""
using './main.bicep'
param intParam = 0
""");
FileHelper.SaveResultFile(
TestContext,
"main.bicep",
"""
param intParam int
""",
Path.GetDirectoryName(bicepparamsPath));
var paramsOverrides = """
{
"intParam" : "bar"
}
""";
var settings = Settings with
{
Environment = TestEnvironment.Create(
("BICEP_PARAMETERS_OVERRIDES", paramsOverrides)
)
};
var outputFilePath = FileHelper.GetResultFilePath(TestContext, "output.json");
File.Exists(outputFilePath).Should().BeFalse();
var result = await Bicep(settings, "build-params", bicepparamsPath, "--stdout");
result.Should().Fail().And.NotHaveStdout();
result.Stderr.Should().Contain("Error BCP033: Expected a value of type \"int\" but the provided value is of type \"'bar'\".");
}
[DataTestMethod]
[BaselineData_Bicepparam.TestData(Filter = BaselineData_Bicepparam.TestDataFilterType.ValidOnly)]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_Valid_Params_File_Should_Succeed(BaselineData_Bicepparam baselineData)
{
var data = baselineData.GetData(TestContext);
var (output, error, result) = await Bicep(Settings, "build-params", data.Parameters.OutputFilePath, "--bicep-file", data.Bicep.OutputFilePath);
using (new AssertionScope())
{
result.Should().Be(0);
output.Should().BeEmpty();
AssertNoErrors(error);
}
data.Compiled!.ShouldHaveExpectedJsonValue();
}
[DataTestMethod]
[BaselineData_Bicepparam.TestData(Filter = BaselineData_Bicepparam.TestDataFilterType.ValidOnly)]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_Valid_Params_File_To_Outdir_Should_Succeed(BaselineData_Bicepparam baselineData)
{
var data = baselineData.GetData(TestContext);
var (output, error, result) = await Bicep(Settings, "build-params", data.Parameters.OutputFilePath, "--bicep-file", data.Bicep.OutputFilePath, "--outdir", Path.GetDirectoryName(data.Compiled!.OutputFilePath));
using (new AssertionScope())
{
result.Should().Be(0);
output.Should().BeEmpty();
AssertNoErrors(error);
}
data.Compiled!.ReadFromOutputFolder().Should().OnlyContainLFNewline();
data.Compiled!.ShouldHaveExpectedJsonValue();
}
[DataTestMethod]
[BaselineData_Bicepparam.TestData(Filter = BaselineData_Bicepparam.TestDataFilterType.ValidOnly)]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_Valid_Params_File_ToStdOut_Should_Succeed(BaselineData_Bicepparam baselineData)
{
var data = baselineData.GetData(TestContext);
var (output, error, result) = await Bicep(Settings, "build-params", data.Parameters.OutputFilePath, "--bicep-file", data.Bicep.OutputFilePath, "--stdout");
using (new AssertionScope())
{
result.Should().Be(0);
output.Should().NotBeEmpty();
AssertNoErrors(error);
}
var parametersStdout = output.FromJson<BuildParamsStdout>();
parametersStdout.parametersJson.Should().OnlyContainLFNewline();
data.Compiled!.WriteToOutputFolder(parametersStdout.parametersJson);
data.Compiled.ShouldHaveExpectedJsonValue();
}
[DataTestMethod]
[BaselineData_Bicepparam.TestData(Filter = BaselineData_Bicepparam.TestDataFilterType.InvalidOnly)]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_Invalid_Single_Params_File_ShouldFail_WithExpectedErrorMessage(BaselineData_Bicepparam baselineData)
{
var data = baselineData.GetData(TestContext);
var diagnostics = await GetAllParamDiagnostics(data.Parameters.OutputFilePath);
var (output, error, result) = await Bicep(Settings, "build-params", data.Parameters.OutputFilePath, "--bicep-file", data.Bicep.OutputFilePath);
using (new AssertionScope())
{
result.Should().Be(1);
output.Should().BeEmpty();
error.Should().ContainAll(diagnostics);
}
}
[TestMethod]
[EmbeddedFilesTestData(@"Files/BuildParamsCommandTests/.*/main\.bicepparam")]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_params_to_stdout_with_non_bicep_references_should_succeed(EmbeddedFile paramFile)
{
var baselineFolder = BaselineFolder.BuildOutputFolder(TestContext, paramFile);
var outputFile = baselineFolder.GetFileOrEnsureCheckedIn("output.json");
var clients = await MockRegistry.Build();
var settings = new InvocationSettings(new(TestContext, RegistryEnabled: true), clients.ContainerRegistry, clients.TemplateSpec);
var result = await Bicep(settings, "build-params", baselineFolder.EntryFile.OutputFilePath, "--stdout");
result.Should().Succeed();
var parametersStdout = result.Stdout.FromJson<BuildParamsStdout>();
// Force consistency for escaped newlines.
parametersStdout = parametersStdout with { templateJson = parametersStdout?.templateJson?.ReplaceLineEndings("\n") };
outputFile.WriteJsonToOutputFolder(parametersStdout);
outputFile.ShouldHaveExpectedJsonValue();
}
[TestMethod]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_params_to_stdout_with_experimentalfeaturenotenabled_should_fail()
{
var clients = await MockRegistry.Build();
var settings = new InvocationSettings(new(TestContext, RegistryEnabled: true), clients.ContainerRegistry, clients.TemplateSpec);
var mainBicepParamPath = FileHelper.SaveResultFile(
TestContext,
"main.bicepparam",
"""
using 'br:mockregistry.io/parameters/basic:v1'
extends 'shared.bicepparam'
param intParam = 123
param boolParam = false
param arrayParam = []
param objectParam = {}
""");
var sharedBicepParamPath = FileHelper.SaveResultFile(
TestContext,
"shared.bicepparam", """
using none
param stringParam = 'foo'
""",
Path.GetDirectoryName(mainBicepParamPath));
var bicepConfigPath = FileHelper.SaveResultFile(
TestContext,
"bicepconfig.json", "{}",
Path.GetDirectoryName(mainBicepParamPath));
var result = await Bicep(settings, "build-params", mainBicepParamPath, "--stdout");
result.Should().Fail().And.HaveStderrMatch($"*Error BCP406: The \"extends\" keyword is not supported*");
}
[TestMethod]
[EmbeddedFilesTestData(@"Files/BuildParamsCommandTests/.*/main\.bicepparam")]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_params_returns_intuitive_error_if_invoked_with_bicep_file_param(EmbeddedFile paramFile)
{
var baselineFolder = BaselineFolder.BuildOutputFolder(TestContext, paramFile);
var bicepFile = Path.Combine(baselineFolder.OutputFolderPath, "main.bicep");
File.WriteAllText(bicepFile, "");
var clients = await MockRegistry.Build();
var settings = new InvocationSettings(new(TestContext, RegistryEnabled: true), clients.ContainerRegistry, clients.TemplateSpec);
var result = await Bicep(settings, "build-params", baselineFolder.EntryFile.OutputFilePath, "--bicep-file", bicepFile, "--stdout");
result.Should().Fail().And.HaveStderrMatch($"Bicep file * provided with --bicep-file can only be used if the Bicep parameters \"using\" declaration refers to a Bicep file on disk.*");
}
[TestMethod]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_params_works_with_using_none()
{
var outputPath = FileHelper.GetUniqueTestOutputPath(TestContext);
var bicepFile = FileHelper.SaveResultFile(TestContext, "main.bicep", @"
param unusedParam int
", outputPath);
var inputFile = FileHelper.SaveResultFile(TestContext, "main.bicepparam", @"
using none
param unusedParam = 3
", outputPath);
var (output, error, result) = await Bicep(["build-params", inputFile, "--bicep-file", bicepFile]);
var expectedOutputFile = FileHelper.GetResultFilePath(TestContext, "main.json", outputPath);
File.Exists(expectedOutputFile).Should().BeTrue();
output.Should().BeEmpty();
error.Should().BeEmpty();
result.Should().Be(0);
}
[TestMethod]
[EmbeddedFilesTestData(@"Files/BuildParamsCommandTests/Registry/main\.bicepparam")]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_params_to_stdout_with_registry_should_succeed_after_restore(EmbeddedFile paramFile)
{
var baselineFolder = BaselineFolder.BuildOutputFolder(TestContext, paramFile);
var outputFile = baselineFolder.GetFileOrEnsureCheckedIn("output.json");
var clients = await MockRegistry.Build();
var settings = new InvocationSettings(new(TestContext, RegistryEnabled: true), clients.ContainerRegistry, clients.TemplateSpec);
var result = await Bicep(settings, "restore", baselineFolder.EntryFile.OutputFilePath);
result.Should().Succeed().And.NotHaveStdout().And.NotHaveStderr();
result = await Bicep(settings, "build-params", baselineFolder.EntryFile.OutputFilePath, "--no-restore", "--stdout");
result.Should().Succeed().And.NotHaveStderr();
var parametersStdout = result.Stdout.FromJson<BuildParamsStdout>();
// Force consistency for escaped newlines.
parametersStdout = parametersStdout with { templateJson = parametersStdout?.templateJson?.ReplaceLineEndings("\n") };
outputFile.WriteJsonToOutputFolder(parametersStdout);
outputFile.ShouldHaveExpectedJsonValue();
}
[TestMethod]
[EmbeddedFilesTestData(@"Files/BuildParamsCommandTests/Registry/main\.bicepparam")]
[TestCategory(BaselineHelper.BaselineTestCategory)]
public async Task Build_bicepparam_should_fail_with_error_diagnostics_for_registry_failure(EmbeddedFile paramFile)
{
var baselineFolder = BaselineFolder.BuildOutputFolder(TestContext, paramFile);
var client = StrictMock.Of<ContainerRegistryContentClient>();
client
.Setup(m => m.GetManifestAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new RequestFailedException("Mock registry request failure."));
var clientFactory = StrictMock.Of<IContainerRegistryClientFactory>();
clientFactory
.Setup(m => m.CreateAuthenticatedBlobClient(It.IsAny<CloudConfiguration>(), new Uri("https://mockregistry.io"), "parameters/basic"))
.Returns(client.Object);
var templateSpecRepositoryFactory = StrictMock.Of<ITemplateSpecRepositoryFactory>();
var settings = new InvocationSettings(new(TestContext, RegistryEnabled: true), clientFactory.Object, templateSpecRepositoryFactory.Object);
var result = await Bicep(settings, "build-params", baselineFolder.EntryFile.OutputFilePath, "--stdout");
result.Should().Fail().And.NotHaveStdout();
result.Stderr.Should().Contain("main.bicepparam(1,7) : Error BCP192: Unable to restore the artifact with reference \"br:mockregistry.io/parameters/basic:v1\": Mock registry request failure.");
}
[DataRow([])]
[DataRow(["--diagnostics-format", "defAULt"])]
[DataRow(["--diagnostics-format", "sArif"])]
[TestMethod]
public async Task BuildParams_supports_sarif_diagnostics_format(string[] args)
{
var outputPath = FileHelper.GetUniqueTestOutputPath(TestContext);
var bicepFile = FileHelper.SaveResultFile(TestContext, "main.bicep", @"
@minValue(1)
@maxValue(50)
param unusedParam int
", outputPath);
var inputFile = FileHelper.SaveResultFile(TestContext, "main.bicepparam", @"
using 'main.bicep'
param unusedParam = 3
", outputPath);
var expectedOutputFile = FileHelper.GetResultFilePath(TestContext, "main.json", outputPath);
File.Exists(expectedOutputFile).Should().BeFalse();
var (output, error, result) = await Bicep(["build-params", inputFile, .. args]);
File.Exists(expectedOutputFile).Should().BeTrue();
output.Should().BeEmpty();
if (Array.Exists(args, x => x.Equals("sarif", StringComparison.OrdinalIgnoreCase)))
{
var sarifLog = JsonConvert.DeserializeObject<SarifLog>(error)!;
sarifLog.Runs[0].Results[0].RuleId.Should().Be("no-unused-params");
sarifLog.Runs[0].Results[0].Message.Text.Should().Be("Parameter \"unusedParam\" is declared but never used. [https://aka.ms/bicep/linter/no-unused-params]");
}
else
{
error.Should().Contain($"{bicepFile}(4,11) : Warning no-unused-params: Parameter \"unusedParam\" is declared but never used. [https://aka.ms/bicep/linter/no-unused-params]");
}
result.Should().Be(0);
}
}
}