Skip to content
This repository has been archived by the owner on Jul 9, 2024. It is now read-only.

SendPrimitiveAsync throws InvalidOperationException for enums #266

Closed
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [1.4.4] - 2024-06-21

### Changed

- Fixes handling enums by `SendPrimitiveAsync`

## [1.4.3] - 2024-05-24

### Changed
Expand Down
278 changes: 278 additions & 0 deletions Microsoft.Kiota.Http.HttpClientLibrary.Tests/RequestAdapterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -535,5 +536,282 @@ public async Task ThrowsApiExceptionOnMissingMapping(HttpStatusCode statusCode)
Assert.Contains("The server returned an unexpected status code and no error factory is registered for this code", apiException.Message);
}
}

[Fact]
public async Task SendPrimitiveHandleEnumIfValueIsString()
{
var mockHandler = new Mock<HttpMessageHandler>();
var client = new HttpClient(mockHandler.Object);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Value1")
});

var mockParseNode = new Mock<IParseNode>();
mockParseNode.Setup(x => x.GetStringValue())
.Returns("Value1");

var mockParseNodeFactory = new Mock<IAsyncParseNodeFactory>();
mockParseNodeFactory.Setup(x => x.GetRootParseNodeAsync(It.IsAny<string>(), It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockParseNode.Object));
var adapter = new HttpClientRequestAdapter(_authenticationProvider, mockParseNodeFactory.Object, httpClient: client);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://example.com")
};

var response = await adapter.SendPrimitiveAsync<TestEnum?>(requestInfo);

Assert.Equal(TestEnum.Value1, response);
}

[Fact]
public async Task SendPrimitiveHandleEnumIfValueIsInteger()
{
var mockHandler = new Mock<HttpMessageHandler>();
var client = new HttpClient(mockHandler.Object);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("1")
});

var mockParseNode = new Mock<IParseNode>();
mockParseNode.Setup(x => x.GetStringValue())
.Returns("1");

var mockParseNodeFactory = new Mock<IAsyncParseNodeFactory>();
mockParseNodeFactory.Setup(x => x.GetRootParseNodeAsync(It.IsAny<string>(), It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockParseNode.Object));
var adapter = new HttpClientRequestAdapter(_authenticationProvider, mockParseNodeFactory.Object, httpClient: client);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://example.com")
};

var response = await adapter.SendPrimitiveAsync<TestEnum?>(requestInfo);

Assert.Equal(TestEnum.Value2, response);
}

[Fact]
public async Task SendPrimitiveHandleEnumIfValueIsFromEnumMember()
{
var mockHandler = new Mock<HttpMessageHandler>();
var client = new HttpClient(mockHandler.Object);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Value__3")
});

var mockParseNode = new Mock<IParseNode>();
mockParseNode.Setup(x => x.GetStringValue())
.Returns("Value__3");

var mockParseNodeFactory = new Mock<IAsyncParseNodeFactory>();
mockParseNodeFactory.Setup(x => x.GetRootParseNodeAsync(It.IsAny<string>(), It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockParseNode.Object));
var adapter = new HttpClientRequestAdapter(_authenticationProvider, mockParseNodeFactory.Object, httpClient: client);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://example.com")
};

var response = await adapter.SendPrimitiveAsync<TestEnum?>(requestInfo);

Assert.Equal(TestEnum.Value3, response);
}

[Fact]
public async Task SendPrimitiveReturnsNullIfValueCannotBeParsedToEnum()
{
var mockHandler = new Mock<HttpMessageHandler>();
var client = new HttpClient(mockHandler.Object);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Value0")
});

var mockParseNode = new Mock<IParseNode>();
mockParseNode.Setup(x => x.GetStringValue())
.Returns("Value0");

var mockParseNodeFactory = new Mock<IAsyncParseNodeFactory>();
mockParseNodeFactory.Setup(x => x.GetRootParseNodeAsync(It.IsAny<string>(), It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockParseNode.Object));
var adapter = new HttpClientRequestAdapter(_authenticationProvider, mockParseNodeFactory.Object, httpClient: client);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://example.com")
};

var response = await adapter.SendPrimitiveAsync<TestEnum?>(requestInfo);

Assert.Null(response);
}

[Fact]
public async Task SendPrimitiveHandleEnumFlagsIfValuesAreStrings()
{
var mockHandler = new Mock<HttpMessageHandler>();
var client = new HttpClient(mockHandler.Object);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Value1,Value3")
});

var mockParseNode = new Mock<IParseNode>();
mockParseNode.Setup(x => x.GetStringValue())
.Returns("Value1,Value3");

