Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 6 additions & 1 deletion InterfaceStubGenerator.Shared/Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ UniqueNameBuilder uniqueNames
ReturnTypeInfo.AsyncVoid => (true, "await (", ").ConfigureAwait(false)"),
ReturnTypeInfo.AsyncResult => (true, "return await (", ").ConfigureAwait(false)"),
ReturnTypeInfo.Return => (false, "return ", ""),
ReturnTypeInfo.SyncVoid => (false, "", ""),
_ => throw new ArgumentOutOfRangeException(
nameof(methodModel.ReturnTypeMetadata),
methodModel.ReturnTypeMetadata,
Expand Down Expand Up @@ -228,12 +229,16 @@ UniqueNameBuilder uniqueNames
lookupName = lookupName.Substring(lastDotIndex + 1);
}

var callExpression = methodModel.ReturnTypeMetadata == ReturnTypeInfo.SyncVoid
? $"______func(this.Client, ______arguments);"
: $"{@return}({returnType})______func(this.Client, ______arguments){configureAwait};";

source.WriteLine(
$"""
var ______arguments = {argumentsArrayString};
var ______func = requestBuilder.BuildRestResultFuncForMethod("{lookupName}", {parameterTypesExpression}{genericString} );

{@return}({returnType})______func(this.Client, ______arguments){configureAwait};
{callExpression}
"""
);

Expand Down
3 changes: 2 additions & 1 deletion InterfaceStubGenerator.Shared/Models/MethodModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ internal enum ReturnTypeInfo : byte
{
Return,
AsyncVoid,
AsyncResult
AsyncResult,
SyncVoid
}
2 changes: 2 additions & 0 deletions InterfaceStubGenerator.Shared/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,7 @@ bool isDerived
{
"Task" => ReturnTypeInfo.AsyncVoid,
"Task`1" or "ValueTask`1" => ReturnTypeInfo.AsyncResult,
"Void" => ReturnTypeInfo.SyncVoid,
_ => ReturnTypeInfo.Return,
};

