#region ========================================================================= USING ===================================================================================== using Nemera.Presentation.Web.Common.Http; using Nemera.Presentation.Web.Common.Middlewares; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading.Tasks; #endregion namespace Nemera.Presentation.Web.UnitTests.Common.Middlewares; /// /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] public class CacheControlHeaderMiddlewareTests { [Fact] public async Task InvokeAsync_WhenTheEndpointStoredACacheControlValue_ShouldRestoreItAfterLaterCallbacksRun() { // Arrange DefaultHttpContext context = new(); TestHttpResponseFeature responseFeature = new(); context.Features.Set(responseFeature); context.Items[HttpContextItemKeys.CACHE_CONTROL] = "private, no-store"; CacheControlHeaderMiddleware sut = new(nextContext => { // The session middleware registers its cache header write after this middleware, so it runs first when the response starts. nextContext.Response.OnStarting(() => { nextContext.Response.Headers.CacheControl = "no-cache,no-store"; return Task.CompletedTask; }); return Task.CompletedTask; }); // Act await sut.InvokeAsync(context); await responseFeature.StartAsync(); // Assert Assert.Equal("private, no-store", context.Response.Headers.CacheControl.ToString()); } [Fact] public async Task InvokeAsync_WhenNoCacheControlValueWasStored_ShouldLeaveTheHeaderWrittenByLaterCallbacks() { // Arrange DefaultHttpContext context = new(); TestHttpResponseFeature responseFeature = new(); context.Features.Set(responseFeature); CacheControlHeaderMiddleware sut = new(nextContext => { nextContext.Response.OnStarting(() => { nextContext.Response.Headers.CacheControl = "no-cache,no-store"; return Task.CompletedTask; }); return Task.CompletedTask; }); // Act await sut.InvokeAsync(context); await responseFeature.StartAsync(); // Assert Assert.Equal("no-cache,no-store", context.Response.Headers.CacheControl.ToString()); } [Fact] public async Task InvokeAsync_WhenTheStoredValueIsEmpty_ShouldLeaveTheHeaderWrittenByLaterCallbacks() { // Arrange DefaultHttpContext context = new(); TestHttpResponseFeature responseFeature = new(); context.Features.Set(responseFeature); context.Items[HttpContextItemKeys.CACHE_CONTROL] = string.Empty; CacheControlHeaderMiddleware sut = new(nextContext => { nextContext.Response.OnStarting(() => { nextContext.Response.Headers.CacheControl = "no-cache,no-store"; return Task.CompletedTask; }); return Task.CompletedTask; }); // Act await sut.InvokeAsync(context); await responseFeature.StartAsync(); // Assert Assert.Equal("no-cache,no-store", context.Response.Headers.CacheControl.ToString()); } /// /// Minimal response feature that stores the response-start callbacks and invokes them in reverse registration order, like the server does. /// [ExcludeFromCodeCoverage] private sealed class TestHttpResponseFeature : IHttpResponseFeature { private readonly List<(Func Callback, object State)> _onStartingCallbacks = []; /// /// Gets or sets the status code of the response. /// public int StatusCode { get; set; } = StatusCodes.Status200OK; /// /// Gets or sets the reason phrase of the response. /// public string? ReasonPhrase { get; set; } /// /// Gets or sets the headers of the response. /// public IHeaderDictionary Headers { get; set; } = new HeaderDictionary(); /// /// Gets or sets the body of the response. /// public Stream Body { get; set; } = new MemoryStream(); /// /// Gets a value indicating whether the response has started. /// public bool HasStarted { get; private set; } /// /// Registers a callback to invoke when the response starts. /// /// The callback to invoke. /// The state passed to the callback. public void OnStarting(Func callback, object state) { _onStartingCallbacks.Add((callback, state)); } /// /// Registers a callback to invoke when the response completes. /// /// The callback to invoke. /// The state passed to the callback. public void OnCompleted(Func callback, object state) { } /// /// Starts the response and invokes the registered callbacks in reverse registration order. /// /// A task representing the asynchronous operation. public async Task StartAsync() { if (HasStarted) return; HasStarted = true; for (int index = _onStartingCallbacks.Count - 1; index >= 0; index--) await _onStartingCallbacks[index].Callback(_onStartingCallbacks[index].State); } } }