using System.Collections; using System.Text.Json; using Agent.PowerShell; using Shared.Contracts.Models; using Xunit; namespace Agent.Tests; public class ScriptArgumentBinderTests { private static Dictionary Args(string json) => JsonSerializer.Deserialize>(json)!; [Fact] public void HashtableEntriesKeepTheirPerEntryPrimitiveTypes() { var parameters = new List { new("Map", ScriptParameterType.Hashtable) }; var arguments = Args(""" { "Map": [ { "key": "Name", "value": "widget" }, { "key": 42, "value": true }, { "key": "Retries", "value": 3 } ] } """); var bound = ScriptArgumentBinder.Bind(parameters, arguments); var table = Assert.IsType(bound["Map"]); // Each entry's key and value carry the JSON-native type it was sent with. Assert.Equal("widget", table["Name"]); Assert.Equal(true, table[42]); Assert.Equal(3, table["Retries"]); Assert.IsType(table.Keys.Cast().Single(k => k is int)); } [Fact] public void ObjectFormHashtablesInferValueTypesFromJson() { var parameters = new List { new("Map", ScriptParameterType.Hashtable) }; var arguments = Args("""{ "Map": { "a": 1, "b": true, "c": "text" } }"""); var table = Assert.IsType( ScriptArgumentBinder.Bind(parameters, arguments)["Map"]); Assert.Equal(1, table["a"]); Assert.Equal(true, table["b"]); Assert.Equal("text", table["c"]); } [Fact] public void AValueNotGivenTakesTheDefaultAndOtherwiseIsLeftToPowerShell() { var parameters = new List { new("Ports", ScriptParameterType.Array, ElementType: PrimitiveType.Number, DefaultValue: JsonSerializer.SerializeToElement(new[] { 80, 443 })), new("Name", ScriptParameterType.String, DefaultValue: JsonSerializer.SerializeToElement("fallback")), new("Path", ScriptParameterType.String, DefaultExpression: "$env:TEMP"), new("Force", ScriptParameterType.Boolean, DefaultValue: JsonSerializer.SerializeToElement(true)), }; // Empty is the same as absent; false is a value. var bound = ScriptArgumentBinder.Bind(parameters, Args("""{ "Ports": [], "Name": " ", "Path": null, "Force": false }""")); Assert.Equal(new object[] { 80, 443 }, Assert.IsType(bound["Ports"])); Assert.Equal("fallback", bound["Name"]); Assert.False(bound.ContainsKey("Path")); Assert.Equal(false, bound["Force"]); } [Fact] public void AGivenValueWinsOverTheDefault() { var parameters = new List { new("Count", ScriptParameterType.Number, DefaultValue: JsonSerializer.SerializeToElement(1)), }; Assert.Equal(5, ScriptArgumentBinder.Bind(parameters, Args("""{ "Count": 5 }"""))["Count"]); Assert.Equal(1, ScriptArgumentBinder.Bind(parameters, null)["Count"]); } }