Skip to content

Commit 661630a

Browse files
authored
add a function to convert primitive type to RequestContent (Azure#38808)
* add a function to convert primitive type to RequestContent * add test * add more test
1 parent 02d6fa9 commit 661630a

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

sdk/core/Azure.Core/src/Shared/RequestContentHelper.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,5 +87,12 @@ public static RequestContent FromDictionary(IDictionary<string, BinaryData> dict
8787

8888
return content;
8989
}
90+
91+
public static RequestContent FromObject(object value)
92+
{
93+
var content = new Utf8JsonRequestContent();
94+
content.JsonWriter.WriteObjectValue(value);
95+
return content;
96+
}
9097
}
9198
}

sdk/core/Azure.Core/tests/RequestContentHelperTests.cs

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
using System.IO;
77
using System.Text.Json;
88
using System.Xml;
9-
using System.Xml.Linq;
109
using NUnit.Framework;
1110

1211
namespace Azure.Core.Tests
@@ -23,6 +22,11 @@ public static IEnumerable<TestCaseData> GetDateTimeData()
2322
yield return new TestCaseData(DateTimeOffset.Parse("2022-08-26T18:38:00Z"), DateTimeOffset.Parse("2022-09-26T18:38:00Z"));
2423
}
2524

25+
public static IEnumerable<TestCaseData> GetOneDateTimeData()
26+
{
27+
yield return new TestCaseData(DateTimeOffset.Parse("2022-08-26T18:38:00Z"));
28+
}
29+
2630
[TestCase(1, 2)]
2731
[TestCase("a", "b")]
2832
[TestCase(true, false)]
@@ -148,5 +152,39 @@ public void TestBinaryDataFromDictionary()
148152
}
149153
}
150154
}
155+
156+
[TestCase("a")]
157+
[TestCase(true)]
158+
[TestCase(1)]
159+
[TestCase(1.0)]
160+
[TestCaseSource("GetOneDateTimeData")]
161+
public void TestFromObject<T>(T value)
162+
{
163+
var content = RequestContentHelper.FromObject(value);
164+
var stream = new MemoryStream();
165+
content.WriteTo(stream, default);
166+
stream.Position = 0;
167+
var document = JsonDocument.Parse(stream);
168+
switch (value)
169+
{
170+
case string:
171+
Assert.AreEqual(JsonValueKind.String, document.RootElement.ValueKind);
172+
Assert.AreEqual($"\"{value}\"", document.RootElement.GetRawText());
173+
break;
174+
case bool:
175+
Assert.AreEqual(value, document.RootElement.GetBoolean());
176+
break;
177+
case int:
178+
Assert.AreEqual(value, document.RootElement.GetInt32());
179+
break;
180+
case double:
181+
Assert.AreEqual(value, document.RootElement.GetDouble());
182+
break;
183+
case DateTimeOffset:
184+
Assert.AreEqual(JsonValueKind.String, document.RootElement.ValueKind);
185+
Assert.AreEqual(value, DateTimeOffset.Parse(document.RootElement.GetString()));
186+
break;
187+
}
188+
}
151189
}
152190
}

0 commit comments

Comments
 (0)