From d50246faedb82b7f04f4f2bf343e45c24fcab590 Mon Sep 17 00:00:00 2001 From: Crystal YU Date: Thu, 19 Oct 2023 09:40:42 +0800 Subject: [PATCH] add a funtion to convert BinaryData to RequestContent (#39316) * add serialize funtion for BinaryData * add more test * Update sdk/core/Azure.Core/src/Shared/RequestContentHelper.cs Co-authored-by: Christopher Scott --------- Co-authored-by: Christopher Scott --- .../src/Shared/RequestContentHelper.cs | 10 +++++++++ .../tests/RequestContentHelperTests.cs | 21 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/sdk/core/Azure.Core/src/Shared/RequestContentHelper.cs b/sdk/core/Azure.Core/src/Shared/RequestContentHelper.cs index 2e02e72699907..3acd8b1e674e3 100644 --- a/sdk/core/Azure.Core/src/Shared/RequestContentHelper.cs +++ b/sdk/core/Azure.Core/src/Shared/RequestContentHelper.cs @@ -94,5 +94,15 @@ public static RequestContent FromObject(object value) content.JsonWriter.WriteObjectValue(value); return content; } + public static RequestContent FromObject(BinaryData value) + { + var content = new Utf8JsonRequestContent(); +#if NET6_0_OR_GREATER + content.JsonWriter.WriteRawValue(value); +#else + JsonSerializer.Serialize(content.JsonWriter, JsonDocument.Parse(value).RootElement); +#endif + return content; + } } } diff --git a/sdk/core/Azure.Core/tests/RequestContentHelperTests.cs b/sdk/core/Azure.Core/tests/RequestContentHelperTests.cs index 4212bab2af7b1..4fe4ec18636fc 100644 --- a/sdk/core/Azure.Core/tests/RequestContentHelperTests.cs +++ b/sdk/core/Azure.Core/tests/RequestContentHelperTests.cs @@ -27,6 +27,16 @@ public static IEnumerable GetOneDateTimeData() yield return new TestCaseData(DateTimeOffset.Parse("2022-08-26T18:38:00Z")); } + public static object[] BinaryDataCases = + { + new object[] { BinaryData.FromString("\"test\"") }, + new object[] { new BinaryData(1)}, + new object[] { new BinaryData(1.1)}, + new object[] { new BinaryData(true)}, + new object[] { BinaryData.FromObjectAsJson(new {name="a", age=1})}, + new object[] { new BinaryData(DateTimeOffset.Parse("2022-08-26T18:38:00Z"))} + }; + [TestCase(1, 2)] [TestCase("a", "b")] [TestCase(true, false)] @@ -186,5 +196,16 @@ public void TestFromObject(T value) break; } } + + [TestCaseSource(nameof(BinaryDataCases))] + public void TestFromObjectForBinaryData(BinaryData value) + { + var content = RequestContentHelper.FromObject(value); + var stream = new MemoryStream(); + content.WriteTo(stream, default); + stream.Position = 0; + var document = JsonDocument.Parse(stream); + Assert.AreEqual(value.ToObjectFromJson(), BinaryData.FromString(document.RootElement.GetRawText()).ToObjectFromJson()); + } } }