private void AssertWrittenJson <TValue>(TValue value, GrpcJsonSettings?settings = null, bool?compareRawStrings = null) where TValue : IMessage { var typeRegistery = TypeRegistry.FromFiles( HelloRequest.Descriptor.File, Timestamp.Descriptor.File); settings ??= new GrpcJsonSettings { WriteInt64sAsStrings = true }; var formatterSettings = new JsonFormatter.Settings( formatDefaultValues: !settings.IgnoreDefaultValues, typeRegistery); formatterSettings = formatterSettings.WithFormatEnumsAsIntegers(settings.WriteEnumsAsIntegers); var formatter = new JsonFormatter(formatterSettings); var jsonOld = formatter.Format(value); _output.WriteLine("Old:"); _output.WriteLine(jsonOld); var jsonSerializerOptions = CreateSerializerOptions(settings, typeRegistery); var jsonNew = JsonSerializer.Serialize(value, jsonSerializerOptions); _output.WriteLine("New:"); _output.WriteLine(jsonNew); using var doc1 = JsonDocument.Parse(jsonNew); using var doc2 = JsonDocument.Parse(jsonOld); var comparer = new JsonElementComparer(maxHashDepth: -1, compareRawStrings: compareRawStrings ?? false); Assert.True(comparer.Equals(doc1.RootElement, doc2.RootElement)); }
public async Task CompareUnforgedFromFile() { var forge = new LocalForge(); var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, MaxDepth = 100_000, }; options.Converters.Add(new DateTimUtcTimezoneAppender()); var jsonComparer = new JsonElementComparer(true, true); var directories = Directory.GetDirectories("../../../Forging/operations"); JsonElement toJsonElement(object o) { // JSON serialize the unforged manager operation for the purpose of deserializing as JsonElement for comparison var serMop = JsonSerializer.Serialize(o, o.GetType(), options); // Deserialize the unforged manager operation to JsonElement for comparison return((JsonElement)DJson.Parse(serMop)); } foreach (var directory in directories) { var json = DJson.Read($"{directory}/unsigned.json", options); // Parse the op bytes var opBytes = Hex.Parse(File.ReadAllText($"{directory}/forged.hex")); // Unforge the op bytes var op = await forge.UnforgeOperationAsync(opBytes); // Serialize/deserialize each operation for the purpose of conversion to JsonElement for comparison var deserOps = op.Item2.Select(toJsonElement); // Assert branch Assert.Equal(json.branch, op.Item1); // Assert equivalent JSON operations Assert.Equal(json.contents.count, op.Item2.Count()); Assert.True(((JsonElement)json.contents).EnumerateArray().SequenceEqual(deserOps, jsonComparer)); } }