Skip to content

Commit a463e8a

Browse files
authored
test(bodies): cover the remaining typed JSON Lines branches (#2339)
* test(bodies): cover the remaining typed JSON Lines branches Adds reflection request-builder and JsonLinesContent<T> tests to close the Codecov patch-coverage gaps on PR #2338: - FindAsyncJsonLinesElementType: a class implementing IAsyncEnumerable<T> is found through GetInterfaces (rather than being that interface itself), and a type implementing two distinct IAsyncEnumerable<> interfaces is treated as ambiguous and returns null. - JsonLinesContent<T>.MoveNextAsync: a stream whose FlushAsync throws while the producer's next step is still pending propagates the failure only after that step completes, so the enumerator is never disposed while it is in flight. Two lines remain uncovered and are genuinely unreachable, not contorted around: - JsonLinesContent<T>'s 2-arg SerializeToStreamAsync override: on NET8_0_OR_GREATER, HttpContent's internal plumbing always invokes the 3-arg CancellationToken overload (verified empirically), so the 2-arg override is dead code once both are overridden; it only matters on the netfx targets that lack the 3-arg overload. - The closing brace of the catch block in MoveNextAsync: that catch always ends with 'throw;', so the sequence point for falling through the catch normally can never fire. * test(bodies): cover the .NET Framework serialize entry point and simplify the flush wait * test(bodies): arm the flush failure only after the first element is written
1 parent 0418743 commit a463e8a

3 files changed

Lines changed: 180 additions & 14 deletions

File tree

‎src/Refit/JsonLinesContent{T}.cs‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -120,20 +120,23 @@ private static async ValueTask<bool> MoveNextAsync(
120120
return await pending.ConfigureAwait(false);
121121
}
122122

123+
// Waiting on both means a failed flush still lets the producer's step finish before the exception propagates.
123124
var moveNext = pending.AsTask();
124-
try
125-
{
126-
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
127-
}
128-
catch
129-
{
130-
await moveNext.ContinueWith(static _ => { }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default).ConfigureAwait(false);
131-
throw;
132-
}
133-
125+
await Task.WhenAll(FlushAsync(stream, cancellationToken), moveNext).ConfigureAwait(false);
134126
return await moveNext.ConfigureAwait(false);
135127
}
136128

129+
/// <summary>Flushes the stream, reporting a synchronous failure through the returned task.</summary>
130+
/// <param name="stream">The request body stream.</param>
131+
/// <param name="cancellationToken">The send's cancellation token.</param>
132+
/// <returns>A task that completes when the flush does.</returns>
133+
[System.Diagnostics.CodeAnalysis.SuppressMessage(
134+
"Performance",
135+
"PSH1311:Return the task directly instead of awaiting it",
136+
Justification = "Awaiting turns a synchronous throw from FlushAsync into a faulted task, so Task.WhenAll still waits for the producer's step.")]
137+
private static async Task FlushAsync(Stream stream, CancellationToken cancellationToken) =>
138+
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
139+
137140
/// <summary>Writes the line-feed byte that separates or terminates lines.</summary>
138141
/// <param name="stream">The request body stream.</param>
139142
/// <param name="cancellationToken">A token to cancel the write.</param>

‎src/tests/Refit.Tests/JsonLinesContentTypedTests.cs‎

Lines changed: 117 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@ public class JsonLinesContentTypedTests
1919
/// <summary>The number of sends performed by the re-enumeration test.</summary>
2020
private const int TwoSends = 2;
2121

22+
/// <summary>The name of the first element produced by a two-element gated sequence.</summary>
23+
private const string FirstElementName = "first";
24+
25+
/// <summary>The name of the second element produced by a two-element gated sequence.</summary>
26+
private const string SecondElementName = "second";
27+
2228
/// <summary>The serializer used directly by these tests.</summary>
2329
private static readonly SystemTextJsonContentSerializer Serializer = new();
2430

@@ -229,10 +235,73 @@ public async Task FlushesBeforeWaitingOnAPendingProducer()
229235

