Skip to content

Commit

Permalink
add a funtion to convert BinaryData to RequestContent (#39316)
Browse files Browse the repository at this point in the history
* add serialize funtion for BinaryData

* add more test

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

Co-authored-by: Christopher Scott <[email protected]>

---------

Co-authored-by: Christopher Scott <[email protected]>
  • Loading branch information
2 people authored and drielenr committed Oct 24, 2023
1 parent ad5cba3 commit f43ee97
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
10 changes: 10 additions & 0 deletions sdk/core/Azure.Core/src/Shared/RequestContentHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
21 changes: 21 additions & 0 deletions sdk/core/Azure.Core/tests/RequestContentHelperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ public static IEnumerable<TestCaseData> 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)]
Expand Down Expand Up @@ -186,5 +196,16 @@ public void TestFromObject<T>(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());
}
}
}

0 comments on commit f43ee97

Please sign in to comment.