Expand Down Expand Up @@ -623,6 +624,7 @@ private static MethodModel ParseMethod(IMethodSymbol methodSymbol, bool isImplic
{
"Task" => ReturnTypeInfo.AsyncVoid,
"Task`1" or "ValueTask`1" => ReturnTypeInfo.AsyncResult,
"Void" => ReturnTypeInfo.SyncVoid,
_ => ReturnTypeInfo.Return,
};

Expand Down
7 changes: 4 additions & 3 deletions Refit.GeneratorTests/Refit.GeneratorTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,22 @@
<IsTestProject>true</IsTestProject>
<NoWarn>$(NoWarn);CS1591;CA1819;CA2000;CA2007;CA1056;CA1707;CA1861;xUnit1031</NoWarn>
</PropertyGroup>

<ItemGroup Condition="$(TargetFramework.StartsWith('net9.0'))">
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="9.0.*" />
</ItemGroup>

<ItemGroup Condition="$(TargetFramework.StartsWith('net8.0'))">
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="8.0.*" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="System.Formats.Asn1" Version="9.0.*" />
<PackageReference Include="coverlet.collector" Version="10.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.4.0" />
<PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" />
<PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" />
<PackageReference Include="System.Collections.Immutable" Version="9.0.*" />
<PackageReference Include="Verify.DiffPlex" Version="3.1.2" />
<PackageReference Include="Verify.SourceGenerators" Version="2.5.0" />
<PackageReference Include="Verify.Xunit" Version="31.12.5" />
Expand All @@ -35,7 +36,7 @@
<ProjectReference Include="..\Refit.Newtonsoft.Json\Refit.Newtonsoft.Json.csproj" />
<ProjectReference Include="..\Refit.Xml\Refit.Xml.csproj" />
<ProjectReference Include="..\InterfaceStubGenerator.Roslyn38\InterfaceStubGenerator.Roslyn38.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="true" />
<ProjectReference Include="..\InterfaceStubGenerator.Roslyn41\InterfaceStubGenerator.Roslyn41.csproj" />
<ProjectReference Include="..\InterfaceStubGenerator.Roslyn41\InterfaceStubGenerator.Roslyn41.csproj" OutputItemType="Analyzer" />
<ProjectReference Include="..\Refit\Refit.csproj" />
</ItemGroup>

Expand Down
20 changes: 20 additions & 0 deletions Refit.GeneratorTests/ReturnTypeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ public Task VoidTaskShouldWork()
""");
}

[Fact]
public Task GenericValueTaskShouldWork()
{
return Fixture.VerifyForBody(
"""
[Get("/users")]
ValueTask<string> Get();
""");
}

[Fact]
public Task ValueTaskApiResponseShouldWork()
{
return Fixture.VerifyForBody(
"""
[Get("/users")]
ValueTask<ApiResponse<string>> Get();
""");
}

[Fact]
public Task GenericConstraintReturnTask()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//HintName: IGeneratedClient.g.cs
#nullable disable
#pragma warning disable
namespace Refit.Implementation
{

partial class Generated
{

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::RefitInternalGenerated.PreserveAttribute]
[global::System.Reflection.Obfuscation(Exclude=true)]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
partial class RefitGeneratorTestIGeneratedClient
: global::RefitGeneratorTest.IGeneratedClient
{
/// <inheritdoc />
public global::System.Net.Http.HttpClient Client { get; }
readonly global::Refit.IRequestBuilder requestBuilder;

/// <inheritdoc />
public RefitGeneratorTestIGeneratedClient(global::System.Net.Http.HttpClient client, global::Refit.IRequestBuilder requestBuilder)
{
Client = client;
this.requestBuilder = requestBuilder;
}


/// <inheritdoc />
public async global::System.Threading.Tasks.ValueTask<string> Get()
{
var ______arguments = global::System.Array.Empty<object>();
var ______func = requestBuilder.BuildRestResultFuncForMethod("Get", global::System.Array.Empty<global::System.Type>() );

return await ((global::System.Threading.Tasks.ValueTask<string>)______func(this.Client, ______arguments)).ConfigureAwait(false);
}
}
}
}

#pragma warning restore
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//HintName: IGeneratedClient.g.cs
#nullable disable
#pragma warning disable
namespace Refit.Implementation
{

partial class Generated
{

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::RefitInternalGenerated.PreserveAttribute]
[global::System.Reflection.Obfuscation(Exclude=true)]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
partial class RefitGeneratorTestIGeneratedClient
: global::RefitGeneratorTest.IGeneratedClient
{
/// <inheritdoc />
public global::System.Net.Http.HttpClient Client { get; }
readonly global::Refit.IRequestBuilder requestBuilder;

/// <inheritdoc />
public RefitGeneratorTestIGeneratedClient(global::System.Net.Http.HttpClient client, global::Refit.IRequestBuilder requestBuilder)
{
Client = client;
this.requestBuilder = requestBuilder;
}


/// <inheritdoc />
public async global::System.Threading.Tasks.ValueTask<global::Refit.ApiResponse<string>> Get()
{
var ______arguments = global::System.Array.Empty<object>();
var ______func = requestBuilder.BuildRestResultFuncForMethod("Get", global::System.Array.Empty<global::System.Type>() );

return await ((global::System.Threading.Tasks.ValueTask<global::Refit.ApiResponse<string>>)______func(this.Client, ______arguments)).ConfigureAwait(false);
}
}
}
}

#pragma warning restore
28 changes: 28 additions & 0 deletions Refit.Tests/AuthenticatedClientHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,34 @@ public async Task AuthorizationHeaderValueGetterIsUsedWhenSupplyingHttpClient()
Assert.Equal("Ok", result);
}

[Fact]
public async Task AuthorizationHeaderValueGetterCanAwaitWhenSupplyingHttpClient()
{
var handler = new MockHttpMessageHandler();
var httpClient = new HttpClient(handler) { BaseAddress = new Uri("http://api") };

var settings = new RefitSettings
{
AuthorizationHeaderValueGetter = async (_, __) =>
{
await Task.Yield();
return "tokenValue";
}
};

handler
.Expect(HttpMethod.Get, "http://api/auth")
.WithHeaders("Authorization", "Bearer tokenValue")
.Respond("text/plain", "Ok");

var fixture = RestService.For<IMyAuthenticatedService>(httpClient, settings);

var result = await fixture.GetAuthenticated();

handler.VerifyNoOutstandingExpectation();
Assert.Equal("Ok", result);
}

[Fact]
public async Task AuthorizationHeaderValueGetterDoesNotOverrideExplicitTokenWhenSupplyingHttpClient()
{
Expand Down
20 changes: 20 additions & 0 deletions Refit.Tests/CachedRequestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,26 @@ public interface IDuplicateNames

public class CachedRequestBuilderTests
{
[Fact]
public void CachedBuilder_ThrowsForNullInnerBuilder()
{
Assert.Throws<ArgumentNullException>(() => new CachedRequestBuilderImplementation(null!));
}

[Fact]
public void MethodTableKey_ObjectEquals_And_GenericArgumentDifference_AreCovered()
{
var key = new MethodTableKey("Foo", [typeof(string)], [typeof(int)]);
object same = new MethodTableKey("Foo", [typeof(string)], [typeof(int)]);
object different = new MethodTableKey("Foo", [typeof(string)], [typeof(long)]);
var differentParameter = new MethodTableKey("Foo", [typeof(int)], [typeof(int)]);

Assert.True(key.Equals(same));
Assert.False(key.Equals(different));
Assert.False(key.Equals(differentParameter));
Assert.False(key.Equals(new object()));
}

[Fact]
public async Task CacheHasCorrectNumberOfElementsTest()
{
Expand Down
Loading
Loading