var mockParseNodeFactory = new Mock<IAsyncParseNodeFactory>();
mockParseNodeFactory.Setup(x => x.GetRootParseNodeAsync(It.IsAny<string>(), It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockParseNode.Object));
var adapter = new HttpClientRequestAdapter(_authenticationProvider, mockParseNodeFactory.Object, httpClient: client);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://example.com")
};

var response = await adapter.SendPrimitiveAsync<TestEnumWithFlags?>(requestInfo);

Assert.Equal(TestEnumWithFlags.Value1 | TestEnumWithFlags.Value3, response);
}

[Fact]
public async Task SendPrimitiveHandleEnumFlagsIfValuesAreIntegers()
{
var mockHandler = new Mock<HttpMessageHandler>();
var client = new HttpClient(mockHandler.Object);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("1,2")
});

var mockParseNode = new Mock<IParseNode>();
mockParseNode.Setup(x => x.GetStringValue())
.Returns("1,2");

var mockParseNodeFactory = new Mock<IAsyncParseNodeFactory>();
mockParseNodeFactory.Setup(x => x.GetRootParseNodeAsync(It.IsAny<string>(), It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockParseNode.Object));
var adapter = new HttpClientRequestAdapter(_authenticationProvider, mockParseNodeFactory.Object, httpClient: client);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://example.com")
};

var response = await adapter.SendPrimitiveAsync<TestEnumWithFlags?>(requestInfo);

Assert.Equal(TestEnumWithFlags.Value1 | TestEnumWithFlags.Value2, response);
}

[Fact]
public async Task SendPrimitiveHandleEnumFlagsIfValuesAreFromEnumMember()
{
var mockHandler = new Mock<HttpMessageHandler>();
var client = new HttpClient(mockHandler.Object);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Value__3,Value__2")
});

var mockParseNode = new Mock<IParseNode>();
mockParseNode.Setup(x => x.GetStringValue())
.Returns("Value__3,Value__2");

var mockParseNodeFactory = new Mock<IAsyncParseNodeFactory>();
mockParseNodeFactory.Setup(x => x.GetRootParseNodeAsync(It.IsAny<string>(), It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockParseNode.Object));
var adapter = new HttpClientRequestAdapter(_authenticationProvider, mockParseNodeFactory.Object, httpClient: client);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://example.com")
};

var response = await adapter.SendPrimitiveAsync<TestEnumWithFlags?>(requestInfo);

Assert.Equal(TestEnumWithFlags.Value2 | TestEnumWithFlags.Value3, response);
}

[Fact]
public async Task SendPrimitiveReturnsNullIfFlagValueCannotBeParsedToEnum()
{
var mockHandler = new Mock<HttpMessageHandler>();
var client = new HttpClient(mockHandler.Object);
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Value0")
});

var mockParseNode = new Mock<IParseNode>();
mockParseNode.Setup(x => x.GetStringValue())
.Returns("Value0");

var mockParseNodeFactory = new Mock<IAsyncParseNodeFactory>();
mockParseNodeFactory.Setup(x => x.GetRootParseNodeAsync(It.IsAny<string>(), It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(mockParseNode.Object));
var adapter = new HttpClientRequestAdapter(_authenticationProvider, mockParseNodeFactory.Object, httpClient: client);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://example.com")
};

var response = await adapter.SendPrimitiveAsync<TestEnumWithFlags?>(requestInfo);

Assert.Null(response);
}
}

public enum TestEnum
{
[EnumMember(Value = "Value__1")]
Value1,
[EnumMember(Value = "Value__2")]
Value2,
[EnumMember(Value = "Value__3")]
Value3
}

[Flags]
public enum TestEnumWithFlags
{
[EnumMember(Value = "Value__1")]
Value1 = 0x01,
[EnumMember(Value = "Value__2")]
Value2 = 0x02,
[EnumMember(Value = "Value__3")]
Value3 = 0x04
}
}
67 changes: 66 additions & 1 deletion src/HttpClientRequestAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
using System.Text.RegularExpressions;
using System.Diagnostics;
using Microsoft.Kiota.Http.HttpClientLibrary.Middleware;
using System.Reflection;
using System.Runtime.Serialization;

