Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample of using Specifications to test serializers
/// <summary>
/// This class scans all available specifications for messages used
/// then performs round-trip via specified serializer,
/// and then does the structural comparison of resulting values
/// </summary>
[TestFixture]
public sealed class TestMessageSerialization
{
static Group[] ListMessages()
{
return typeof(CustomerSpec)
.Assembly
.GetExportedTypes()
.Where(t => typeof(ContainsSpecifications).IsAssignableFrom(t))
.SelectMany(TypeReader.GetSpecificationsIn)
.SelectMany(GetGroups)
.GroupBy(g => g.Message.GetType())
.Select(g => new Group(g.ToArray(),g.Key))
.ToArray();
}
public sealed class Group
{
public readonly IEnumerable<Source> Messages;
public readonly Type Type ;
public Group(IEnumerable<Source> messages, Type type)
{
Messages = messages;
Type = type;
}
public override string ToString()
{
return Type.Name + " x" + Messages.Count();
}
}
public sealed class Source
{
public readonly HubDefine.IMessage Message;
public readonly string Origin;
public Source(HubDefine.IMessage message, string origin)
{
Message = message;
Origin = origin;
}
}
static IEnumerable<Source> GetGroups(SpecificationToRun run)
{
var s = run.Specification as IAggregateSpecification;
var name = run.FoundOn.DeclaringType.Name + " " + run.FoundOn.Name;
if (s == null)
{
yield break;
}
foreach (var @event in s.GetGiven())
{
yield return new Source(@event, name + " Given");
}
yield return new Source(s.GetWhen(), name + " When");
foreach (var w in s.GetExpect())
{
yield return new Source(w, name + " Expect");
}
}
[TestCaseSource( "ListMessages")]
public void Verify(Group msgs)
{
foreach (var exp in msgs.Messages)
{
var expected = exp.Message;
{
var type = expected.GetType();
var s = JsonSerializer.SerializeToString(expected, type);
var actual = JsonSerializer.DeserializeFromString(s, type);
var compare = CompareObjects.FindDifferences(expected, actual);
if (!string.IsNullOrEmpty(compare))
{
Assert.Fail("JsonSerializer" + exp.Origin + Environment.NewLine + compare);
}
}
{
var actual = Serializer.DeepClone(expected);
var compare = CompareObjects.FindDifferences(expected, actual);
if (!string.IsNullOrWhiteSpace(compare))
{
Assert.Fail("ProtoBuf" + exp.Origin + Environment.NewLine + compare);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment