Skip to content

Commit 285cc67

Browse files
authored
fix: resolve generated clients when the module initializer runs late (#2289)
* fix: resolve generated clients when the module initializer runs late - Force the interface assembly's module constructor when a generated client lookup misses, then look again. Mono (Blazor WebAssembly) may not have run it yet, so the registry looked empty. - Resolve the generated type by name on .NET Framework, where no module initializer is emitted at all. - Cover the retry path with tests and assert it works under Native AOT. Closes #2287 * test: add a .NET Framework smoke test for generated clients - Exercise RestService.ForGenerated on net462 - net481, where the generator emits no module initializer and the client has to be resolved by name. - Cover a GET, a POST body, a generated query string, a repeat lookup, and the error for an interface with no generated client. - Run it on net472 and net481 from a Windows CI job, since the test matrix is net8.0 - net11.0 only. * build: exclude the smoke tests from Sonar coverage - Both smoke tests are standalone executables run outside the test harness, so no collector instruments them. - Applied to the same-repo and fork Sonar workflows, which carry the same exclusion lists.
1 parent 69ee15f commit 285cc67

20 files changed

Lines changed: 777 additions & 35 deletions

‎.github/workflows/netfx-smoke.yml‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
name: .NET Framework smoke
2+
3+
on:
4+
push:
5+
branches: [ main ]
6+
pull_request:
7+
branches: [ main ]
8+
9+
permissions:
10+
contents: read
11+
12+
jobs:
13+
netfx-smoke:
14+
runs-on: windows-latest
15+
steps:
16+
- name: Checkout
17+
uses: actions/checkout@v7
18+
19+
- name: Setup .NET
20+
uses: actions/setup-dotnet@v6
21+
with:
22+
dotnet-version: 11.x
23+
dotnet-quality: preview
24+
25+
- name: Build the smoke test
26+
run: dotnet build src/Refit.NetFrameworkSmoke/Refit.NetFrameworkSmoke.csproj -c Release
27+
28+
# The generator emits its factory registrations inside #if NET5_0_OR_GREATER, so these targets resolve the
29+
# generated client by name instead. Nothing else in the test matrix runs on .NET Framework.
30+
- name: Run on net472
31+
run: src\Refit.NetFrameworkSmoke\bin\Release\net472\Refit.NetFrameworkSmoke.exe
32+
33+
- name: Run on net481
34+
run: src\Refit.NetFrameworkSmoke\bin\Release\net481\Refit.NetFrameworkSmoke.exe

‎.github/workflows/sonarcloud-fork.yml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ jobs:
2727
sonarProjectKey: reactiveui_refit
2828
sonarOrganization: reactiveui
2929
sonarExclusions: '**/tests/**,**/benchmarks/**,**/examples/**,**/TestResults/**'
30-
sonarCoverageExclusions: '**/tests/**,**/benchmarks/**,**/examples/**,**/*Tests/**,**/*Tests.cs,**/Generated/**,**/*.g.cs'
30+
# The smoke tests are standalone executables run outside the test harness, so no collector instruments them.
31+
sonarCoverageExclusions: '**/tests/**,**/benchmarks/**,**/examples/**,**/*Tests/**,**/*Tests.cs,**/Generated/**,**/*.g.cs,**/Refit.NativeAotSmoke/**,**/Refit.NetFrameworkSmoke/**'
3132
sonarCpdExclusions: '**/tests/**,**/benchmarks/**,**/examples/**'
3233
sonarTestExclusions: '**/tests/**,**/benchmarks/**,**/examples/**'
3334
testTimeout: '15m'

‎.github/workflows/sonarcloud.yml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ jobs:
1919
sonarProjectKey: reactiveui_refit
2020
sonarOrganization: reactiveui
2121
sonarExclusions: '**/tests/**,**/benchmarks/**,**/examples/**,**/TestResults/**'
22-
sonarCoverageExclusions: '**/tests/**,**/benchmarks/**,**/examples/**,**/*Tests/**,**/*Tests.cs,**/Generated/**,**/*.g.cs'
22+
# The smoke tests are standalone executables run outside the test harness, so no collector instruments them.
23+
sonarCoverageExclusions: '**/tests/**,**/benchmarks/**,**/examples/**,**/*Tests/**,**/*Tests.cs,**/Generated/**,**/*.g.cs,**/Refit.NativeAotSmoke/**,**/Refit.NetFrameworkSmoke/**'
2324
sonarCpdExclusions: '**/tests/**,**/benchmarks/**,**/examples/**'
2425
sonarTestExclusions: '**/tests/**,**/benchmarks/**,**/examples/**'
2526
testTimeout: '15m'
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved.
2+
// ReactiveUI and Contributors licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for full license information.
4+
5+
namespace Refit.NativeAotSmoke;
6+
7+
/// <summary>An interface carrying no Refit attributes, so the generator emits no client and no registration for it.</summary>
8+
internal interface INoGeneratedClientApi
9+
{
10+
/// <summary>Sends a request.</summary>
11+
/// <returns>The response body.</returns>
12+
Task<string> GetAsync();
13+
}

‎src/Refit.NativeAotSmoke/Program.cs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,24 @@
7272
throw new InvalidOperationException("The AOT URL-encoded request body was not serialized through generated Refit code.");
7373
}
7474

