Files
octokit.net/Octokit/Models/Response/StringEnum.cs
Kristian Hellang 5ee4d64046 Add StringEnum to handle unknown enum values returned from API (#1595)
* Added StringEnum<TEnum>

* Added tests

* Make sure the serializer can work with StringEnum

* Use StringEnum for EventInfo.Event

* Add convention test to assert that all Response models use StringEnum<> to wrap enum properties

* Add Stringnum<> to all response types failing convention test

* Handle StringEnum to Enum conversion when Issue response model populates IssueUpdate request model

* Fix unit test

* Refactor SimpleJsonSerializer to expose the DeserializeEnum strategy so it can be used in StringEnum class

* Need to expose/use SerializeEnum functionality too, so we use the correct string representation of enum values that have custom properties (eg ReactionType Plus1 to "+1")

* fix unit tests, since the string is now the "correct" upstream api value

* Add a couple of tests for the Enum serialize/deserialize when underscores, hyphens and custom property attributes are present

* Compare parsed values for equality

* add convention test to ensure enum members all have Parameter property set

* update test to cover implicit conversions too

* this test should work but fails at the moment due to magic hyphen removal in deserializer causing a one way trip from utf-8 to EncodingType.Utf8 with no way to get back

* (unsuccesfully) expand event info test to try to catch more cases of unknown event types

* fix broken integration test while im here

* Fixed build errors after .NET Core merge

* Value -> StringValue, ParsedValue -> Value

* Don't allow StringValue to be null

* Ignore enums not used in request/response models

* Added ParameterAttribute to almost all enum values

* Ignore Language enum

* Fix failing tests

* Fix milestone sort parameter and tests

* whitespace

* fix milestone unit tests

* Fix StringEnum.Equals ... This could've been embarrassing!

* Change SimpleJsonSerializer Enum handling to only use `[Parameter()]` attributes (no more magic removal of hyphen/underscores from strings)

* Tidy up this integration test while im here

* Only test request/response enums in convention test

* Keep skipping Language

* Remove unused method

* Remove excluded enum types

* Removed unnecessary ParameterAttributes

* Remove unused enum

* Add StringEnum test for string-comparison of two invalid values

* Bring back IssueCommentSort and use it in IssueCommentRequest

This reverts commit 38a4a291d1476ef8c992fe0f76956974b6f32a49.

* Use assembly instead of namespace for Octokit check

* Add failing test to reproduce the issue where only the first enum paramter/value was added to the cache

* Fix deserializer enum cache to include all enum members rather than only the first member encountered

* Use a static SimpleJsonSerializer in StringEnum

* Remove serializer instance in StringEnum

* Add some documentation on StringEnum<TEnum>

* Fix parameter value to resolve failing integration test
2017-06-25 19:29:57 +10:00

156 lines
4.5 KiB
C#

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Octokit.Internal;
namespace Octokit
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public struct StringEnum<TEnum> : IEquatable<StringEnum<TEnum>>
where TEnum : struct
{
private readonly string _stringValue;
private TEnum? _parsedValue;
public StringEnum(TEnum parsedValue)
{
if (!Enum.IsDefined(typeof(TEnum), parsedValue))
{
throw GetArgumentException(parsedValue.ToString());
}
// Use the SimpleJsonSerializer to serialize the TEnum into the correct string according to the GitHub Api strategy
_stringValue = SimpleJsonSerializer.SerializeEnum(parsedValue as Enum);
_parsedValue = parsedValue;
}
public StringEnum(string stringValue)
{
_stringValue = stringValue ?? string.Empty;
_parsedValue = null;
}
public string StringValue
{
get { return _stringValue; }
}
public TEnum Value
{
get { return _parsedValue ?? (_parsedValue = ParseValue()).Value; }
}
internal string DebuggerDisplay
{
get { return StringValue; }
}
public bool TryParse(out TEnum value)
{
if (_parsedValue.HasValue)
{
// the value has been parsed already.
value = _parsedValue.Value;
return true;
}
if (string.IsNullOrEmpty(StringValue))
{
value = default(TEnum);
return false;
}
try
{
// Use the SimpleJsonSerializer to parse the string to Enum according to the GitHub Api strategy
value = (TEnum)SimpleJsonSerializer.DeserializeEnum(StringValue, typeof(TEnum));
// cache the parsed value for subsequent calls.
_parsedValue = value;
return true;
}
catch (ArgumentException)
{
value = default(TEnum);
return false;
}
}
public bool Equals(StringEnum<TEnum> other)
{
TEnum value;
TEnum otherValue;
if (TryParse(out value) && other.TryParse(out otherValue))
{
// if we're able to parse both values, compare the parsed enum
return value.Equals(otherValue);
}
// otherwise, we fall back to a case-insensitive comparison of the string values.
return string.Equals(StringValue, other.StringValue, StringComparison.OrdinalIgnoreCase);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is StringEnum<TEnum> && Equals((StringEnum<TEnum>) obj);
}
public override int GetHashCode()
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(StringValue);
}
public static bool operator ==(StringEnum<TEnum> left, StringEnum<TEnum> right)
{
return left.Equals(right);
}
public static bool operator !=(StringEnum<TEnum> left, StringEnum<TEnum> right)
{
return !left.Equals(right);
}
public static implicit operator StringEnum<TEnum>(string value)
{
return new StringEnum<TEnum>(value);
}
public static implicit operator StringEnum<TEnum>(TEnum parsedValue)
{
return new StringEnum<TEnum>(parsedValue);
}
public override string ToString()
{
return StringValue;
}
private TEnum ParseValue()
{
TEnum value;
if (TryParse(out value))
{
return value;
}
throw GetArgumentException(StringValue);
}
private static ArgumentException GetArgumentException(string value)
{
return new ArgumentException(string.Format(
CultureInfo.InvariantCulture,
"Value '{0}' is not a valid '{1}' enum value.",
value,
typeof(TEnum).Name));
}
}
}