Skip to content

Commit

Permalink
Fix enum parsing
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Farr <tsfarr@amazon.com>
  • Loading branch information
Xtansia committed Sep 20, 2024
1 parent 04c7c83 commit d8829c8
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/OpenSearch.Net/Api/Enums.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private static Func<string, Enum> GetEnumStringParser(Type type)
var isFlag = type.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0;

return isFlag
? s => (Enum) Convert.ChangeType(s.ToLowerInvariant().Split(',').Aggregate(0ul, (acc, value) => acc | Convert.ToUInt64(dictionary[value])), type)
? s => (Enum)Enum.ToObject(type, s.ToLowerInvariant().Split(',').Aggregate(0, (acc, value) => acc | Convert.ToInt32(dictionary[value])))
: s => dictionary[s.ToLowerInvariant()];
}
}
Expand Down
62 changes: 62 additions & 0 deletions tests/Tests/ClientConcepts/Enums/EnumParsingTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

using System;
using System.Runtime.Serialization;
using FluentAssertions;
using OpenSearch.Net;
using OpenSearch.OpenSearch.Xunit.XunitPlumbing;

namespace Tests.ClientConcepts.Enums;

public class EnumParsingTests
{
[U]
public void CanParseRegularEnum() => KnownEnums.Parse<RegularEnum>("first").Should().Be(RegularEnum.First);

[U]
public void CanParseEnumWithAttribute() => KnownEnums.Parse<EnumWithAttribute>("second_value").Should().Be(EnumWithAttribute.Second);

[U]
public void CanParseFlagsEnum() => KnownEnums.Parse<FlagsEnum>("first,third").Should().Be(FlagsEnum.First | FlagsEnum.Third);

[U]
public void CanParseFlagsEnumWithAttribute() => KnownEnums.Parse<FlagsEnumWithAttribute>("first_value,third_value").Should().Be(FlagsEnumWithAttribute.First | FlagsEnumWithAttribute.Third);

private enum RegularEnum
{
First,
Second
}

private enum EnumWithAttribute
{
[EnumMember(Value = "first_value")]
First,
[EnumMember(Value = "second_value")]
Second
}

[Flags]
private enum FlagsEnum
{
First = 1 << 0,
Second = 1 << 1,
Third = 1 << 2
}

[Flags]
private enum FlagsEnumWithAttribute
{
[EnumMember(Value = "first_value")]
First = 1 << 0,
[EnumMember(Value = "second_value")]
Second = 1 << 1,
[EnumMember(Value = "third_value")]
Third = 1 << 2
}
}

0 comments on commit d8829c8

Please sign in to comment.