Skip to content

Commit 1e4a508

Browse files
authored
DynamicData: Allow arrays of objects where elements are allowed types (Azure#38458)
* Allow arrays of objects that are allowed types * cast to string array instead
1 parent a49ab6a commit 1e4a508

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

sdk/core/Azure.Core/src/DynamicData/DynamicData.AllowList.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,9 @@ private static bool IsAllowedEnumerableValue(Type elementType, IEnumerable enume
158158
continue;
159159
}
160160

161-
// Don't allow heterogenous collections
162-
if (item.GetType() != elementType)
161+
// Don't allow heterogenous collections,
162+
// unless the types it's holding are allowed types.
163+
if (item.GetType() != elementType && !IsAllowedType(item.GetType()))
163164
{
164165
return false;
165166
}

sdk/core/Azure.Core/tests/DynamicData/DynamicJsonAllowListTests.cs

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
using System.IO;
77
using System.Net.Http;
88
using System.Runtime.Serialization;
9-
using System.Text.Json;
109
using Azure.Core.Serialization;
1110
using NUnit.Framework;
1211

@@ -66,6 +65,46 @@ public void CanAssignObjectArray()
6665
Assert.DoesNotThrow(() => json.Bar = new object[] { 2, false, "b" });
6766
}
6867

68+
[Test]
69+
public void CanAssignObjectArrayOfAllowedTypes()
70+
{
71+
dynamic json = BinaryData.FromString("""{"foo":1}""").ToDynamicFromJson(JsonPropertyNames.CamelCase);
72+
73+
// Existing property
74+
Assert.DoesNotThrow(() => json.Foo = new object[] { 1, null, "a" });
75+
76+
// New property
77+
Assert.DoesNotThrow(() => json.Bar = new object[] { 2, false, "b" });
78+
}
79+
80+
[Test]
81+
public void CanAssignArrayOfDynamic()
82+
{
83+
dynamic jsonWithArray = BinaryData.FromString("""
84+
{
85+
"MyArray": ["a", "b", "c"]
86+
}
87+
""").ToDynamicFromJson(JsonPropertyNames.CamelCase);
88+
89+
dynamic json = BinaryData.FromString("""{"foo": 1}""").ToDynamicFromJson(JsonPropertyNames.CamelCase);
90+
91+
// Existing property
92+
Assert.DoesNotThrow(() => json.Foo = jsonWithArray.MyArray);
93+
94+
// New property
95+
Assert.DoesNotThrow(() => json.Bar = jsonWithArray.MyArray);
96+
97+
// Create list to add an item to
98+
List<string> list = new((string[])json.Foo);
99+
list.Add("d");
100+
101+
json.Foo = list;
102+
Assert.IsTrue("a" == json.Foo[0]);
103+
Assert.IsTrue("b" == json.Foo[1]);
104+
Assert.IsTrue("c" == json.Foo[2]);
105+
Assert.IsTrue("d" == json.Foo[3]);
106+
}
107+
69108
[Test]
70109
public void CannotAssignObjectArrayContainingUnallowedTypes()
71110
{

0 commit comments

Comments
 (0)