From 9d6b4b7a431f77fe40c14d9196835c36d9f776ee Mon Sep 17 00:00:00 2001 From: Paulskit Date: Thu, 7 Dec 2023 14:18:20 +0200 Subject: [PATCH] fix(Deserialize): fail on enums marked with Flags (#142) Co-authored-by: Sergii Kurganskiy --- .../AvroObjectServices/Read/Resolvers/Int.cs | 3 +++ .../EnumTests.cs | 14 ++++++++++++++ tests/AvroConvertTests/TestClasses.cs | 11 +++++++++++ 3 files changed, 28 insertions(+) diff --git a/src/AvroConvert/AvroObjectServices/Read/Resolvers/Int.cs b/src/AvroConvert/AvroObjectServices/Read/Resolvers/Int.cs index 7ea1551a..0121f6da 100644 --- a/src/AvroConvert/AvroObjectServices/Read/Resolvers/Int.cs +++ b/src/AvroConvert/AvroObjectServices/Read/Resolvers/Int.cs @@ -32,6 +32,9 @@ private object ConvertValue(Type readType, object value) { switch (readType) { + case not null when readType.IsEnum: + return Enum.ToObject(readType, value); + case not null when readType == typeof(int): case not null when readType == typeof(int?): return Convert.ToInt32(value); diff --git a/tests/AvroConvertTests/FullSerializationAndDeserialization/EnumTests.cs b/tests/AvroConvertTests/FullSerializationAndDeserialization/EnumTests.cs index 2bba303c..2fc953c2 100644 --- a/tests/AvroConvertTests/FullSerializationAndDeserialization/EnumTests.cs +++ b/tests/AvroConvertTests/FullSerializationAndDeserialization/EnumTests.cs @@ -43,6 +43,20 @@ public void Enum_object(Func engine) //Assert Assert.Equal(toSerialize, deserialized); } + + [Theory] + [MemberData(nameof(TestEngine.All), MemberType = typeof(TestEngine))] + public void Enum_with_flags_object(Func engine) + { + foreach (var toSerialize in Enum.GetValues()) + { + //Act + var deserialized = engine.Invoke(toSerialize, typeof(TestEnumWithFlags)); + + //Assert + Assert.Equal(toSerialize, deserialized); + } + } [Theory] [MemberData(nameof(TestEngine.All), MemberType = typeof(TestEngine))] diff --git a/tests/AvroConvertTests/TestClasses.cs b/tests/AvroConvertTests/TestClasses.cs index 4cda5628..7bcbd54e 100644 --- a/tests/AvroConvertTests/TestClasses.cs +++ b/tests/AvroConvertTests/TestClasses.cs @@ -301,6 +301,17 @@ public enum TestEnum ca, dlo } + + [Flags] + public enum TestEnumWithFlags + { + None = 0, + Option1 = 1, + Option2 = 2, + Option3 = 4, + Option4 = 8, + CombinedOption = Option1 | Option2 + } [Equals(DoNotAddEqualityOperators = true)] public class ClassWithEnum