230236
static async IAsyncEnumerable<SealedRecord> GatedAsync(TaskCompletionSource gate)
231237
{
232-
yield return new("1", "first");
238+
yield return new("1", FirstElementName);
233239
await gate.Task;
234-
yield return new("2", "second");
240+
yield return new("2", SecondElementName);
241+
}
242+
}
243+
244+
/// <summary>Verifies a flush failure that occurs while the producer's next step is still pending is rethrown
245+
/// only after that step completes, so the enumerator is disposed once, after the pending step finishes rather
246+
/// than while it is still in flight.</summary>
247+
/// <returns>A task representing the asynchronous test.</returns>
248+
[Test]
249+
public async Task FlushFailurePropagatesAfterThePendingProducerStepCompletes()
250+
{
251+
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
252+
var flushInvoked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
253+
var tracker = new DisposeTracker();
254+
var stream = new FlushThrowingStream(flushInvoked);
255+
var content = new JsonLinesContent<SealedRecord>(GatedTrackedAsync(gate, tracker, stream), Serializer);
256+
try
257+
{
258+
var copy = content.CopyToAsync(stream, CancellationToken.None);
259+
260+
// The flush that precedes the wait on the still-pending second element has already run (and failed) by
261+
// the time this point is reached: CopyToAsync only suspends once it starts awaiting that pending step.
262+
await flushInvoked.Task.WaitAsync(FlushWaitTimeout);
263+
await Assert.That(tracker.Disposed).IsFalse();
264+
265+
gate.SetResult();
266+
267+
// HttpContent.CopyToAsync wraps a stream-copy failure in HttpRequestException; the flush failure
268+
// survives as its InnerException.
269+
var exception = await Assert.That(async () => await copy).ThrowsExactly<HttpRequestException>();
270+
271+
await Assert.That(exception!.InnerException).IsTypeOf<IOException>();
235272
}
273+
finally
274+
{
275+
content.Dispose();
276+
}
277+
278+
await Assert.That(tracker.Disposed).IsTrue();
279+
}
280+
281+
/// <summary>
282+
/// Verifies the token-less serialize override, the entry point on .NET Framework where the cancellable overload
283+
/// does not exist, writes the same body as a normal send.
284+
/// </summary>
285+
/// <returns>A task representing the asynchronous test.</returns>
286+
[Test]
287+
[System.Diagnostics.CodeAnalysis.SuppressMessage(
288+
"Security",
289+
"SES1406:Avoid reaching non-public members through reflection",
290+
Justification = "HttpContent on .NET 8+ always calls the cancellable overload; reflection is the only way to exercise the .NET Framework entry point here.")]
291+
public async Task TokenlessSerializeOverrideWritesTheSameBody()
292+
{
293+
using var content = new JsonLinesContent<SealedRecord>([new("1", "a"), new("2", "b")], Serializer);
294+
var tokenless = typeof(JsonLinesContent<SealedRecord>).GetMethod(
295+
"SerializeToStreamAsync",
296+
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic,
297+
[typeof(Stream), typeof(System.Net.TransportContext)])!;
298+
299+
await using var direct = new MemoryStream();
300+
await (Task)tokenless.Invoke(content, [direct, null])!;
301+
await using var sent = new MemoryStream();
302+
await content.CopyToAsync(sent);
303+
304+
await Assert.That(direct.ToArray()).IsEquivalentTo(sent.ToArray());
236305
}
237306
#endif
238307

@@ -397,10 +466,10 @@ private static async IAsyncEnumerable<SealedRecord> CancellingAsync(
397466
{
398467
try
399468
{
400-
yield return new("1", "first");
469+
yield return new("1", FirstElementName);
401470
await cts.CancelAsync();
402471
cancellationToken.ThrowIfCancellationRequested();
403-
yield return new("2", "second");
472+
yield return new("2", SecondElementName);
404473
}
405474
finally
406475
{
@@ -420,6 +489,26 @@ private static async IAsyncEnumerable<SealedRecord> CaptureTokenAsync(
420489
await Task.CompletedTask;
421490
yield return new("1", "a");
422491
}
492+
493+
/// <summary>Produces two elements, awaiting a gate between them, and records enumerator disposal.</summary>
494+
/// <param name="gate">Completed to release the second element.</param>
495+
/// <param name="tracker">Records whether the enumerator was disposed.</param>
496+
/// <param name="stream">Armed once the first element has been written, just before waiting on the gate.</param>
497+
/// <returns>The asynchronous sequence.</returns>
498+
private static async IAsyncEnumerable<SealedRecord> GatedTrackedAsync(TaskCompletionSource gate, DisposeTracker tracker, FlushThrowingStream stream)
499+
{
500+
try
501+
{
502+
yield return new("1", FirstElementName);
503+
stream.Armed = true;
504+
await gate.Task;
505+
yield return new("2", SecondElementName);
506+
}
507+
finally
508+
{
509+
tracker.Disposed = true;
510+
}
511+
}
423512
#endif
424513

425514
/// <summary>A non-sealed reference-type element, not eligible for the typed JSON Lines path.</summary>
@@ -504,6 +593,30 @@ public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, Cancella
504593
_writes++;
505594
}
506595
}
596+
597+
/// <summary>A stream whose flush fails once armed, recording that it was invoked before throwing.</summary>
598+
/// <param name="flushInvoked">Completed the moment an armed <see cref="FlushAsync"/> is invoked, before it throws.</param>
599+
/// <remarks>
600+
/// It is armed only when the producer reaches its gate: on .NET 11 the JSON serializer also flushes the
601+
/// destination after writing each element, and that flush must not be the one that fails.
602+
/// </remarks>
603+
private sealed class FlushThrowingStream(TaskCompletionSource flushInvoked) : MemoryStream
604+
{
605+
/// <summary>Gets or sets a value indicating whether the next flush fails.</summary>
606+
internal bool Armed { get; set; }
607+
608+
/// <inheritdoc/>
609+
public override Task FlushAsync(CancellationToken cancellationToken)
610+
{
611+
if (!Armed)
612+
{
613+
return base.FlushAsync(cancellationToken);
614+
}
615+
616+
_ = flushInvoked.TrySetResult();
617+
throw new IOException("Flush failed.");
618+
}
619+
}
507620
#endif
508621

509622
/// <summary>A sealed reference-type element, eligible for the typed JSON Lines path.</summary>

‎src/tests/Refit.Tests/RequestBuilderTests.cs‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,24 @@ static async IAsyncEnumerable<JsonLineRecord> ProduceAsync()
346346
}
347347
}
348348

