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 3 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
107 changes: 107 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,111 @@ 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 SendMethodHandleEnumIfValueIsString()
{
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 SendMethodHandleEnumIfValueIsInteger()
{
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 SendMethodHandleEnumIfValueIsFromEnumMember()
{
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);
}
}

public enum TestEnum
{
[EnumMember(Value = "Value__1")]
Value1,
[EnumMember(Value = "Value__2")]
Value2,
[EnumMember(Value = "Value__3")]
Value3
}
}
21 changes: 20 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,24 @@ 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
{
foreach(var field in underlyingType.GetFields())
{
if(field.GetCustomAttribute<EnumMemberAttribute>() is { } attr && rawValue.Equals(attr.Value, StringComparison.Ordinal))
{
rawValue = field.Name;
break;
}
}
result = Enum.Parse(underlyingType, rawValue, true);
MartinM85 marked this conversation as resolved.
Show resolved Hide resolved
}
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