-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskTestBase.cs
More file actions
722 lines (636 loc) · 30.6 KB
/
TaskTestBase.cs
File metadata and controls
722 lines (636 loc) · 30.6 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AggregateConfigBuildTask.Tests.Unit
{
public abstract class TaskTestBase
{
private string testPath;
private readonly StringComparison comparison = StringComparison.OrdinalIgnoreCase;
private Mock<ITaskLogger> mockLogger;
internal IFileSystem virtualFileSystem;
public TestContext TestContext { get; set; }
public void TestInitialize(bool isWindowsMode, string testPath)
{
this.testPath = testPath;
this.mockLogger = new Mock<ITaskLogger> { DefaultValue = DefaultValue.Mock };
this.virtualFileSystem = new VirtualFileSystem(isWindowsMode);
this.virtualFileSystem.CreateDirectory(testPath);
}
[TestCleanup]
public void Cleanup()
{
foreach (var invocation in mockLogger.Invocations)
{
var methodName = invocation.Method.Name;
var arguments = string.Join(", ", invocation.Arguments);
TestContext.WriteLine($"Logger call: {methodName}({arguments})");
}
}
[TestMethod]
[Description("Test that YAML files are merged into correct JSON output.")]
public void ShouldGenerateJsonOutput()
{
// Arrange: Prepare sample YAML data in the mock file system.
virtualFileSystem.WriteAllText($"{testPath}\\file1.yml", @"
options:
- name: 'Option 1'
description: 'First option'");
virtualFileSystem.WriteAllText($"{testPath}\\file2.yml", @"
options:
- name: 'Option 2'
description: 'Second option'");
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Json),
AddSourceProperty = true,
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Check that output was generated correctly.
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.json");
var json = JsonConvert.DeserializeObject<Dictionary<string, object>>(output);
Assert.IsTrue(json.ContainsKey("options"));
Assert.AreEqual(2, ((IEnumerable<object>)json.GetValueOrDefault("options")).Count());
}
[TestMethod]
[Description("Test that YAML files are merged into correct ARM parameter output.")]
public void ShouldGenerateArmParameterOutput()
{
// Arrange: Prepare sample YAML data in the mock file system.
virtualFileSystem.WriteAllText($"{testPath}\\file1.yml", @"
options:
- name: 'Option 1'
description: 'First option'");
virtualFileSystem.WriteAllText($"{testPath}\\file2.yml", @"
options:
- name: 'Option 2'
description: 'Second option'");
// Create the task instance with the mock file system
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.parameters.json",
OutputType = nameof(FileType.Arm),
AddSourceProperty = true,
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Check the ARM output structure
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.parameters.json");
var armTemplate = JsonConvert.DeserializeObject<Dictionary<string, object>>(output);
Assert.IsTrue(armTemplate.ContainsKey("parameters"));
JObject parameters = (JObject)armTemplate["parameters"];
Assert.IsNotNull(parameters.GetValue("options", comparison));
Assert.AreEqual("array", parameters.GetValue("options", comparison)["type"].ToString());
}
[TestMethod]
[Description("Test that the source property is correctly added when AddSourceProperty is true.")]
public void ShouldAddSourceProperty()
{
// Arrange: Prepare sample YAML data with source property enabled.
virtualFileSystem.WriteAllText($"{testPath}\\file1.yml", @"
options:
- name: 'Option 1'
description: 'First option'");
// Create the task instance with the mock file system
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Json),
AddSourceProperty = true,
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Verify that the source property was added
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.json");
var json = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, string>>>>(output);
Assert.IsTrue(json["options"][0].ContainsKey("source"));
Assert.AreEqual("file1", json["options"][0]["source"]);
}
[TestMethod]
[Description("Test that the source property is correctly added for multiple files when AddSourceProperty is true.")]
public void ShouldAddSourcePropertyMultipleFiles()
{
// Arrange: Prepare sample YAML data with source property enabled.
virtualFileSystem.WriteAllText($"{testPath}\\file1.yml", @"
options:
- name: 'Option 1'
description: 'First option'
additionalOptions:
value: 'Good day'");
virtualFileSystem.WriteAllText($"{testPath}\\file2.yml", @"
options:
- name: 'Option 2'
description: 'Second option'
- name: '''Option 3'''
description: 'Third option'
additionalOptions:
value: 'Good night'
text:
- name: 'Text 1'
description: 'Text'");
// Create the task instance with the mock file system
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Json),
AddSourceProperty = true,
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Verify that the source property was added
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.json");
var json = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, object>>>>(output);
Assert.IsTrue(OptionExistsWithSource(json["options"], "Option 1", "file1"));
Assert.IsTrue(OptionExistsWithSource(json["options"], "Option 2", "file2"));
Assert.IsTrue(OptionExistsWithSource(json["options"], "'Option 3'", "file2"));
Assert.IsTrue(OptionExistsWithSource(json["text"], "Text 1", "file2"));
}
[TestMethod]
[Description("Test that additional properties are correctly added to the top level in JSON output.")]
[DataRow(true, DisplayName = "Legacy properties")]
[DataRow(false, DisplayName = "Modern properties")]
public void ShouldIncludeAdditionalPropertiesInJson(bool useLegacyAdditionalProperties)
{
// Arrange: Prepare sample YAML data.
virtualFileSystem.WriteAllText($"{testPath}\\file1.yml", @"
options:
- name: 'Option 1'
description: 'First option'");
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Json),
AddSourceProperty = true,
AdditionalProperties = new Dictionary<string, string>(StringComparer.Ordinal)
{
{ "Group", "TestRG" },
{ "Environment\\=Key", "Prod\\=West" }
}.CreateTaskItems(useLegacyAdditionalProperties),
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Verify additional properties are included
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.json");
var json = JsonConvert.DeserializeObject<Dictionary<string, object>>(output);
Assert.AreEqual("TestRG", json["Group"]);
if (useLegacyAdditionalProperties)
{
Assert.AreEqual("Prod=West", json["Environment=Key"]);
}
else
{
Assert.AreEqual("Prod\\=West", json["Environment\\=Key"]);
}
}
[TestMethod]
[Description("Test that additional properties are correctly added to the ARM parameters output.")]
[DataRow(true, DisplayName = "Legacy properties")]
[DataRow(false, DisplayName = "Modern properties")]
public void ShouldIncludeAdditionalPropertiesInArmParameters(bool useLegacyAdditionalProperties)
{
// Arrange: Prepare sample YAML data.
virtualFileSystem.WriteAllText($"{testPath}\\file1.yml", @"
options:
- name: 'Option 1'
description: 'First option'");
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Arm),
AddSourceProperty = true,
AdditionalProperties = new Dictionary<string, string>(StringComparer.Ordinal)
{
{ "Group", "TestRG" },
{ "Environment", "Prod" }
}.CreateTaskItems(useLegacyAdditionalProperties),
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Verify additional properties are included in ARM output
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.json");
var armTemplate = JsonConvert.DeserializeObject<Dictionary<string, object>>(output);
JObject parameters = (JObject)armTemplate["parameters"];
Assert.AreEqual("array", parameters.GetValue("options", comparison)["type"].ToString());
Assert.AreEqual("TestRG", parameters.GetValue("Group", comparison)["value"].Value<string>());
Assert.AreEqual("Prod", parameters.GetValue("Environment", comparison)["value"].Value<string>());
}
[TestMethod]
[Description("Test that the task handles an empty input directory gracefully.")]
public void ShouldHandleEmptyDirectory()
{
// Arrange: No files added to the mock file system (empty directory).
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Json),
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Ensure the task fails and output is empty
Assert.IsFalse(result);
bool outputExists = virtualFileSystem.FileExists($"{testPath}\\output.json");
Assert.IsFalse(outputExists, "No file should have been created!");
}
[TestMethod]
[Description("Test that the task throws an error when it encounters invalid YAML format.")]
public void ShouldHandleInvalidYamlFormat()
{
// Arrange: Add invalid YAML file to the mock file system.
virtualFileSystem.WriteAllText($"{testPath}\\invalid.yml", @"
options:
- name: 'Option 1'
description: 'Unclosed value");
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Json),
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Expect the task to fail
bool result = task.Execute();
// Assert: Verify the task fails due to invalid YAML
Assert.IsFalse(result);
}
[TestMethod]
[Description("Test that boolean input values are correctly treated as booleans in the output.")]
public void ShouldCorrectlyParseBooleanValues()
{
// Arrange: Prepare sample YAML data.
virtualFileSystem.WriteAllText($"{testPath}\\file1.yml", @"
options:
- name: 'Option 1'
description: 'First option'
isEnabled: true");
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Arm),
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Verify additional properties are included in ARM output
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.json");
var armTemplate = JsonConvert.DeserializeObject<Dictionary<string, object>>(output);
JObject parameters = (JObject)armTemplate["parameters"];
Assert.AreEqual("array", parameters.GetValue("options", comparison)["type"].ToString());
Assert.AreEqual("Boolean", parameters.GetValue("options", comparison)["value"].First()["isEnabled"].Type.ToString());
Assert.IsTrue(parameters.GetValue("options", comparison)["value"].First()["isEnabled"].Value<bool>());
}
[TestMethod]
[Description("Test that additional properties are correctly added to the ARM parameters output from JSON input.")]
[DataRow(true, DisplayName = "Legacy properties")]
[DataRow(false, DisplayName = "Modern properties")]
public void ShouldIncludeAdditionalPropertiesInJsonInput(bool useLegacyAdditionalProperties)
{
// Arrange: Prepare sample JSON data.
virtualFileSystem.WriteAllText($"{testPath}\\file1.json", """
{
"options": [
{
"name": "Option 1",
"description": "First option",
"isEnabled": true
}
]
}
""");
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputType = nameof(FileType.Json),
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Arm),
AddSourceProperty = true,
AdditionalProperties = new Dictionary<string, string>(StringComparer.Ordinal)
{
{ "Group", "TestRG" },
{ "Environment", "Prod" }
}.CreateTaskItems(useLegacyAdditionalProperties),
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Verify additional properties are included in ARM output
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.json");
var armTemplate = JsonConvert.DeserializeObject<Dictionary<string, object>>(output);
JObject parameters = (JObject)armTemplate["parameters"];
Assert.AreEqual("TestRG", parameters.GetValue("Group", comparison)["value"].Value<string>());
Assert.AreEqual("Prod", parameters.GetValue("Environment", comparison)["value"].Value<string>());
Assert.AreEqual("String", parameters.GetValue("options", comparison)["value"].First()["source"].Type.ToString());
Assert.AreEqual("file1", parameters.GetValue("options", comparison)["value"].First()["source"].Value<string>());
Assert.AreEqual("Boolean", parameters.GetValue("options", comparison)["value"].First()["isEnabled"].Type.ToString());
Assert.IsTrue(parameters.GetValue("options", comparison)["value"].First()["isEnabled"].Value<bool>());
}
[TestMethod]
[Description("Test that ARM parameters are correctly processed and additional properties are included in the output.")]
[DataRow(true, DisplayName = "Legacy properties")]
[DataRow(false, DisplayName = "Modern properties")]
public void ShouldIncludeAdditionalPropertiesInArmParameterFile(bool useLegacyAdditionalProperties)
{
// Arrange: Prepare ARM template parameter file data in 'file1.parameters.json'.
virtualFileSystem.WriteAllText($"{testPath}\\file1.parameters.json", """
{
"parameters": {
"options": {
"type": "array",
"value": [
{
"name": "Option 1",
"description": "First option",
"isEnabled": true
}
]
}
}
}
""");
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputType = nameof(FileType.Arm),
InputDirectory = testPath,
OutputFile = testPath + @"\output.parameters.json",
OutputType = nameof(FileType.Arm),
AddSourceProperty = true,
AdditionalProperties = new Dictionary<string, string>(StringComparer.Ordinal)
{
{ "Group", "TestRG" },
{ "Environment", "'Prod'" }
}.CreateTaskItems(useLegacyAdditionalProperties),
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Verify additional properties are included in ARM output
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.parameters.json");
var armTemplate = JsonConvert.DeserializeObject<Dictionary<string, object>>(output);
JObject parameters = (JObject)armTemplate["parameters"];
Assert.AreEqual("TestRG", parameters.GetValue("Group", comparison)["value"].Value<string>());
Assert.AreEqual("'Prod'", parameters.GetValue("Environment", comparison)["value"].Value<string>());
Assert.AreEqual("String", parameters.GetValue("options", comparison)["value"].First()["source"].Type.ToString());
Assert.AreEqual("file1.parameters", parameters.GetValue("options", comparison)["value"].First()["source"].Value<string>());
Assert.AreEqual("Boolean", parameters.GetValue("options", comparison)["value"].First()["isEnabled"].Type.ToString());
Assert.IsTrue(parameters.GetValue("options", comparison)["value"].First()["isEnabled"].Value<bool>());
}
[TestMethod]
[Description("Stress test to verify the source property is correctly added for 1,000 files with 10 options each.")]
[Timeout(60000)]
public void StressTest_ShouldAddSourcePropertyManyFiles()
{
// Arrange: Prepare sample YAML data.
const int totalFiles = 1_000;
const int totalOptionsPerFile = 10;
for (int fileIndex = 1; fileIndex <= totalFiles; fileIndex++)
{
var sb = new StringBuilder();
sb.AppendLine("options:");
for (int optionIndex = 1; optionIndex <= totalOptionsPerFile; optionIndex++)
{
sb.AppendLine(CultureInfo.InvariantCulture, $" - name: 'Option {optionIndex}'")
.AppendLine(CultureInfo.InvariantCulture, $" description: 'Description for Option {optionIndex}'");
}
// Write each YAML file to the mock file system
virtualFileSystem.WriteAllText($"{testPath}\\file{fileIndex}.yml", sb.ToString());
}
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = testPath,
OutputFile = testPath + @"\output.json",
OutputType = nameof(FileType.Json),
AddSourceProperty = true,
BuildEngine = Mock.Of<IBuildEngine>()
};
// Act: Execute the task
bool result = task.Execute();
// Assert: Verify that the source property was added correctly for all files and options
Assert.IsTrue(result);
string output = virtualFileSystem.ReadAllText($"{testPath}\\output.json");
var json = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, object>>>>(output);
int optionIndexInTotal = 0;
for (int fileIndex = 1; fileIndex <= totalFiles; fileIndex++)
{
for (int optionIndex = 1; optionIndex <= totalOptionsPerFile; optionIndex++, optionIndexInTotal++)
{
Assert.IsTrue(OptionExistsWithSource(json["options"], $"Option {optionIndex}", $"file{fileIndex}"));
}
}
}
[TestMethod]
[DataRow("arm", new[] { "json", "yml", "arm" }, DisplayName = "ARM -> JSON -> YAML -> ARM")]
[DataRow("arm", new[] { "yml", "json", "arm" }, DisplayName = "ARM -> YAML -> JSON -> ARM")]
[DataRow("json", new[] { "arm", "yml", "json" }, DisplayName = "JSON -> ARM -> YAML -> JSON")]
[DataRow("json", new[] { "yml", "arm", "json" }, DisplayName = "JSON -> YAML -> ARM -> JSON")]
[DataRow("yml", new[] { "arm", "json", "yml" }, DisplayName = "YAML -> ARM -> JSON -> YAML")]
[DataRow("yml", new[] { "json", "arm", "yml" }, DisplayName = "YAML -> JSON -> ARM -> YAML")]
[Description("Test that files are correctly translated between ARM, JSON, and YAML.")]
public void ShouldTranslateBetweenFormatsAndValidateNoDataLoss(string inputType, string[] steps)
{
Assert.IsNotNull(steps);
Assert.IsGreaterThan(steps.Length, 0);
// Setup input file
string inputFilePath = SetupInputFile(inputType);
// Execute translation chain
var (finalInputPath, finalOutputType) = ExecuteTranslationChain(inputType, steps, inputFilePath);
// Execute final conversion back to original format
string finalOutputPath = ExecuteFinalConversion(inputType, finalInputPath, finalOutputType);
// Validate no data loss
AssertNoDataLoss(inputFilePath, finalOutputPath, inputType);
}
private string SetupInputFile(string inputType)
{
var inputDir = $"{testPath}\\input";
virtualFileSystem.CreateDirectory(inputDir);
var inputFilePath = $"{inputDir}\\input.{(string.Equals(inputType, "arm", StringComparison.Ordinal) ? "json" : inputType)}";
virtualFileSystem.WriteAllText(inputFilePath, GetSampleDataForType(inputType));
return inputFilePath;
}
private (string path, string outputType) ExecuteTranslationChain(string inputType, string[] steps, string inputFilePath)
{
string previousInputPath = inputFilePath;
string previousOutputType = inputType;
// Execute the translation steps dynamically
for (int i = 0; i < steps.Length; i++)
{
var outputType = steps[i];
var stepDir = $"{testPath}\\step{i + 1}";
var stepOutputPath = $"{stepDir}\\output.{(string.Equals(outputType, "arm", StringComparison.Ordinal) ? "json" : outputType)}";
virtualFileSystem.CreateDirectory(stepDir);
// Execute translation for this step
ExecuteTranslationTask(previousOutputType, outputType, previousInputPath, stepOutputPath);
// Update paths for the next iteration
previousInputPath = stepOutputPath;
previousOutputType = outputType;
}
return (previousInputPath, previousOutputType);
}
private string ExecuteFinalConversion(string inputType, string previousInputPath, string previousOutputType)
{
// Final step: Convert the final output back to the original input type
var finalDir = $"{testPath}\\final";
var finalOutputPath = $"{finalDir}\\final_output.{(string.Equals(inputType, "arm", StringComparison.Ordinal) ? "json" : inputType)}";
virtualFileSystem.CreateDirectory(finalDir);
ExecuteTranslationTask(previousOutputType, inputType, previousInputPath, finalOutputPath);
return finalOutputPath;
}
private void ExecuteTranslationTask(string inputType, string outputType, string inputFilePath, string outputFilePath)
{
var task = new AggregateConfig(virtualFileSystem, mockLogger.Object)
{
InputDirectory = inputFilePath,
InputType = inputType,
OutputFile = outputFilePath,
OutputType = outputType,
BuildEngine = Mock.Of<IBuildEngine>()
};
bool result = task.Execute();
Assert.IsTrue(result, $"Failed translation: {inputType} -> {outputType}");
}
private void AssertNoDataLoss(string originalFilePath, string finalFilePath, string inputType)
{
string originalInput = virtualFileSystem.ReadAllText(originalFilePath);
string finalOutput = virtualFileSystem.ReadAllText(finalFilePath);
Assert.IsTrue(string.Equals(originalInput, finalOutput, StringComparison.Ordinal), $"Data mismatch after full conversion cycle for {inputType}");
}
private static string GetSampleDataForType(string type)
{
if (string.Equals(type, "json", StringComparison.Ordinal))
{
return GetJsonSampleData();
}
else if (string.Equals(type, "arm", StringComparison.Ordinal))
{
return GetArmSampleData();
}
else if (string.Equals(type, "yml", StringComparison.Ordinal))
{
return GetYmlSampleData();
}
else
{
throw new InvalidOperationException("Unknown type");
}
}
private static string GetJsonSampleData()
{
return """
{
"options": [
{
"name": "Option 1",
"description": "First option",
"isTrue": true,
"number": 100,
"nested": [
{
"name": "Nested option 1",
"description": "Nested first option",
"isTrue": true,
"number": 1001
},
{
"name": "Nested option 2",
"description": "Nested second option"
}
]
}
]
}
""";
}
private static string GetArmSampleData()
{
return """
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"options": {
"type": "object",
"value": {
"name": "Option 1",
"description": "First option",
"isTrue": true,
"number": 100,
"nested": [
{
"name": "Nested option 1",
"description": "Nested first option",
"isTrue": true,
"number": 1002
},
{
"name": "Nested option 2",
"description": "Nested second option"
}
]
}
}
}
}
""";
}
private static string GetYmlSampleData()
{
return @"options:
- name: Option 1
description: First option
isTrue: true
number: 100
nested:
- name: Nested option 1
description: Nested first option
isTrue: true
number: 1003
- name: Nested option 2
description: Nested second option
";
}
/// <summary>
/// Check if an option exists with a given name and source in the top-level of the given root tree.
/// </summary>
/// <param name="options">The tree to search within.</param>
/// <param name="optionName">The option to search for.</param>
/// <param name="expectedSource">The expected source property on the option object.</param>
private static bool OptionExistsWithSource(List<Dictionary<string, object>> options, string optionName, string expectedSource)
{
return options.Any(option =>
option.ContainsKey("name") &&
string.Equals((string)option["name"], optionName, StringComparison.Ordinal) &&
option.ContainsKey("source") &&
string.Equals((string)option["source"], expectedSource, StringComparison.Ordinal));
}
}
}