Files
Heimdall/tests/Heimdall.Web.Tests/Services/TokenRefreshHandlerTests.cs
T

100 lines
3.2 KiB
C#

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Heimdall.Web.Services;
using Microsoft.Extensions.Configuration;
using NSubstitute;
namespace Heimdall.Web.Tests.Services;
public sealed class TokenRefreshHandlerTests : IDisposable
{
private readonly MockInnerHandler _innerHandler;
private readonly HttpClient _httpClient;
private readonly AuthState _authState;
private readonly TokenRefreshHandler _handler;
public TokenRefreshHandlerTests()
{
_innerHandler = new MockInnerHandler();
_authState = new AuthState();
var authStateProvider = Substitute.For<HeimdallAuthStateProvider>(null!, _authState);
var config = Substitute.For<IConfiguration>();
config.GetValue<string>("ApiBaseUrl").Returns("http://localhost:8080");
_handler = new TokenRefreshHandler(_authState, authStateProvider, config);
var pipeline = _innerHandler.CreatePipeline(_handler);
_httpClient = new HttpClient(pipeline) { BaseAddress = new Uri("http://localhost:8080/") };
}
public void Dispose() => _httpClient.Dispose();
[Fact]
public async Task SendAsync_Non401Response_PassesThrough()
{
_innerHandler.QueueResponse(HttpStatusCode.OK);
var response = await _httpClient.GetAsync("api/sites");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task SendAsync_401WithoutRefreshToken_DoesNotRetry()
{
_innerHandler.QueueResponse(HttpStatusCode.Unauthorized);
var response = await _httpClient.GetAsync("api/sites");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal(1, _innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_AuthEndpoint_DoesNotIntercept()
{
_innerHandler.QueueResponse(HttpStatusCode.Unauthorized);
var response = await _httpClient.PostAsync("api/auth/login", null);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal(1, _innerHandler.CallCount);
}
}
public class MockInnerHandler : HttpMessageHandler
{
private readonly Queue<HttpResponseMessage> _responses = new();
public int CallCount { get; private set; }
public List<HttpRequestMessage> Requests { get; } = [];
public void QueueResponse(HttpStatusCode status, object? body = null)
{
var response = new HttpResponseMessage(status);
if (body is not null)
response.Content = JsonContent.Create(body, options: new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
_responses.Enqueue(response);
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
CallCount++;
Requests.Add(request);
var response = _responses.Count > 0 ? _responses.Dequeue() : new HttpResponseMessage(HttpStatusCode.OK);
return Task.FromResult(response);
}
public HttpMessageHandler CreatePipeline(DelegatingHandler handler)
{
handler.InnerHandler = this;
return handler;
}
}