349+
/// <summary>Verifies a class implementing <see cref="IAsyncEnumerable{T}"/> (rather than being that interface
350+
/// itself) is recognized as an asynchronous JSON Lines body through its declared interfaces.</summary>
351+
/// <returns>A task that represents the asynchronous operation.</returns>
352+
[Test]
353+
public async Task FindAsyncJsonLinesElementTypeFindsTheElementTypeOfAnImplementingClass() =>
354+
await Assert
355+
.That(RequestBuilderImplementation.FindAsyncJsonLinesElementType(typeof(AsyncEnumerableClassBody)))
356+
.IsEqualTo(typeof(JsonLineRecord));
357+
358+
/// <summary>Verifies a type implementing two distinct <see cref="IAsyncEnumerable{T}"/> interfaces is ambiguous
359+
/// and is not treated as an asynchronous JSON Lines body.</summary>
360+
/// <returns>A task that represents the asynchronous operation.</returns>
361+
[Test]
362+
public async Task FindAsyncJsonLinesElementTypeReturnsNullForAnAmbiguousImplementer() =>
363+
await Assert
364+
.That(RequestBuilderImplementation.FindAsyncJsonLinesElementType(typeof(AmbiguousAsyncEnumerableBody)))
365+
.IsNull();
366+
349367
/// <summary>A stream response is wrapped in an ApiResponse.</summary>
350368
/// <returns>A task that represents the asynchronous operation.</returns>
351369
[Test]
@@ -545,4 +563,36 @@ public async Task MethodsThatDontHaveAnHttpMethodShouldFail()
545563
await Assert.That(shouldDie).IsFalse();
546564
}
547565
}
566+
567+
/// <summary>A class implementing <see cref="IAsyncEnumerable{T}"/> alongside an unrelated interface, used to
568+
/// exercise the branch of <see cref="RequestBuilderImplementation.FindAsyncJsonLinesElementType"/> that finds the
569+
/// element type through <see cref="Type.GetInterfaces"/> rather than the declared type itself.</summary>
570+
private sealed class AsyncEnumerableClassBody : IAsyncEnumerable<JsonLineRecord>, IDisposable
571+
{
572+
/// <inheritdoc/>
573+
public void Dispose()
574+
{
575+
}
576+
577+
/// <inheritdoc/>
578+
public async IAsyncEnumerator<JsonLineRecord> GetAsyncEnumerator(CancellationToken cancellationToken = default)
579+
{
580+
await Task.Yield();
581+
yield return new JsonLineRecord { Id = "1", Name = "a" };
582+
}
583+
}
584+
585+
/// <summary>A type implementing two distinct closed <see cref="IAsyncEnumerable{T}"/> interfaces, used to
586+
/// exercise the ambiguous-implementer branch of
587+
/// <see cref="RequestBuilderImplementation.FindAsyncJsonLinesElementType"/>.</summary>
588+
private sealed class AmbiguousAsyncEnumerableBody : IAsyncEnumerable<JsonLineRecord>, IAsyncEnumerable<string>
589+
{
590+
/// <inheritdoc/>
591+
IAsyncEnumerator<JsonLineRecord> IAsyncEnumerable<JsonLineRecord>.GetAsyncEnumerator(CancellationToken cancellationToken) =>
592+
throw new NotSupportedException("Not used: this type only exercises the ambiguous-implementer branch of FindAsyncJsonLinesElementType.");
593+
594+
/// <inheritdoc/>
595+
IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(CancellationToken cancellationToken) =>
596+
throw new NotSupportedException("Not used: this type only exercises the ambiguous-implementer branch of FindAsyncJsonLinesElementType.");
597+
}
548598
}

0 commit comments

Comments
 (0)
⌂ 换网址