using System.Net;
using System.Net.Sockets;
using AIStudio.Provider;
namespace AIStudio.Tests.Provider;
///
/// Checks which failures of a request count as a failed connection, before the provider answered.
///
///
/// A transcription which fails that way says so, instead of claiming that the provider could not transcribe the file.
/// The exceptions come from a real HttpClient and a real socket, since only they show how .NET reports a connection
/// which breaks off while the media file is on its way.
///
[TestFixture]
public sealed class ConnectionFailureTests
{
private static readonly TimeSpan TIME_LIMIT = TimeSpan.FromSeconds(10);
private static readonly HttpClient HTTP_CLIENT = new();
[Test]
public async Task AConnectionWhichBreaksOffDuringTheUploadCounts()
{
using var timeout = new CancellationTokenSource(TIME_LIMIT);
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
try
{
var server = ResetFirstConnectionAsync(listener, timeout.Token);
var failure = await SendMediaFileAsync(AddressOf(listener), timeout.Token);
await server;
Assert.That(BaseProvider.IsConnectionFailure(failure), Is.True, failure.ToString());
}
finally
{
listener.Stop();
}
}
[Test]
public async Task AServerWhichCannotBeReachedCounts()
{
using var timeout = new CancellationTokenSource(TIME_LIMIT);
// A port which was free a moment ago and has no listener anymore:
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var address = AddressOf(listener);
listener.Stop();
var failure = await SendMediaFileAsync(address, timeout.Token);
Assert.That(BaseProvider.IsConnectionFailure(failure), Is.True, failure.ToString());
}
[Test]
public void AnAnswerOfTheProviderDoesNotCount()
{
var failure = new HttpRequestException("Response status code does not indicate success: 500 (Internal Server Error).", null, HttpStatusCode.InternalServerError);
Assert.That(BaseProvider.IsConnectionFailure(failure), Is.False);
}
[Test]
public void ATimeoutDoesNotCount()
{
var failure = new TaskCanceledException("The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.", new TimeoutException());
Assert.That(BaseProvider.IsConnectionFailure(failure), Is.False);
}
private static Uri AddressOf(TcpListener listener) => new($"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/audio/transcriptions");
///
/// Accepts one connection, reads the beginning of the request, and closes the connection with a reset, as a
/// provider does which drops an upload.
///
private static async Task ResetFirstConnectionAsync(TcpListener listener, CancellationToken token)
{
using var client = await listener.AcceptTcpClientAsync(token);
var buffer = new byte[16 * 1_024];
_ = await client.GetStream().ReadAsync(buffer, token);
client.Client.LingerState = new LingerOption(true, 0);
client.Close();
}
///
/// Uploads a media file of several MB, as a transcription request does, and returns what the request threw.
///
private static async Task SendMediaFileAsync(Uri address, CancellationToken token)
{
using var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(new byte[8 * 1_024 * 1_024]), "file", "recording.webm");
form.Add(new StringContent("whisper-1"), "model");
try
{
using var response = await HTTP_CLIENT.PostAsync(address, form, token);
}
catch (Exception exception) when (exception is not OperationCanceledException || !token.IsCancellationRequested)
{
return exception;
}
throw new AssertionException("The request did not fail.");
}
}