75+
// A missed generated-client lookup forces the interface assembly's module initializer and looks again, which is what
76+
// rescues runtimes that have not run it yet. Prove that forcing path is reachable under Native AOT.
77+
string? missingClientMessage = null;
78+
79+
try
80+
{
81+
_ = RestService.ForGenerated<INoGeneratedClientApi>(client);
82+
}
83+
catch (InvalidOperationException ex)
84+
{
85+
missingClientMessage = ex.Message;
86+
}
87+
88+
if (missingClientMessage?.Contains("doesn't look like a Refit interface", StringComparison.Ordinal) != true)
89+
{
90+
throw new InvalidOperationException("The AOT lookup for a missing generated client did not report it.");
91+
}
92+
7593
Console.WriteLine("Native AOT Refit smoke test passed.");
7694

7795
/// <summary>The generated top-level program's declaring type, sealed so the JIT can devirtualize its members.</summary>
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
[*.cs]
2+
3+
# SST1449: Avoid writing directly to the console.
4+
# The smoke test reports its pass/fail result on stdout; that is the whole point of the program.
5+
dotnet_diagnostic.SST1449.severity = none
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved.
2+
// ReactiveUI and Contributors licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for full license information.
4+
5+
namespace Refit.NetFrameworkSmoke;
6+
7+
/// <summary>The Refit interface exercised by the .NET Framework smoke test. Every method generates inline, so the
8+
/// smoke test never needs the reflection request builder.</summary>
9+
internal interface INetFrameworkSmokeApi
10+
{
11+
/// <summary>Fetches a todo by identifier.</summary>
12+
/// <param name="id">The todo identifier.</param>
13+
/// <returns>The fetched todo.</returns>
14+
[Get("/todos/{id}")]
15+
Task<Todo> GetTodoAsync(int id);
16+
17+
/// <summary>Creates a todo.</summary>
18+
/// <param name="todo">The todo to create.</param>
19+
/// <returns>The created todo.</returns>
20+
[Post("/todos")]
21+
Task<Todo> CreateTodoAsync([Body] Todo todo);
22+
23+
/// <summary>Searches todos.</summary>
24+
/// <param name="q">The search term.</param>
25+
/// <param name="page">The page number.</param>
26+
/// <returns>The raw response body.</returns>
27+
[Get("/search")]
28+
Task<string> SearchAsync(string q, int page);
29+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved.
2+
// ReactiveUI and Contributors licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for full license information.
4+
5+
namespace Refit.NetFrameworkSmoke;
6+
7+
/// <summary>An interface carrying no Refit attributes, so the generator emits no client for it.</summary>
8+
internal interface INoGeneratedClientApi
9+
{
10+
/// <summary>Sends a request.</summary>
11+
/// <returns>The response body.</returns>
12+
Task<string> GetAsync();
13+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved.
2+
// ReactiveUI and Contributors licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for full license information.
4+
using System.Net;
5+
using System.Text;
6+
7+
namespace Refit.NetFrameworkSmoke;
8+
9+
/// <summary>A test HTTP message handler that serves canned responses for the .NET Framework smoke test.</summary>
10+
internal sealed class NetFrameworkSmokeHandler : HttpMessageHandler
11+
{
12+
/// <summary>Gets a value indicating whether a POST body containing the expected payload was observed.</summary>
13+
internal bool SawPostBody { get; private set; }
14+
15+
/// <summary>Gets a value indicating whether the generated query string matched the expected shape.</summary>
16+
internal bool SawExpectedQuery { get; private set; }
17+
18+
/// <inheritdoc/>
19+
protected override async Task<HttpResponseMessage> SendAsync(
20+
HttpRequestMessage request,
21+
CancellationToken cancellationToken)
22+
{
23+
if (request.RequestUri?.AbsolutePath == "/todos")
24+
{
25+
var body = request.Content is null
26+
? string.Empty
27+
: await request.Content.ReadAsStringAsync().ConfigureAwait(false);
28+
29+
SawPostBody = body.IndexOf("prove net framework", StringComparison.Ordinal) >= 0;
30+
31+
return Json("{\"id\":42,\"title\":\"prove net framework\"}");
32+
}
33+
34+
if (request.RequestUri?.AbsolutePath == "/search")
35+
{
36+
SawExpectedQuery = request.RequestUri.PathAndQuery == "/search?q=a%20b&page=3";
37+
38+
return new(HttpStatusCode.OK) { Content = new StringContent("found", Encoding.UTF8, "text/plain") };
39+
}
40+
41+
return request.RequestUri?.AbsolutePath == "/todos/42"
42+
? Json("{\"id\":42,\"title\":\"fetched on net framework\"}")
43+
: new(HttpStatusCode.NotFound);
44+
}
45+
46+
/// <summary>Builds an OK response with the given JSON content.</summary>
47+
/// <param name="content">The JSON content for the response body.</param>
48+
/// <returns>The constructed JSON response message.</returns>
49+
private static HttpResponseMessage Json(string content) =>
50+
new(HttpStatusCode.OK) { Content = new StringContent(content, Encoding.UTF8, "application/json") };
51+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved.
2+
// ReactiveUI and Contributors licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for full license information.
4+
using Refit;
5+
using Refit.NetFrameworkSmoke;
6+
7+
const int ExpectedTodoId = 42;
8+
9+
const int SearchPage = 3;
10+
11+
const string MissingClientFragment = "doesn't look like a Refit interface";
12+
13+
var handler = new NetFrameworkSmokeHandler();
14+
15+
using var client = new HttpClient(handler) { BaseAddress = new("https://netfx.refit.test") };
16+
17+
// .NET Framework has no [ModuleInitializer], so the generator emits no factory registrations here and the registries
18+
// stay empty. ForGenerated has to resolve the generated implementation by name for any of this to work at all.
19+
var api = RestService.ForGenerated<INetFrameworkSmokeApi>(client);
20+
21+
var fetched = await api.GetTodoAsync(ExpectedTodoId).ConfigureAwait(false);
22+
23+
if (fetched.Id != ExpectedTodoId || fetched.Title != "fetched on net framework")
24+
{
25+
throw new InvalidOperationException("The .NET Framework GET response was not deserialized correctly.");
26+
}
27+
28+
var created = await api.CreateTodoAsync(new(ExpectedTodoId, "prove net framework")).ConfigureAwait(false);
29+
30+
if (created.Id != ExpectedTodoId || created.Title != "prove net framework")
31+
{
32+
throw new InvalidOperationException("The .NET Framework POST response was not deserialized correctly.");
33+
}
34+
35+
if (!handler.SawPostBody)
36+
{
37+
throw new InvalidOperationException("The .NET Framework request body was not serialized through Refit.");
38+
}
39+
40+
var searched = await api.SearchAsync("a b", SearchPage).ConfigureAwait(false);
41+
42+
if (searched != "found" || !handler.SawExpectedQuery)
43+
{
44+
throw new InvalidOperationException("The .NET Framework generated query string was not constructed correctly.");
45+
}
46+
47+
// Resolving the same interface twice must reuse the cached generated type rather than resolving it again.
48+
if (RestService.ForGenerated<INetFrameworkSmokeApi>(client) is null)
49+
{
50+
throw new InvalidOperationException("The .NET Framework repeat lookup did not return a generated client.");
51+
}
52+
53+
// An interface the generator never saw must still report that clearly instead of failing some other way.
54+
string? missingClientMessage = null;
55+
56+
try
57+
{
58+
_ = RestService.ForGenerated<INoGeneratedClientApi>(client);
59+
}
60+
catch (InvalidOperationException ex)
61+
{
62+
missingClientMessage = ex.Message;
63+
}
64+
65+
if (missingClientMessage?.IndexOf(MissingClientFragment, StringComparison.Ordinal) < 0
66+
|| missingClientMessage is null)
67+
{
68+
throw new InvalidOperationException("The .NET Framework lookup for a missing generated client did not report it.");
69+
}
70+
71+
Console.WriteLine("Refit .NET Framework smoke test passed.");
72+
73+
/// <summary>The generated top-level program's declaring type, sealed so the JIT can devirtualize its members.</summary>
74+
internal sealed partial class Program
75+
{
76+
/// <summary>Initializes a new instance of the <see cref="Program"/> class. Unused; the entry point is the generated top-level <c>Main</c>.</summary>
77+
private Program()
78+
{
79+
}
80+
}

0 commit comments

Comments
 (0)
⌂ 换网址