Skip to content
Open
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,7 +188,8 @@
ReturnTypeInfo.AsyncVoid => (true, "await (", ").ConfigureAwait(false)"),
ReturnTypeInfo.AsyncResult => (true, "return await (", ").ConfigureAwait(false)"),
ReturnTypeInfo.Return => (false, "return ", ""),
ReturnTypeInfo.SyncVoid => (false, "", ""),
_ => throw new ArgumentOutOfRangeException(

Check warning on line 192 in InterfaceStubGenerator.Shared/Emitter.cs

View workflow job for this annotation

GitHub Actions / build / build-unix (ubuntu-latest)

Method WriteRefitMethod passes 'ReturnTypeMetadata' as the paramName argument to a ArgumentOutOfRangeException constructor. Replace this argument with one of the method's parameter names. Note that the provided parameter name should have the exact casing as declared on the method. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2208)

Check warning on line 192 in InterfaceStubGenerator.Shared/Emitter.cs

View workflow job for this annotation

GitHub Actions / build / build-windows

Method WriteRefitMethod passes 'ReturnTypeMetadata' as the paramName argument to a ArgumentOutOfRangeException constructor. Replace this argument with one of the method's parameter names. Note that the provided parameter name should have the exact casing as declared on the method. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2208)
nameof(methodModel.ReturnTypeMetadata),
methodModel.ReturnTypeMetadata,
"Unsupported value."
Expand Down Expand Up @@ -228,12 +229,16 @@
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 Expand Up @@ -317,7 +322,7 @@
if (isExplicitInterface)
{
var ct = methodModel.ContainingType;
if (!ct.StartsWith("global::"))

Check warning on line 325 in InterfaceStubGenerator.Shared/Emitter.cs

View workflow job for this annotation

GitHub Actions / build / build-unix (ubuntu-latest)

The behavior of 'string.StartsWith(string)' could vary based on the current user's locale settings. Replace this call in 'Refit.Generator.Emitter.WriteMethodOpening(Refit.Generator.SourceWriter, Refit.Generator.MethodModel, bool, bool, bool)' with a call to 'string.StartsWith(string, System.StringComparison)'. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1310)

Check warning on line 325 in InterfaceStubGenerator.Shared/Emitter.cs

View workflow job for this annotation

GitHub Actions / build / build-windows

The behavior of 'string.StartsWith(string)' could vary based on the current user's locale settings. Replace this call in 'Refit.Generator.Emitter.WriteMethodOpening(Refit.Generator.SourceWriter, Refit.Generator.MethodModel, bool, bool, bool)' with a call to 'string.StartsWith(string, System.StringComparison)'. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1310)
{
ct = "global::" + ct;
}
Expand All @@ -337,7 +342,7 @@
builder.Append(string.Join(", ", list));
}

builder.Append(")");

Check warning on line 345 in InterfaceStubGenerator.Shared/Emitter.cs

View workflow job for this annotation

GitHub Actions / build / build-unix (ubuntu-latest)

Use 'StringBuilder.Append(char)' instead of 'StringBuilder.Append(string)' when the input is a constant unit string (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1834)

Check warning on line 345 in InterfaceStubGenerator.Shared/Emitter.cs

View workflow job for this annotation

GitHub Actions / build / build-windows

Use 'StringBuilder.Append(char)' instead of 'StringBuilder.Append(string)' when the input is a constant unit string (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1834)

source.WriteLine();
source.WriteLine(builder.ToString());
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 @@ -43,7 +43,7 @@
// TODO: we should allow source generators to provide source during initialize, so that this step isn't required.
var options = (CSharpParseOptions)compilation.SyntaxTrees[0].Options;

var disposableInterfaceSymbol = wellKnownTypes.Get(typeof(IDisposable));

Check warning on line 46 in InterfaceStubGenerator.Shared/Parser.cs

View workflow job for this annotation

GitHub Actions / build / build-unix (ubuntu-latest)

Prefer the generic overload 'Refit.Generator.WellKnownTypes.Get<T>()' instead of 'Refit.Generator.WellKnownTypes.Get(System.Type)' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2263)

Check warning on line 46 in InterfaceStubGenerator.Shared/Parser.cs

View workflow job for this annotation

GitHub Actions / build / build-windows

Prefer the generic overload 'Refit.Generator.WellKnownTypes.Get<T>()' instead of 'Refit.Generator.WellKnownTypes.Get(System.Type)' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2263)
var httpMethodBaseAttributeSymbol = wellKnownTypes.TryGet(
"Refit.HttpMethodAttribute"
);
Expand Down Expand Up @@ -462,6 +462,7 @@
{
"Task" => ReturnTypeInfo.AsyncVoid,
"Task`1" or "ValueTask`1" => ReturnTypeInfo.AsyncResult,
"Void" => ReturnTypeInfo.SyncVoid,
_ => ReturnTypeInfo.Return,
};

Expand Down Expand Up @@ -623,6 +624,7 @@
{
"Task" => ReturnTypeInfo.AsyncVoid,
"Task`1" or "ValueTask`1" => ReturnTypeInfo.AsyncResult,
"Void" => ReturnTypeInfo.SyncVoid,
_ => ReturnTypeInfo.Return,
};

Expand Down
7 changes: 3 additions & 4 deletions Refit.GeneratorTests/Refit.GeneratorTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,20 @@
<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="8.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<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 +34,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