#region ========================================================================= USING ===================================================================================== using Nemera.Presentation.Web.Common.Api; using Nemera.Presentation.Web.Fixtures.Common.Api; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics.CodeAnalysis; #endregion namespace Nemera.Presentation.Web.SecurityTests.Common.Setup; /// /// Factory for creating the Web application for security tests, with the remote API client replaced by a configurable stub. /// [ExcludeFromCodeCoverage] public class NemeraWebFactory : WebApplicationFactory, IDisposable { private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; /// /// Gets the stub used in place of the remote API client. /// public StubApiHttpClient ApiClientStub { get; } = new(); /// /// Gets the stub used in place of the remote streaming API client. /// public StubStreamingApiHttpClient StreamingApiClientStub { get; } = new(); /// /// Initializes a new instance of the class. /// public NemeraWebFactory() { } /// /// Configures the web host for the security tests. /// /// The web host builder to configure. protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureAppConfiguration((context, config) => { // Provide the application configuration values that the Web app validates on startup. config.AddInMemoryCollection(initialData: new Dictionary { ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY, ["ServerConfiguration:ApiVersion"] = "1", ["ServerConfiguration:BaseAddress"] = "http://localhost", ["ServerConfiguration:Port"] = "5214" }); }); builder.ConfigureServices(services => { // Remove the typed HTTP client registration, so that the stub can take its place. ServiceDescriptor[] apiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IApiHttpClient))]; foreach (ServiceDescriptor descriptor in apiClientDescriptors) services.Remove(descriptor); services.AddSingleton(ApiClientStub); // Remove the typed streaming HTTP client registration, so that the streaming stub can take its place. ServiceDescriptor[] streamingApiClientDescriptors = [.. services.Where(serviceDescriptor => serviceDescriptor.ServiceType == typeof(IStreamingApiHttpClient))]; foreach (ServiceDescriptor descriptor in streamingApiClientDescriptors) services.Remove(descriptor); services.AddSingleton(StreamingApiClientStub); }); } }