#region ========================================================================= USING ===================================================================================== using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net.Http; using System.Threading; using System.Threading.Tasks; #endregion namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; /// /// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent. /// [ExcludeFromCodeCoverage] internal sealed class StubHttpMessageHandler : HttpMessageHandler { private readonly Func _responseFactory; private int _callCount; /// /// Gets the requests that were sent through the handler. /// public List Requests { get; } = []; /// /// Gets the number of requests that were sent through the handler. /// public int CallCount => _callCount; /// /// Initializes a new instance of the class. /// /// The factory that produces the response of a request, given the request and its one based call index. public StubHttpMessageHandler(Func responseFactory) { _responseFactory = responseFactory; } /// /// Sends the provided request, producing its response through the configured factory. /// /// The request to send. /// Cancellation token that can be used to stop the execution. /// The response produced for the request. protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { int callIndex = Interlocked.Increment(ref _callCount); Requests.Add(request); try { return Task.FromResult(_responseFactory(request, callIndex)); } catch (Exception exception) { // A response factory may throw to simulate a transport failure, which is surfaced as a faulted task. return Task.FromException(exception); } } }