Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SerializationBinder to formatter we use in tests #5075

Merged
merged 1 commit into from
Feb 19, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

using Microsoft.VisualStudio.TestTools.UnitTesting;
Expand Down Expand Up @@ -32,13 +33,30 @@ private void VerifySerialization(Action actionThatThrows)
// Ensure the thrown exception can be serialized and deserialized by binary formatter to keep compatibility with it,
// even though it is obsoleted and removed in .NET.
var mem = new MemoryStream();
new BinaryFormatter().Serialize(mem, ex);
var formatter = new BinaryFormatter
{
Binder = new FormatterBinder(),
};
formatter.Serialize(mem, ex);
mem.Position = 0;
new BinaryFormatter().Deserialize(mem);
string str = Encoding.UTF8.GetString(mem.GetBuffer(), 0, (int)mem.Length);
Assert.IsNotNull(str);
var deserializedException = (Exception)formatter.Deserialize(mem);

Assert.AreEqual(ex.Message, deserializedException.Message);

return;
}

throw new InvalidOperationException($"The provided '{nameof(actionThatThrows)}' did not throw any exception.");
}

/// <summary>
/// This is for compliance, usage of BinaryFormatter without binder is not allowed.
/// </summary>
private class FormatterBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
=> null!;
}
}