Skip to content

Commit

Permalink
Add SerializationBinder to formatter we use in tests (#5075)
Browse files Browse the repository at this point in the history
  • Loading branch information
nohwnd authored Feb 19, 2025
1 parent 661e266 commit 371d3c7
Showing 1 changed file with 20 additions and 2 deletions.
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!;
}
}

0 comments on commit 371d3c7

Please sign in to comment.