namespace Microsoft.Kiota.Http.HttpClientLibrary
{
Expand Down Expand Up @@ -293,7 +295,70 @@ public string? BaseUrl
{
result = rootNode.GetDateValue();
}
else throw new InvalidOperationException("error handling the response, unexpected type");
else if(
Nullable.GetUnderlyingType(modelType) is { IsEnum: true } underlyingType &&
baywet marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're going to need the AOT annotation on the generic type so people don't get errors when compiling with trimming.
https://github.com/microsoft/kiota-serialization-json-dotnet/blob/d0454daecb7ec2327f3e55d642fa510cf617e8b5/src/JsonParseNode.cs#L579

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The AOT attribute will also be required in the public method declaration I believe.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean something like this?

public async Task<ModelType?> SendPrimitiveAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] ModelType>(RequestInformation requestInfo, Dictionary<string, ParsableFactory<IParsable>>? errorMapping = default, CancellationToken cancellationToken = default)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correct

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@andrueastman @baywet
It's probably a breaking change which requires changes in Microsoft.Kiota.Abstractions

error IL2095: 'DynamicallyAccessedMemberTypes' in 'DynamicallyAccessedMembersAttribute' on the generic parameter 'ModelType' of 'Microsoft.Kiota.Http.HttpClientLibrary.HttpClientRequestAdapter.SendPrimitiveAsync(RequestInformation, Dictionary<String, ParsableFactory>, CancellationToken)' don't match overridden generic parameter 'ModelType' of 'Microsoft.Kiota.Abstractions.IRequestAdapter.SendPrimitiveAsync(RequestInformation, Dictionary<String, ParsableFactory>, CancellationToken)'. All overridden members must have the same 'DynamicallyAccessedMembersAttribute' usage.

Is DynamicallyAccessedMembersAttribute necessary for SendPrimitiveAsync? Reflection is used on the underlying type, not directly on ModelType.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know the internals of AOT/trimming/the type system well enough to have a definitive answer answer to that question.
For changes impacting parse node and others, we did update the original interfaces, and that didn't result in a breaking change for anyone besides maybe people already doing AOT, but they were already broken.
I guess a first step here could be to look at the implementation/annotations on Nullable.GetUnderlyingType(modelType) and see what it requires (any dynamic attribute?) to know whether we need to propagate things here.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At first sight, no dynamic attribute is used in the implementation

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think if we move the functionality to the abstractions side, things will become clearer/different. So, let's make that change first...

rootNode.GetStringValue() is { Length: > 0 } rawValue)
baywet marked this conversation as resolved.
Show resolved Hide resolved
{
if(underlyingType.IsDefined(typeof(FlagsAttribute)))
{
int intValue = 0;
while(rawValue.Length > 0)
{
int commaIndex = rawValue.IndexOf(',');
var valueName = commaIndex < 0 ? rawValue : rawValue.Substring(0, commaIndex);
foreach(var field in underlyingType.GetFields())
{
if(field.GetCustomAttribute<EnumMemberAttribute>() is { } attr && valueName.Equals(attr.Value, StringComparison.Ordinal))
{
valueName = field.Name;
break;
}
}
#if NET5_0_OR_GREATER
if(Enum.TryParse(underlyingType, valueName, true, out var enumPartResult))
intValue |= (int)enumPartResult!;
#else
try
{
intValue |= (int)Enum.Parse(underlyingType, valueName, true);
}
catch { }
#endif

rawValue = commaIndex < 0 ? string.Empty : rawValue.Substring(commaIndex + 1);
}
result = intValue > 0 ? Enum.Parse(underlyingType, intValue.ToString(), true) : null;
}
else
{
foreach(var field in underlyingType.GetFields())
{
if(field.GetCustomAttribute<EnumMemberAttribute>() is { } attr && rawValue.Equals(attr.Value, StringComparison.Ordinal))
{
rawValue = field.Name;
break;
}
}
MartinM85 marked this conversation as resolved.
Show resolved Hide resolved

#if NET5_0_OR_GREATER
Enum.TryParse(underlyingType, rawValue, true, out object? enumResult);
result = enumResult;
#else
try
{
result = Enum.Parse(underlyingType, rawValue, true);
}
catch
{
result = null;
}
#endif
}
}
else
{
throw new InvalidOperationException("error handling the response, unexpected type");
}
SetResponseType(result, span);
return (ModelType)result!;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Kiota.Http.HttpClientLibrary.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<PackageProjectUrl>https://aka.ms/kiota/docs</PackageProjectUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<Deterministic>true</Deterministic>
<VersionPrefix>1.4.3</VersionPrefix>
<VersionPrefix>1.4.4</VersionPrefix>
<VersionSuffix></VersionSuffix>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<!-- Enable this line once we go live to prevent breaking changes -->
Expand Down
Loading