From 6ac0dea029ac8ad143ff246ffd962cbff77b4e74 Mon Sep 17 00:00:00 2001 From: Rob Earlam Date: Fri, 12 Sep 2025 15:05:26 +1000 Subject: [PATCH 01/41] Refactored TestWebApplicationFactory usage, updated Pages Fixtures, updated one binding fixture usage --- .../Binding/ComplexModelBindingFixture.cs | 71 +++++++++---------- .../Fixtures/Pages/PagesEditingFixture.cs | 61 ++++++++++++++-- .../Pages/PagesSetupRoutingFixture.cs | 67 ++++++++++++++--- .../Fixtures/Pages/TestPagesProgram.cs | 44 ------------ .../TestWebApplicationProgram.cs | 22 ++++++ 5 files changed, 168 insertions(+), 97 deletions(-) delete mode 100644 tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/TestPagesProgram.cs create mode 100644 tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/TestWebApplicationProgram.cs diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs index f60c81a..10bb390 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs @@ -1,6 +1,7 @@ using System.Net; using FluentAssertions; using HtmlAgilityPack; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -10,43 +11,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class ComplexModelBindingFixture : IDisposable +public class ComplexModelBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public ComplexModelBindingFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Complex-Component", StringComparison.OrdinalIgnoreCase), "ComplexComponent") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task SitecoreLayoutModelBinders_BindDataCorrectly() { @@ -57,7 +26,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -103,8 +72,38 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildBindingWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Complex-Component", StringComparison.OrdinalIgnoreCase), "ComplexComponent") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesEditingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesEditingFixture.cs index 0878a8a..24da5f1 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesEditingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesEditingFixture.cs @@ -1,26 +1,30 @@ using System.Net; using FluentAssertions; using GraphQL; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using NSubstitute; using Sitecore.AspNetCore.SDK.GraphQL.Request; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; +using Sitecore.AspNetCore.SDK.Pages.Configuration; +using Sitecore.AspNetCore.SDK.Pages.Extensions; +using Sitecore.AspNetCore.SDK.Pages.Middleware; using Sitecore.AspNetCore.SDK.Pages.Request.Handlers.GraphQL; +using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; using Sitecore.AspNetCore.SDK.TestData; using Xunit; namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Pages; -public class PagesEditingFixture(TestWebApplicationFactory factory) : IClassFixture> +public class PagesEditingFixture(TestWebApplicationFactory factory) : IClassFixture> { - private readonly TestWebApplicationFactory _factory = factory; - [Fact] public async Task EditingRequest_ValidRequest_ReturnsChromeDecoratedResponse() { // Arrange - _factory.MockGraphQLClient.SendQueryAsync(Arg.Any()).Returns(TestConstants.SimpleEditingLayoutQueryResponse); - _factory.MockGraphQLClient.SendQueryAsync(Arg.Any()).Returns(TestConstants.DictionaryResponseWithoutPaging); - - HttpClient client = _factory.CreateClient(); + factory.MockGraphQLClient.SendQueryAsync(Arg.Any()).Returns(TestConstants.SimpleEditingLayoutQueryResponse); + factory.MockGraphQLClient.SendQueryAsync(Arg.Any()).Returns(TestConstants.DictionaryResponseWithoutPaging); + HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); string url = $"/Pages/index?mode=edit&secret={TestConstants.JssEditingSecret}&sc_itemid={TestConstants.TestItemId}&sc_version=1&sc_layoutKind=final"; // Act @@ -34,4 +38,47 @@ public async Task EditingRequest_ValidRequest_ReturnsChromeDecoratedResponse() responseBody.Should().Contain(""); responseBody.Should().Contain(""); } + + private WebApplicationFactory BuildPagesWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddSitecoreLayoutService() + .AddSitecorePagesHandler() + .AddGraphQLWithContextHandler("default", TestConstants.ContextId, siteName: TestConstants.SiteName) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultPartialView("_ComponentNotFound"); + }) + .WithSitecorePages(TestConstants.ContextId, options => { options.EditingSecret = TestConstants.JssEditingSecret; }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseMiddleware(); + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Pages}/{action=Index}"); + + endpoints.MapControllerRoute( + "pages-config", + TestConstants.ConfigRoute, + new { controller = "PagesSetup", action = "Config" }); + + endpoints.MapControllerRoute( + "pages-render", + TestConstants.RenderRoute, + new { controller = "PagesSetup", action = "Render" }); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs index 72c3691..d7327c1 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs @@ -1,19 +1,23 @@ using System.Net; using FluentAssertions; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; +using Sitecore.AspNetCore.SDK.Pages.Extensions; +using Sitecore.AspNetCore.SDK.Pages.Middleware; +using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; using Sitecore.AspNetCore.SDK.TestData; using Xunit; namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Pages; -public class PagesSetupRoutingFixture(TestWebApplicationFactory factory) : IClassFixture> +public class PagesSetupRoutingFixture(TestWebApplicationFactory factory) : IClassFixture> { - private readonly TestWebApplicationFactory _factory = factory; - [Fact] public async Task ConfigRoute_MissingSecret_ReturnsBadRequest() { // Arrange - HttpClient client = _factory.CreateClient(); + HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); string url = $"{TestConstants.ConfigRoute}?secret="; // Act @@ -28,7 +32,7 @@ public async Task ConfigRoute_MissingSecret_ReturnsBadRequest() public async Task ConfigRoute_InvalidSecret_ReturnsBadRequest() { // Arrange - HttpClient client = _factory.CreateClient(); + HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); string url = $"{TestConstants.ConfigRoute}?secret=invalid_secret_value"; // Act @@ -43,7 +47,7 @@ public async Task ConfigRoute_InvalidSecret_ReturnsBadRequest() public async Task ConfigRoute_InvalidRequestOrigin_ReturnsBadRequest() { // Arrange - HttpClient client = _factory.CreateClient(); + HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); string url = $"{TestConstants.ConfigRoute}?secret={TestConstants.JssEditingSecret}"; client.DefaultRequestHeaders.Add("Origin", "http://invalid_origin_domain.com"); @@ -59,7 +63,7 @@ public async Task ConfigRoute_InvalidRequestOrigin_ReturnsBadRequest() public async Task ConfigRoute_ValidCall_ReturnsCorrectObject() { // Arrange - HttpClient client = _factory.CreateClient(); + HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); string url = $"{TestConstants.ConfigRoute}?secret={TestConstants.JssEditingSecret}"; client.DefaultRequestHeaders.Add("Origin", "https://pages.sitecorecloud.io"); @@ -80,7 +84,7 @@ public async Task ConfigRoute_ValidCall_ReturnsCorrectObject() public async Task RenderRoute_MissingSecret_ReturnsBadRequest() { // Arrange - HttpClient client = _factory.CreateClient(); + HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); string url = $"{TestConstants.RenderRoute}?secret="; // Act @@ -95,7 +99,7 @@ public async Task RenderRoute_MissingSecret_ReturnsBadRequest() public async Task RenderRoute_InvalidSecret_ReturnsBadRequest() { // Arrange - HttpClient client = _factory.CreateClient(); + HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); string url = $"{TestConstants.RenderRoute}?secret=invalid_secret_value"; // Act @@ -110,7 +114,7 @@ public async Task RenderRoute_InvalidSecret_ReturnsBadRequest() public async Task RenderRoute_ValidCall_ReturnsCorrectResponse() { // Arrange - HttpClient client = _factory.CreateClient(); + HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); Guid itemId = Guid.NewGuid(); string language = "en"; string layoutKind = "final"; @@ -128,4 +132,47 @@ public async Task RenderRoute_ValidCall_ReturnsCorrectResponse() response.Should().NotBeNull(); response.StatusCode.Should().Be(HttpStatusCode.Redirect); } + + private WebApplicationFactory BuildPagesWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddSitecoreLayoutService() + .AddSitecorePagesHandler() + .AddGraphQLWithContextHandler("default", TestConstants.ContextId, siteName: TestConstants.SiteName) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultPartialView("_ComponentNotFound"); + }) + .WithSitecorePages(TestConstants.ContextId, options => { options.EditingSecret = TestConstants.JssEditingSecret; }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseMiddleware(); + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Pages}/{action=Index}"); + + endpoints.MapControllerRoute( + "pages-config", + TestConstants.ConfigRoute, + new { controller = "PagesSetup", action = "Config" }); + + endpoints.MapControllerRoute( + "pages-render", + TestConstants.RenderRoute, + new { controller = "PagesSetup", action = "Render" }); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/TestPagesProgram.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/TestPagesProgram.cs deleted file mode 100644 index 7b65ba8..0000000 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/TestPagesProgram.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Sitecore.AspNetCore.SDK.GraphQL.Extensions; -using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; -using Sitecore.AspNetCore.SDK.Pages.Configuration; -using Sitecore.AspNetCore.SDK.Pages.Extensions; -using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; -using Sitecore.AspNetCore.SDK.TestData; - -WebApplicationBuilder builder = WebApplication.CreateBuilder(args); - -builder.Services.AddRouting() - .AddMvc(); - -builder.Services.AddGraphQLClient(configuration => -{ - configuration.ContextId = TestConstants.ContextId; -}); - -builder.Services.AddSitecoreLayoutService() - .AddSitecorePagesHandler() - .AddGraphQLWithContextHandler("default", TestConstants.ContextId!, siteName: TestConstants.SiteName!) - .AsDefaultHandler(); - -builder.Services.AddSitecoreRenderingEngine(options => - { - options.AddDefaultPartialView("_ComponentNotFound"); - }) - .WithSitecorePages(TestConstants.ContextId, options => { options.EditingSecret = TestConstants.JssEditingSecret; }); - -WebApplication app = builder.Build(); -app.UseSitecorePages(new PagesOptions { ConfigEndpoint = TestConstants.ConfigRoute }); -app.UseRouting(); - -app.MapControllerRoute( - name: "default", - pattern: "{controller=Pages}/{action=Index}"); - -app.Run(); - -/// -/// Partial class allowing this TestProgram to be created by a WebApplicationFactory for integration testing. -/// -public partial class TestPagesProgram -{ -} \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/TestWebApplicationProgram.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/TestWebApplicationProgram.cs new file mode 100644 index 0000000..ee04bae --- /dev/null +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/TestWebApplicationProgram.cs @@ -0,0 +1,22 @@ +using Sitecore.AspNetCore.SDK.GraphQL.Extensions; +using Sitecore.AspNetCore.SDK.TestData; + +WebApplicationBuilder builder = WebApplication.CreateBuilder(args); + +builder.Services.AddRouting() + .AddMvc(); + +builder.Services.AddGraphQLClient(configuration => +{ + configuration.ContextId = TestConstants.ContextId; +}); + +WebApplication app = builder.Build(); +app.Run(); + +/// +/// Partial class allowing this TestProgram to be created by a WebApplicationFactory for integration testing. +/// +public partial class TestWebApplicationProgram +{ +} \ No newline at end of file From c5f63b76458dfb9a83b78f6dcd2adc7676576943 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Fri, 12 Sep 2025 13:04:32 +0530 Subject: [PATCH 02/41] Migrate ModelBindingFixture.cs --- .../Fixtures/Binding/ModelBindingFixture.cs | 57 ++++++++++--------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs index 91cb431..dfe7967 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs @@ -1,5 +1,6 @@ using System.Net; using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -10,33 +11,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class ModelBindingFixture : IDisposable +public class ModelBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public ModelBindingFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(); - }) - .Configure(app => - { - app.UseSitecoreRenderingEngine(); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task SitecoreRouteModelBinding_ReturnsCorrectData() { @@ -46,7 +25,7 @@ public async Task SitecoreRouteModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreRoute"); // assert that the SitecoreRouteProperty attribute binding worked @@ -68,7 +47,7 @@ public async Task SitecoreContextModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreContext"); // assert that the SitecoreContextProperty attribute binding worked @@ -88,7 +67,7 @@ public async Task SitecoreResponseModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreResponse"); // assert that the SitecoreLayoutResponse attribute binding worked @@ -97,8 +76,30 @@ public async Task SitecoreResponseModelBinding_ReturnsCorrectData() public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildBindingWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + } } \ No newline at end of file From d44de35e4f7c1701b03dfe7980ca1fba49cd3a87 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Fri, 12 Sep 2025 13:09:42 +0530 Subject: [PATCH 03/41] Migrate ModelBindingErrorHandlingFixture.cs --- .../ModelBindingErrorHandlingFixture.cs | 71 +++++++++---------- 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs index 67f70c5..14547a3 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs @@ -1,6 +1,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -10,43 +11,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class ModelBindingErrorHandlingFixture : IDisposable +public class ModelBindingErrorHandlingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public ModelBindingErrorHandlingFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Component-With-Missing-Data", StringComparison.OrdinalIgnoreCase), "ComponentWithMissingData") - .AddModelBoundView(name => name.Equals("Component-Without-Id", StringComparison.OrdinalIgnoreCase), "ComponentWithoutId"); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task SitecoreLayoutModelBinders_HandleMissingDataCorrectly() { @@ -57,7 +26,7 @@ public async Task SitecoreLayoutModelBinders_HandleMissingDataCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithMissingData)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -92,8 +61,38 @@ public async Task SitecoreLayoutModelBinders_HandleMissingDataCorrectly() public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildBindingWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Component-With-Missing-Data", StringComparison.OrdinalIgnoreCase), "ComponentWithMissingData") + .AddModelBoundView(name => name.Equals("Component-Without-Id", StringComparison.OrdinalIgnoreCase), "ComponentWithoutId"); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file From e4890f5c78bdf3063696ba8cb76155ceac719273 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Fri, 12 Sep 2025 13:16:02 +0530 Subject: [PATCH 04/41] Migrate CustomModelContextBindingFixture.cs --- .../CustomModelContextBindingFixture.cs | 71 +++++++++---------- 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs index 41c55e1..f6a6b30 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs @@ -2,6 +2,7 @@ using System.Text.Json.Nodes; using AwesomeAssertions; using HtmlAgilityPack; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -12,43 +13,11 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class CustomModelContextBindingFixture : IDisposable +public class CustomModelContextBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public CustomModelContextBindingFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Custom-Model-Context-Component", StringComparison.OrdinalIgnoreCase), "CustomModelContextComponent") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task SitecoreLayoutModelBinders_BindDataCorrectly() { @@ -73,7 +42,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(jObject!.ToJsonString(Serializer.GetOptions())) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -109,8 +78,38 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildBindingWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Custom-Model-Context-Component", StringComparison.OrdinalIgnoreCase), "CustomModelContextComponent") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file From 1fbb5a0a2b3f2c33fdb9dabc290604314b8072f3 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Fri, 12 Sep 2025 13:27:55 +0530 Subject: [PATCH 05/41] Migrate CustomResolverBindingFixture.cs --- .../Binding/CustomResolverBindingFixture.cs | 73 +++++++++---------- .../Fixtures/Binding/ModelBindingFixture.cs | 6 +- 2 files changed, 39 insertions(+), 40 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs index 84961d2..89c1f82 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs @@ -1,6 +1,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -11,44 +12,11 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class CustomResolverBindingFixture : IDisposable +public class CustomResolverBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public CustomResolverBindingFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("PartialDesignDynamicPlaceholder") - .AddModelBoundView(name => name.Equals("Navigation", StringComparison.OrdinalIgnoreCase), "CustomResolver") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task SitecoreLayoutModelBinders_BindDataCorrectly() { @@ -60,7 +28,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(json) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -80,8 +48,39 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildBindingWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("PartialDesignDynamicPlaceholder") + .AddModelBoundView(name => name.Equals("Navigation", StringComparison.OrdinalIgnoreCase), "CustomResolver") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs index dfe7967..a1be91d 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs @@ -25,7 +25,7 @@ public async Task SitecoreRouteModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreRoute"); // assert that the SitecoreRouteProperty attribute binding worked @@ -47,7 +47,7 @@ public async Task SitecoreContextModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreContext"); // assert that the SitecoreContextProperty attribute binding worked @@ -67,7 +67,7 @@ public async Task SitecoreResponseModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreResponse"); // assert that the SitecoreLayoutResponse attribute binding worked From 74fbf45a53e53575b912bcec567956f624400fb2 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Fri, 12 Sep 2025 13:34:49 +0530 Subject: [PATCH 06/41] Migrate ViewFieldsBindingFixture.cs --- .../Binding/ViewFieldsBindingFixture.cs | 71 +++++++++---------- 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs index 8912153..f66e9bd 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs @@ -1,6 +1,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -10,43 +11,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class ViewFieldsBindingFixture : IDisposable +public class ViewFieldsBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public ViewFieldsBindingFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Component-5", StringComparison.OrdinalIgnoreCase), "Component5") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task SitecoreLayoutModelBinders_BindDataCorrectly() { @@ -57,7 +26,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -83,8 +52,38 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildBindingWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Component-5", StringComparison.OrdinalIgnoreCase), "Component5") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file From 8d5674905b5e67f86584527dc19847118cc740de Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Fri, 12 Sep 2025 14:44:05 +0530 Subject: [PATCH 07/41] Migrate custom render types fixtures --- .../LoggingComponentRendererFixture.cs | 72 +++++++++--------- .../MultipleComponentsAddedFixture.cs | 73 +++++++++---------- .../PartialViewRendererFixture.cs | 72 +++++++++--------- 3 files changed, 107 insertions(+), 110 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs index 2c22dd2..9bc4a74 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs @@ -1,6 +1,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -11,44 +12,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.CustomRenderTypes; -public class LoggingComponentRendererFixture : IDisposable +public class LoggingComponentRendererFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public LoggingComponentRendererFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - - testHostBuilder - .ConfigureServices(builder => - { - builder.AddSingleton(new IntegrationTestLoggerProvider()); - - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options.AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task CustomRenderTypes_DefaultRendererWritesToLogWithoutRenderingHtml() { @@ -59,7 +27,7 @@ public async Task CustomRenderTypes_DefaultRendererWritesToLogWithoutRenderingHt Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -77,7 +45,37 @@ public async Task CustomRenderTypes_DefaultRendererWritesToLogWithoutRenderingHt public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildBindingWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddSingleton(new IntegrationTestLoggerProvider()); + + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs index 8212bfa..9e60653 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs @@ -2,6 +2,7 @@ using System.Text.Encodings.Web; using AwesomeAssertions; using HtmlAgilityPack; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -11,44 +12,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.CustomRenderTypes; -public class MultipleComponentsAddedFixture : IDisposable +public class MultipleComponentsAddedFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public MultipleComponentsAddedFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Component-3", StringComparison.OrdinalIgnoreCase), "Component3") - .AddModelBoundView(name => name.Equals("Component-6", StringComparison.OrdinalIgnoreCase), "Component6") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task CustomRenderTypes_MultipleComponentsBoundsInCorrectOrder() { @@ -59,7 +27,7 @@ public async Task CustomRenderTypes_MultipleComponentsBoundsInCorrectOrder() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -85,7 +53,38 @@ public async Task CustomRenderTypes_MultipleComponentsBoundsInCorrectOrder() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildBindingWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Component-3", StringComparison.OrdinalIgnoreCase), "Component3") + .AddModelBoundView(name => name.Equals("Component-6", StringComparison.OrdinalIgnoreCase), "Component6") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs index 02773de..be183e7 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs @@ -1,6 +1,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -10,43 +11,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.CustomRenderTypes; -public class PartialViewRendererFixture : IDisposable +public class PartialViewRendererFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public PartialViewRendererFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddPartialView(name => name.Equals("Component-6", StringComparison.OrdinalIgnoreCase), "_PartialView") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task CustomRenderTypes_PartialViewRendersCorrectly() { @@ -57,7 +26,7 @@ public async Task CustomRenderTypes_PartialViewRendersCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildPartialViewWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -74,7 +43,38 @@ public async Task CustomRenderTypes_PartialViewRendersCorrectly() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildPartialViewWebApplicationFactory() + { + return factory + .WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddPartialView(name => name.Equals("Component-6", StringComparison.OrdinalIgnoreCase), "_PartialView") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file From d3317b7ed2a3b5e039168dbbf865e68f3862ae48 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 16 Sep 2025 10:08:15 +0530 Subject: [PATCH 08/41] Apply the same file-specific rename pattern to the Binding and CustomRenderTypes Fixtures --- .../Fixtures/Binding/ComplexModelBindingFixture.cs | 4 ++-- .../Fixtures/Binding/CustomModelContextBindingFixture.cs | 4 ++-- .../Fixtures/Binding/CustomResolverBindingFixture.cs | 4 ++-- .../Fixtures/Binding/ModelBindingErrorHandlingFixture.cs | 4 ++-- .../Fixtures/Binding/ModelBindingFixture.cs | 8 ++++---- .../Fixtures/Binding/ViewFieldsBindingFixture.cs | 4 ++-- .../CustomRenderTypes/LoggingComponentRendererFixture.cs | 4 ++-- .../CustomRenderTypes/MultipleComponentsAddedFixture.cs | 4 ++-- 8 files changed, 18 insertions(+), 18 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs index e2c1033..c049f8f 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs @@ -26,7 +26,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildComplexModelBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -76,7 +76,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private WebApplicationFactory BuildBindingWebApplicationFactory() + private WebApplicationFactory BuildComplexModelBindingWebApplicationFactory() { return factory .WithWebHostBuilder(builder => diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs index f6a6b30..6f9b810 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs @@ -42,7 +42,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(jObject!.ToJsonString(Serializer.GetOptions())) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildCustomModelContextBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -82,7 +82,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private WebApplicationFactory BuildBindingWebApplicationFactory() + private WebApplicationFactory BuildCustomModelContextBindingWebApplicationFactory() { return factory .WithWebHostBuilder(builder => diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs index 89c1f82..b1e5838 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs @@ -28,7 +28,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(json) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildCustomResolverBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -52,7 +52,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private WebApplicationFactory BuildBindingWebApplicationFactory() + private WebApplicationFactory BuildCustomResolverBindingWebApplicationFactory() { return factory .WithWebHostBuilder(builder => diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs index 14547a3..d2ef243 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs @@ -26,7 +26,7 @@ public async Task SitecoreLayoutModelBinders_HandleMissingDataCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithMissingData)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildModelBindingErrorHandlingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -65,7 +65,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private WebApplicationFactory BuildBindingWebApplicationFactory() + private WebApplicationFactory BuildModelBindingErrorHandlingWebApplicationFactory() { return factory .WithWebHostBuilder(builder => diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs index a1be91d..c628759 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs @@ -25,7 +25,7 @@ public async Task SitecoreRouteModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildModelBindingWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreRoute"); // assert that the SitecoreRouteProperty attribute binding worked @@ -47,7 +47,7 @@ public async Task SitecoreContextModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildModelBindingWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreContext"); // assert that the SitecoreContextProperty attribute binding worked @@ -67,7 +67,7 @@ public async Task SitecoreResponseModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildModelBindingWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreResponse"); // assert that the SitecoreLayoutResponse attribute binding worked @@ -80,7 +80,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private WebApplicationFactory BuildBindingWebApplicationFactory() + private WebApplicationFactory BuildModelBindingWebApplicationFactory() { return factory .WithWebHostBuilder(builder => diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs index f66e9bd..396d53f 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs @@ -26,7 +26,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildViewFieldsBindingWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -56,7 +56,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private WebApplicationFactory BuildBindingWebApplicationFactory() + private WebApplicationFactory BuildViewFieldsBindingWebApplicationFactory() { return factory .WithWebHostBuilder(builder => diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs index 9bc4a74..15ce5fd 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs @@ -27,7 +27,7 @@ public async Task CustomRenderTypes_DefaultRendererWritesToLogWithoutRenderingHt Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildLoggingComponentRendererWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -48,7 +48,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private WebApplicationFactory BuildBindingWebApplicationFactory() + private WebApplicationFactory BuildLoggingComponentRendererWebApplicationFactory() { return factory .WithWebHostBuilder(builder => diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs index 9e60653..3aab1a0 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs @@ -27,7 +27,7 @@ public async Task CustomRenderTypes_MultipleComponentsBoundsInCorrectOrder() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildBindingWebApplicationFactory().CreateClient(); + HttpClient client = BuildMultipleComponentsAddedWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -56,7 +56,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private WebApplicationFactory BuildBindingWebApplicationFactory() + private WebApplicationFactory BuildMultipleComponentsAddedWebApplicationFactory() { return factory .WithWebHostBuilder(builder => From a7443f4747b5ea7d1336f4c1a0356def96fa14c6 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 16 Sep 2025 13:11:48 +0530 Subject: [PATCH 09/41] migrate ForwardHeadersToLayoutServiceFixture --- .../ForwardHeadersToLayoutServiceFixture.cs | 125 +++++++++--------- 1 file changed, 60 insertions(+), 65 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs index 924db9c..f8de6d8 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs @@ -1,7 +1,7 @@ using System.Net; using AwesomeAssertions; using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -11,67 +11,12 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.ForwardHeaders; -public class ForwardHeadersToLayoutServiceFixture : IDisposable +public class ForwardHeadersToLayoutServiceFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { private const string TestHeaderRhResponse = "testHeaderResponseFromRenderingHost"; - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public ForwardHeadersToLayoutServiceFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - - _ = testHostBuilder - .ConfigureServices(builder => - { - builder.Configure(options => - { - options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | - ForwardedHeaders.XForwardedProto; - }); - - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) - { - BaseAddress = _layoutServiceUri - }) - .AsDefaultHandler(); - - builder.AddSitecoreRenderingEngine(options => - { - options - .AddDefaultComponentRenderer(); - }).ForwardHeaders(options => - { - options.HeadersWhitelist.Add("HEADERTOCOPY"); - options.HeadersWhitelist.Add("Cookie"); - options.RequestHeadersFilters.Add( - (_, result) => - { - result.AppendValue("testNonWhitelistedHeader", "testNonWhitelistedHeaderValue"); - result.AppendValue("headerToModify", "newModifiedHeaderValue"); - result.AppendValue("cookie", "NewAddedCookie=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax"); - }); - - options.ResponseHeadersFilters.Add( - (_, result) => - { - result.AppendValue(TestHeaderRhResponse, "testHeaderResponseValueFromRenderingHost"); - }); - }); - }) - .Configure(app => - { - app.UseForwardedHeaders(); - app.UseSitecoreRenderingEngine(); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task SitecoreLayoutServiceRequest_FiltersHeaders() { @@ -82,7 +27,7 @@ public async Task SitecoreLayoutServiceRequest_FiltersHeaders() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)), }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); HttpRequestMessage request = BrowserWhitelistedHeaders(); request.Headers.Add("connection", string.Empty); request.Headers.Add("keep-alive", "sometestvalueshere"); @@ -118,7 +63,7 @@ public async Task SitecoreLayoutServiceRequest_FiltersHeaders_CaseSensitive() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); request.Headers.Add("COOKIE", "testValue"); @@ -140,7 +85,7 @@ public async Task SitecoreLayoutServiceRequest_FiltersHeaders_NonWhitelistedHead Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); request.Headers.Add("testNonWhitelistedHeader", "testNonWhitelistedHeaderValue"); @@ -161,7 +106,7 @@ public async Task SitecoreLayoutServiceRequest_FiltersHeadersNegativeCasesEmptyH Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); HttpRequestMessage request = BrowserWhitelistedHeaders(); request.Headers.Add("connection", string.Empty); @@ -187,7 +132,7 @@ public async Task SitecoreResponse_Headers_CopiedToResponse_AreFilteredAndModifi _mockClientHandler.Responses.Push(responseMsg); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); HttpRequestMessage request = BrowserWhitelistedHeaders(); request.Headers.Add("headerToModify", "oldHeaderValue"); request.Headers.Add("HEADERTOCOPY", "sometestvalueshere"); @@ -215,7 +160,7 @@ public async Task SitecoreResponse_Headers_CopiedToResponse_WhitelistedFilteredA _mockClientHandler.Responses.Push(responseMsg); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); HttpRequestMessage request = BrowserWhitelistedHeaders(); request.Headers.Add("Cookie", ["ASP.NET_SessionId=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax", "SC_ANALYTICS_GLOBAL_COOKIE=0f82f53555ce4304a1ee8ae99ab9f9a8|False; expires = Fri, 15 - Mar - 2030 13:15:08 GMT; path =/; HttpOnly"]); @@ -231,11 +176,61 @@ public async Task SitecoreResponse_Headers_CopiedToResponse_WhitelistedFilteredA public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + private WebApplicationFactory BuildForwardHeadersToLayoutServiceWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | + ForwardedHeaders.XForwardedProto; + }); + + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) + { + BaseAddress = _layoutServiceUri + }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultComponentRenderer(); + }).ForwardHeaders(options => + { + options.HeadersWhitelist.Add("HEADERTOCOPY"); + options.HeadersWhitelist.Add("Cookie"); + options.RequestHeadersFilters.Add( + (_, result) => + { + result.AppendValue("testNonWhitelistedHeader", "testNonWhitelistedHeaderValue"); + result.AppendValue("headerToModify", "newModifiedHeaderValue"); + result.AppendValue("cookie", "NewAddedCookie=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax"); + }); + + options.ResponseHeadersFilters.Add( + (_, result) => + { + result.AppendValue(TestHeaderRhResponse, "testHeaderResponseValueFromRenderingHost"); + }); + }); + }); + + builder.Configure(app => + { + app.UseForwardedHeaders(); + app.UseSitecoreRenderingEngine(); + }); + }); + } + private static HttpRequestMessage BrowserWhitelistedHeaders() { HttpRequestMessage request = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); From 5f953d9eb0dd37e2c0ac4eacbc3123e20031be5f Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 16 Sep 2025 13:48:25 +0530 Subject: [PATCH 10/41] Migrate Localization fixtures --- .../AdvanceLocalizationFixture.cs | 110 +++++++++--------- .../DefaultLocalizationFixture.cs | 84 +++++++------ .../Localization/LocalizationFixture.cs | 79 +++++++------ ...lizationUsingAttributeMiddlewareFixture.cs | 102 ++++++++-------- 4 files changed, 185 insertions(+), 190 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs index 5483406..e381562 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs @@ -4,7 +4,7 @@ using HtmlAgilityPack; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc.Razor; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -13,59 +13,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Localization; -public class AdvanceLocalizationFixture : IDisposable +public class AdvanceLocalizationFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public AdvanceLocalizationFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder.AddLocalization(options => options.ResourcesPath = "Resources"); - builder.AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - builder.AddSitecoreRenderingEngine(options => - { - options.AddModelBoundView("Component-4", "Component4") - .AddDefaultComponentRenderer(); - }); - builder.AddMvc() - .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); - }) - .Configure(app => - { - app.UseRouting(); - app.UseRequestLocalization(options => - { - List supportedCultures = [new("en"), new("da")]; - options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); - options.SupportedCultures = supportedCultures; - options.SupportedUICultures = supportedCultures; - options.UseSitecoreRequestLocalization(); - }); - app.UseSitecoreRenderingEngine(); - - app.UseEndpoints(endpoints => - { - // ReSharper disable once RouteTemplates.RouteParameterConstraintNotResolved - Custom constraint - endpoints.MapControllerRoute( - name: "default", - pattern: "content/{culture:culture}/{**sitecoreRoute}", - defaults: new { controller = "Home", action = "Index" }); - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() { @@ -76,7 +28,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildAdvanceLocalizationWebApplicationFactory().CreateClient(); // Act await client.GetStringAsync(new Uri("content/da/UsingGlobalMiddleware", UriKind.Relative)); @@ -94,7 +46,7 @@ public async Task LocalizedRequest_PicksDefaultView() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildAdvanceLocalizationWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -118,7 +70,7 @@ public async Task LocalizedRequest_PicksLocalizedView() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildAdvanceLocalizationWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("content/da", UriKind.Relative)); @@ -135,7 +87,55 @@ public async Task LocalizedRequest_PicksLocalizedView() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildAdvanceLocalizationWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services.AddLocalization(options => options.ResourcesPath = "Resources"); + + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddModelBoundView("Component-4", "Component4") + .AddDefaultComponentRenderer(); + }); + + services.AddMvc() + .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseRequestLocalization(options => + { + List supportedCultures = new() { new("en"), new("da") }; + options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); + options.SupportedCultures = supportedCultures; + options.SupportedUICultures = supportedCultures; + options.UseSitecoreRequestLocalization(); + }); + app.UseSitecoreRenderingEngine(); + + app.UseEndpoints(endpoints => + { + // ReSharper disable once RouteTemplates.RouteParameterConstraintNotResolved - Custom constraint + endpoints.MapControllerRoute( + name: "default", + pattern: "content/{culture:culture}/{**sitecoreRoute}", + defaults: new { controller = "Home", action = "Index" }); + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs index 19f429b..cb73285 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs @@ -1,6 +1,6 @@ using System.Net; using AwesomeAssertions; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.LayoutService.Client.Request; @@ -10,51 +10,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Localization; -public class DefaultLocalizationFixture : IDisposable +public class DefaultLocalizationFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public DefaultLocalizationFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder.AddLocalization(options => options.ResourcesPath = "Resources"); - builder - .AddSitecoreLayoutService().WithDefaultRequestOptions(request => - { - request - .Language("da"); - }) - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-4", "Component4") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - - app.UseSitecoreRenderingEngine(); - - app.UseEndpoints(endpoints => - { - endpoints.MapSitecoreLocalizedRoute("Localized", "Index", "UsingGlobalMiddleware"); - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() { @@ -65,7 +25,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildDefaultLocalizationWebApplicationFactory().CreateClient(); // Act await client.GetStringAsync(new Uri("/da/UsingGlobalMiddleware", UriKind.Relative)); @@ -76,7 +36,41 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildDefaultLocalizationWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services.AddLocalization(options => options.ResourcesPath = "Resources"); + services + .AddSitecoreLayoutService().WithDefaultRequestOptions(request => { request.Language("da"); }) + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-4", "Component4") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + + app.UseSitecoreRenderingEngine(); + + app.UseEndpoints(endpoints => + { + endpoints.MapSitecoreLocalizedRoute("Localized", "Index", "UsingGlobalMiddleware"); + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs index 871719d..0ec9437 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs @@ -2,7 +2,7 @@ using System.Net; using AwesomeAssertions; using Microsoft.AspNetCore.Localization; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -11,32 +11,57 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Localization; -public class LocalizationFixture : IDisposable +public class LocalizationFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public LocalizationFixture() + [Fact] + public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() + { + // Arrange + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) + }); + + HttpClient client = BuildLocalizationWebApplicationFactory().CreateClient(); + + // Act + await client.GetStringAsync(new Uri("/ru-RU/UsingGlobalMiddleware", UriKind.Relative)); + + _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=ru-RU"); + } + + public void Dispose() { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => + _mockClientHandler.Dispose(); + GC.SuppressFinalize(this); + } + + private WebApplicationFactory BuildLocalizationWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => { - builder.AddLocalization(options => options.ResourcesPath = "Resources"); - builder + services.AddLocalization(options => options.ResourcesPath = "Resources"); + + services .AddSitecoreLayoutService() .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => + + services.AddSitecoreRenderingEngine(options => { options .AddModelBoundView("Component-4", "Component4") .AddDefaultComponentRenderer(); }); - }) - .Configure(app => + }); + + builder.Configure(app => { app.UseRouting(); app.UseRequestLocalization(options => @@ -56,32 +81,6 @@ public LocalizationFixture() endpoints.MapDefaultControllerRoute(); }); }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - - [Fact] - public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() - { - // Arrange - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - - HttpClient client = _server.CreateClient(); - - // Act - await client.GetStringAsync(new Uri("/ru-RU/UsingGlobalMiddleware", UriKind.Relative)); - - _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=ru-RU"); - } - - public void Dispose() - { - _mockClientHandler.Dispose(); - _server.Dispose(); - GC.SuppressFinalize(this); } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs index 6fc2bc6..50f7bae 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs @@ -3,7 +3,7 @@ using System.Net.Http.Headers; using AwesomeAssertions; using Microsoft.AspNetCore.Localization; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -12,53 +12,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Localization; -public class LocalizationUsingAttributeMiddlewareFixture : IDisposable +public class LocalizationUsingAttributeMiddlewareFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public LocalizationUsingAttributeMiddlewareFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder.AddLocalization(options => options.ResourcesPath = "Resources"); - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-4", "Component4") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseRequestLocalization(options => - { - List supportedCultures = [new("en"), new("uk-UA"), new("da-DK")]; - - options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); - options.SupportedCultures = supportedCultures; - options.SupportedUICultures = supportedCultures; - options.UseSitecoreRequestLocalization(); - }); - app.UseEndpoints(endpoints => - { - endpoints.MapSitecoreLocalizedRoute("Localized", "UseLocalizeWithAttribute", "UsingAttribute"); - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Theory] [InlineData("br", "en")] [InlineData("en", "en")] @@ -72,7 +30,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_FromTheR Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLocalizationUsingAttributeMiddlewareWebApplicationFactory().CreateClient(); // Act await client.GetStringAsync(new Uri($"/{routeLanguage}/UsingAttribute/UseLocalizeWithAttribute", UriKind.Relative)); @@ -95,7 +53,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_FromAcce Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLocalizationUsingAttributeMiddlewareWebApplicationFactory().CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.Clear(); if (!string.IsNullOrWhiteSpace(acceptLanguageHeader)) @@ -125,7 +83,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_RouteLan Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLocalizationUsingAttributeMiddlewareWebApplicationFactory().CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.Clear(); if (!string.IsNullOrWhiteSpace(acceptLanguageHeader)) @@ -134,7 +92,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_RouteLan } // Act - await client.GetStringAsync(new Uri($"{routeLanguage}/UsingAttribute/UseLocalizeWithAttribute", UriKind.Relative)); + await client.GetStringAsync(new Uri($"/{routeLanguage}/UsingAttribute/UseLocalizeWithAttribute", UriKind.Relative)); // Assert _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain($"sc_lang={mappedLanguage}"); @@ -143,7 +101,51 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_RouteLan public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildLocalizationUsingAttributeMiddlewareWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services.AddLocalization(options => options.ResourcesPath = "Resources"); + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-4", "Component4") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + + app.UseRequestLocalization(options => + { + List supportedCultures = new() { new("en"), new("uk-UA"), new("da-DK") }; + + options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); + options.SupportedCultures = supportedCultures; + options.SupportedUICultures = supportedCultures; + options.UseSitecoreRequestLocalization(); + }); + + app.UseSitecoreRenderingEngine(); + + app.UseEndpoints(endpoints => + { + endpoints.MapSitecoreLocalizedRoute("Localized", "UseLocalizeWithAttribute", "UsingAttribute"); + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file From 381f7f64324875ff28ac76e4a2e88ef9f10e3ef7 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 16 Sep 2025 13:52:01 +0530 Subject: [PATCH 11/41] Revert "Migrate Localization fixtures" This reverts commit 5f953d9eb0dd37e2c0ac4eacbc3123e20031be5f. --- .../AdvanceLocalizationFixture.cs | 110 +++++++++--------- .../DefaultLocalizationFixture.cs | 84 ++++++------- .../Localization/LocalizationFixture.cs | 79 ++++++------- ...lizationUsingAttributeMiddlewareFixture.cs | 102 ++++++++-------- 4 files changed, 190 insertions(+), 185 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs index e381562..5483406 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs @@ -4,7 +4,7 @@ using HtmlAgilityPack; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc.Razor; -using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -13,11 +13,59 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Localization; -public class AdvanceLocalizationFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class AdvanceLocalizationFixture : IDisposable { - private readonly MockHttpMessageHandler _mockClientHandler = new(); + private readonly TestServer _server; + private readonly MockHttpMessageHandler _mockClientHandler; private readonly Uri _layoutServiceUri = new("http://layout.service"); + public AdvanceLocalizationFixture() + { + TestServerBuilder testHostBuilder = new(); + _mockClientHandler = new MockHttpMessageHandler(); + testHostBuilder + .ConfigureServices(builder => + { + builder.AddLocalization(options => options.ResourcesPath = "Resources"); + builder.AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + builder.AddSitecoreRenderingEngine(options => + { + options.AddModelBoundView("Component-4", "Component4") + .AddDefaultComponentRenderer(); + }); + builder.AddMvc() + .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); + }) + .Configure(app => + { + app.UseRouting(); + app.UseRequestLocalization(options => + { + List supportedCultures = [new("en"), new("da")]; + options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); + options.SupportedCultures = supportedCultures; + options.SupportedUICultures = supportedCultures; + options.UseSitecoreRequestLocalization(); + }); + app.UseSitecoreRenderingEngine(); + + app.UseEndpoints(endpoints => + { + // ReSharper disable once RouteTemplates.RouteParameterConstraintNotResolved - Custom constraint + endpoints.MapControllerRoute( + name: "default", + pattern: "content/{culture:culture}/{**sitecoreRoute}", + defaults: new { controller = "Home", action = "Index" }); + endpoints.MapDefaultControllerRoute(); + }); + }); + + _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + } + [Fact] public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() { @@ -28,7 +76,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildAdvanceLocalizationWebApplicationFactory().CreateClient(); + HttpClient client = _server.CreateClient(); // Act await client.GetStringAsync(new Uri("content/da/UsingGlobalMiddleware", UriKind.Relative)); @@ -46,7 +94,7 @@ public async Task LocalizedRequest_PicksDefaultView() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildAdvanceLocalizationWebApplicationFactory().CreateClient(); + HttpClient client = _server.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -70,7 +118,7 @@ public async Task LocalizedRequest_PicksLocalizedView() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildAdvanceLocalizationWebApplicationFactory().CreateClient(); + HttpClient client = _server.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("content/da", UriKind.Relative)); @@ -87,55 +135,7 @@ public async Task LocalizedRequest_PicksLocalizedView() public void Dispose() { _mockClientHandler.Dispose(); + _server.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildAdvanceLocalizationWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services.AddLocalization(options => options.ResourcesPath = "Resources"); - - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options.AddModelBoundView("Component-4", "Component4") - .AddDefaultComponentRenderer(); - }); - - services.AddMvc() - .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseRequestLocalization(options => - { - List supportedCultures = new() { new("en"), new("da") }; - options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); - options.SupportedCultures = supportedCultures; - options.SupportedUICultures = supportedCultures; - options.UseSitecoreRequestLocalization(); - }); - app.UseSitecoreRenderingEngine(); - - app.UseEndpoints(endpoints => - { - // ReSharper disable once RouteTemplates.RouteParameterConstraintNotResolved - Custom constraint - endpoints.MapControllerRoute( - name: "default", - pattern: "content/{culture:culture}/{**sitecoreRoute}", - defaults: new { controller = "Home", action = "Index" }); - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs index cb73285..19f429b 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs @@ -1,6 +1,6 @@ using System.Net; using AwesomeAssertions; -using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.LayoutService.Client.Request; @@ -10,56 +10,36 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Localization; -public class DefaultLocalizationFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class DefaultLocalizationFixture : IDisposable { - private readonly MockHttpMessageHandler _mockClientHandler = new(); + private readonly TestServer _server; + private readonly MockHttpMessageHandler _mockClientHandler; private readonly Uri _layoutServiceUri = new("http://layout.service"); - [Fact] - public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() + public DefaultLocalizationFixture() { - // Arrange - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) - }); - - HttpClient client = BuildDefaultLocalizationWebApplicationFactory().CreateClient(); - - // Act - await client.GetStringAsync(new Uri("/da/UsingGlobalMiddleware", UriKind.Relative)); - - _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=da"); - } - - public void Dispose() - { - _mockClientHandler.Dispose(); - GC.SuppressFinalize(this); - } - - private WebApplicationFactory BuildDefaultLocalizationWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => + TestServerBuilder testHostBuilder = new(); + _mockClientHandler = new MockHttpMessageHandler(); + testHostBuilder + .ConfigureServices(builder => { - services.AddLocalization(options => options.ResourcesPath = "Resources"); - services - .AddSitecoreLayoutService().WithDefaultRequestOptions(request => { request.Language("da"); }) + builder.AddLocalization(options => options.ResourcesPath = "Resources"); + builder + .AddSitecoreLayoutService().WithDefaultRequestOptions(request => + { + request + .Language("da"); + }) .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => + builder.AddSitecoreRenderingEngine(options => { options .AddModelBoundView("Component-4", "Component4") .AddDefaultComponentRenderer(); }); - }); - - builder.Configure(app => + }) + .Configure(app => { app.UseRouting(); @@ -71,6 +51,32 @@ private WebApplicationFactory BuildDefaultLocalizatio endpoints.MapDefaultControllerRoute(); }); }); + + _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + } + + [Fact] + public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() + { + // Arrange + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); + + HttpClient client = _server.CreateClient(); + + // Act + await client.GetStringAsync(new Uri("/da/UsingGlobalMiddleware", UriKind.Relative)); + + _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=da"); + } + + public void Dispose() + { + _mockClientHandler.Dispose(); + _server.Dispose(); + GC.SuppressFinalize(this); } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs index 0ec9437..871719d 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs @@ -2,7 +2,7 @@ using System.Net; using AwesomeAssertions; using Microsoft.AspNetCore.Localization; -using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -11,57 +11,32 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Localization; -public class LocalizationFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class LocalizationFixture : IDisposable { - private readonly MockHttpMessageHandler _mockClientHandler = new(); + private readonly TestServer _server; + private readonly MockHttpMessageHandler _mockClientHandler; private readonly Uri _layoutServiceUri = new("http://layout.service"); - [Fact] - public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() - { - // Arrange - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) - }); - - HttpClient client = BuildLocalizationWebApplicationFactory().CreateClient(); - - // Act - await client.GetStringAsync(new Uri("/ru-RU/UsingGlobalMiddleware", UriKind.Relative)); - - _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=ru-RU"); - } - - public void Dispose() + public LocalizationFixture() { - _mockClientHandler.Dispose(); - GC.SuppressFinalize(this); - } - - private WebApplicationFactory BuildLocalizationWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => + TestServerBuilder testHostBuilder = new(); + _mockClientHandler = new MockHttpMessageHandler(); + testHostBuilder + .ConfigureServices(builder => { - services.AddLocalization(options => options.ResourcesPath = "Resources"); - - services + builder.AddLocalization(options => options.ResourcesPath = "Resources"); + builder .AddSitecoreLayoutService() .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => + builder.AddSitecoreRenderingEngine(options => { options .AddModelBoundView("Component-4", "Component4") .AddDefaultComponentRenderer(); }); - }); - - builder.Configure(app => + }) + .Configure(app => { app.UseRouting(); app.UseRequestLocalization(options => @@ -81,6 +56,32 @@ private WebApplicationFactory BuildLocalizationWebApp endpoints.MapDefaultControllerRoute(); }); }); + + _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + } + + [Fact] + public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() + { + // Arrange + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); + + HttpClient client = _server.CreateClient(); + + // Act + await client.GetStringAsync(new Uri("/ru-RU/UsingGlobalMiddleware", UriKind.Relative)); + + _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=ru-RU"); + } + + public void Dispose() + { + _mockClientHandler.Dispose(); + _server.Dispose(); + GC.SuppressFinalize(this); } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs index 50f7bae..6fc2bc6 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs @@ -3,7 +3,7 @@ using System.Net.Http.Headers; using AwesomeAssertions; using Microsoft.AspNetCore.Localization; -using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -12,11 +12,53 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Localization; -public class LocalizationUsingAttributeMiddlewareFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class LocalizationUsingAttributeMiddlewareFixture : IDisposable { - private readonly MockHttpMessageHandler _mockClientHandler = new(); + private readonly TestServer _server; + private readonly MockHttpMessageHandler _mockClientHandler; private readonly Uri _layoutServiceUri = new("http://layout.service"); + public LocalizationUsingAttributeMiddlewareFixture() + { + TestServerBuilder testHostBuilder = new(); + _mockClientHandler = new MockHttpMessageHandler(); + testHostBuilder + .ConfigureServices(builder => + { + builder.AddLocalization(options => options.ResourcesPath = "Resources"); + builder + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + builder.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-4", "Component4") + .AddDefaultComponentRenderer(); + }); + }) + .Configure(app => + { + app.UseRouting(); + app.UseRequestLocalization(options => + { + List supportedCultures = [new("en"), new("uk-UA"), new("da-DK")]; + + options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); + options.SupportedCultures = supportedCultures; + options.SupportedUICultures = supportedCultures; + options.UseSitecoreRequestLocalization(); + }); + app.UseEndpoints(endpoints => + { + endpoints.MapSitecoreLocalizedRoute("Localized", "UseLocalizeWithAttribute", "UsingAttribute"); + endpoints.MapDefaultControllerRoute(); + }); + }); + + _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + } + [Theory] [InlineData("br", "en")] [InlineData("en", "en")] @@ -30,7 +72,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_FromTheR Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLocalizationUsingAttributeMiddlewareWebApplicationFactory().CreateClient(); + HttpClient client = _server.CreateClient(); // Act await client.GetStringAsync(new Uri($"/{routeLanguage}/UsingAttribute/UseLocalizeWithAttribute", UriKind.Relative)); @@ -53,7 +95,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_FromAcce Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLocalizationUsingAttributeMiddlewareWebApplicationFactory().CreateClient(); + HttpClient client = _server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.Clear(); if (!string.IsNullOrWhiteSpace(acceptLanguageHeader)) @@ -83,7 +125,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_RouteLan Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLocalizationUsingAttributeMiddlewareWebApplicationFactory().CreateClient(); + HttpClient client = _server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.Clear(); if (!string.IsNullOrWhiteSpace(acceptLanguageHeader)) @@ -92,7 +134,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_RouteLan } // Act - await client.GetStringAsync(new Uri($"/{routeLanguage}/UsingAttribute/UseLocalizeWithAttribute", UriKind.Relative)); + await client.GetStringAsync(new Uri($"{routeLanguage}/UsingAttribute/UseLocalizeWithAttribute", UriKind.Relative)); // Assert _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain($"sc_lang={mappedLanguage}"); @@ -101,51 +143,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_RouteLan public void Dispose() { _mockClientHandler.Dispose(); + _server.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildLocalizationUsingAttributeMiddlewareWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services.AddLocalization(options => options.ResourcesPath = "Resources"); - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-4", "Component4") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - - app.UseRequestLocalization(options => - { - List supportedCultures = new() { new("en"), new("uk-UA"), new("da-DK") }; - - options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); - options.SupportedCultures = supportedCultures; - options.SupportedUICultures = supportedCultures; - options.UseSitecoreRequestLocalization(); - }); - - app.UseSitecoreRenderingEngine(); - - app.UseEndpoints(endpoints => - { - endpoints.MapSitecoreLocalizedRoute("Localized", "UseLocalizeWithAttribute", "UsingAttribute"); - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file From b984d871bb608c2be23a2068390b7a117d79b43e Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 16 Sep 2025 14:26:22 +0530 Subject: [PATCH 12/41] Migrate Multisite fixture --- .../Fixtures/Multisite/MultisiteFixture.cs | 150 +++++++++--------- 1 file changed, 75 insertions(+), 75 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs index 42b36ee..0c77e3f 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs @@ -3,7 +3,7 @@ using AwesomeAssertions; using GraphQL; using GraphQL.Client.Abstractions; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using NSubstitute; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -15,79 +15,12 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Multisite; -public class MultisiteFixture : IDisposable +public class MultisiteFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { private const string DefaultSiteName = "defaultSiteName"; - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public MultisiteFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService().WithDefaultRequestOptions(request => - { - request - .SiteName(DefaultSiteName); - if (!request.ContainsKey(RequestKeys.Language)) - { - request.Language("en"); - } - }) - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - IGraphQLClient? mockedGraphQLClient = Substitute.For(); - mockedGraphQLClient.SendQueryAsync(Arg.Any()).Returns(new GraphQLResponse - { - Data = new SiteInfoCollectionResult - { - Site = new Site - { - SiteInfoCollection = - [ - new SiteInfo { HostName = "host1", Name = "siteForHost1" }, - new SiteInfo { HostName = "host2", Name = "siteForHost2" }, - new SiteInfo { HostName = "foo.bar", Name = "fooSite" }, - new SiteInfo { HostName = "*.test.com", Name = "wildcardSite" }, - new SiteInfo { HostName = "concrete.test.com", Name = "concrete" }, - new SiteInfo { HostName = "multiHostname1.test.com | multiHostname2.test.com ", Name = "multiHostNameTestSite" } - ] - } - } - }); - - builder.AddSitecoreRenderingEngine(options => - { - options.AddDefaultPartialView("_ComponentNotFound"); - }); - - builder.AddSingleton(mockedGraphQLClient); - builder.AddMultisite(); - }) - .Configure(app => - { - app.UseRouting(); - app.UseMultisite(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapFallbackToController("Index", "Multisite"); - }); - }); - - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK - }); - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Theory] [InlineData("host1", "siteForHost1")] [InlineData("host2", "siteForHost2")] @@ -100,7 +33,7 @@ public MultisiteFixture() public async Task Multisite_Should_Resolve_SiteName_ByHostName(string hostname, string expectedSiteName) { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = BuildMultisiteWebApplicationFactory().CreateClient(); client.BaseAddress = new Uri($"http://{hostname}"); // Act @@ -116,7 +49,7 @@ public async Task Multisite_Should_Resolve_SiteName_ByHostName(string hostname, public async Task Multisite_Should_Resolve_SiteName_ByQueryParam() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = BuildMultisiteWebApplicationFactory().CreateClient(); const string expectedSiteName = "siteNameFromQueryString"; // Act @@ -133,7 +66,7 @@ public async Task Multisite_Should_Resolve_SiteName_ByQueryParam() public async Task Multisite_Should_FallBacks_To_DefaultSite_If_Site_Is_NotResolved(string hostname) { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = BuildMultisiteWebApplicationFactory().CreateClient(); client.BaseAddress = new Uri($"http://{hostname}"); // Act @@ -150,7 +83,7 @@ public async Task Multisite_Should_FallBacks_To_DefaultSite_If_Site_Is_NotResolv public async Task Multisite_Should_FallBacks_To_DefaultSite_If_Site_Is_NotResolved_OnSecondRequest(string hostnameFirstRequest, string hostnameSecondRequest, string resolvedFirsSite) { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = BuildMultisiteWebApplicationFactory().CreateClient(); HttpRequestMessage msg = new() { @@ -175,8 +108,75 @@ public async Task Multisite_Should_FallBacks_To_DefaultSite_If_Site_Is_NotResolv public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildMultisiteWebApplicationFactory() + { + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK + }); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService().WithDefaultRequestOptions(request => + { + request + .SiteName(DefaultSiteName); + if (!request.ContainsKey(RequestKeys.Language)) + { + request.Language("en"); + } + }) + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + IGraphQLClient? mockedGraphQLClient = Substitute.For(); + mockedGraphQLClient + .SendQueryAsync(Arg.Any()) + .Returns(new GraphQLResponse + { + Data = new SiteInfoCollectionResult + { + Site = new Site + { + SiteInfoCollection = new[] + { + new SiteInfo { HostName = "host1", Name = "siteForHost1" }, + new SiteInfo { HostName = "host2", Name = "siteForHost2" }, + new SiteInfo { HostName = "foo.bar", Name = "fooSite" }, + new SiteInfo { HostName = "*.test.com", Name = "wildcardSite" }, + new SiteInfo { HostName = "concrete.test.com", Name = "concrete" }, + new SiteInfo { HostName = "multiHostname1.test.com | multiHostname2.test.com ", Name = "multiHostNameTestSite" } + } + } + } + }); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultPartialView("_ComponentNotFound"); + }); + + services.AddSingleton(mockedGraphQLClient); + services.AddMultisite(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseMultisite(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapFallbackToController("Index", "Multisite"); + }); + }); + }); + } } \ No newline at end of file From 07a4c035f5d9cd073c282d623921e98393203b44 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 16 Sep 2025 14:42:10 +0530 Subject: [PATCH 13/41] Migrate SearchOptimization fixtures --- .../EdgeSitemapProxyFixture.cs | 103 +++++++++--------- .../SearchOptimization/SitemapProxyFixture.cs | 63 +++++------ 2 files changed, 80 insertions(+), 86 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs index 9540022..690f0e8 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs @@ -2,7 +2,7 @@ using AwesomeAssertions; using GraphQL; using GraphQL.Client.Abstractions; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using NSubstitute; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Mocks; @@ -13,66 +13,17 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.SearchOptimization; -public class EdgeSitemapProxyFixture : IDisposable +public class EdgeSitemapProxyFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly ISitemapService _mockSitemapService = Substitute.For(); private readonly Uri _edgeSitemapUrl = new("https://xmcloud-test.com/sitemap.xml"); - public EdgeSitemapProxyFixture() - { - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK - }); - - TestServerBuilder testHostBuilder = new(); - _ = testHostBuilder - .ConfigureServices(builder => - { - builder.AddSingleton(_mockSitemapService); - builder.AddSingleton(_ => - { - return new CustomHttpClientFactory( - () => - new HttpClient(_mockClientHandler)); - }); - - IGraphQLClient? mockedGraphQLClient = Substitute.For(); - mockedGraphQLClient.SendQueryAsync(Arg.Any()).Returns(new GraphQLResponse - { - Data = new SiteInfoResultModel - { - Site = new Site - { - SiteInfo = new SiteInfo - { - Sitemap = - [ - _edgeSitemapUrl.ToString() - ] - } - } - } - }); - - builder.AddSingleton(mockedGraphQLClient); - builder.AddEdgeSitemap(); - }) - .Configure(app => - { - app.UseSitemap(); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task EdgeSitemap_MustBeProxied() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = BuildEdgeSitemapWebApplicationFactory().CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/sitemap.xml", UriKind.Relative)); _mockSitemapService.GetSitemapUrl(Arg.Any(), Arg.Any()) .Returns(_edgeSitemapUrl.AbsoluteUri); @@ -89,8 +40,54 @@ public async Task EdgeSitemap_MustBeProxied() public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildEdgeSitemapWebApplicationFactory() + { + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK + }); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services.AddSingleton(_mockSitemapService); + + services.AddSingleton(_ => + { + return new CustomHttpClientFactory( + () => new HttpClient(_mockClientHandler)); + }); + + IGraphQLClient? mockedGraphQLClient = Substitute.For(); + mockedGraphQLClient + .SendQueryAsync(Arg.Any()) + .Returns(new GraphQLResponse + { + Data = new SiteInfoResultModel + { + Site = new Site + { + SiteInfo = new SiteInfo + { + Sitemap = new[] { _edgeSitemapUrl.ToString() } + } + } + } + }); + + services.AddSingleton(mockedGraphQLClient); + services.AddEdgeSitemap(); + }); + + builder.Configure(app => + { + app.UseSitemap(); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/SitemapProxyFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/SitemapProxyFixture.cs index 62aec98..5434b61 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/SitemapProxyFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/SitemapProxyFixture.cs @@ -1,6 +1,6 @@ using System.Net; using AwesomeAssertions; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Mocks; using Sitecore.AspNetCore.SDK.SearchOptimization.Extensions; @@ -8,45 +8,16 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.SearchOptimization; -public class SitemapProxyFixture : IDisposable +public class SitemapProxyFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _cdInstanceUri = new("http://cd"); - public SitemapProxyFixture() - { - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK - }); - - TestServerBuilder testHostBuilder = new(); - _ = testHostBuilder - .ConfigureServices(builder => - { - builder.AddSingleton(_ => - { - return new CustomHttpClientFactory( - () => - new HttpClient(_mockClientHandler)); - }); - - builder.AddSitemap(c => c.Url = _cdInstanceUri); - }) - .Configure(app => - { - app.UseSitemap(); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task SitemapRequest_MustBeProxied() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = BuildSitemapProxyWebApplicationFactory().CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/sitemap.xml", UriKind.Relative)); // Act @@ -61,8 +32,34 @@ public async Task SitemapRequest_MustBeProxied() public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildSitemapProxyWebApplicationFactory() + { + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK + }); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services.AddSingleton(_ => + { + return new CustomHttpClientFactory( + () => new HttpClient(_mockClientHandler)); + }); + + services.AddSitemap(c => c.Url = _cdInstanceUri); + }); + + builder.Configure(app => + { + app.UseSitemap(); + }); + }); + } } \ No newline at end of file From 6740448288f380d54887346113d91bca53905999 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 16 Sep 2025 15:30:46 +0530 Subject: [PATCH 14/41] Migrate TagHelper Fixtures --- .../TagHelpers/AllFieldTagHelpersFixture.cs | 72 ++++++++------- .../TagHelpers/DateFieldTagHelperFixture.cs | 74 ++++++++-------- .../TagHelpers/FileFieldTagHelperFixture.cs | 78 ++++++++-------- .../TagHelpers/ImageFieldTagHelperFixture.cs | 85 +++++++++--------- .../TagHelpers/LinkFieldTagHelperFixture.cs | 88 +++++++++---------- .../TagHelpers/NumberFieldTagHelperFixture.cs | 73 ++++++++------- .../TagHelpers/PlaceholderTagHelperFixture.cs | 78 ++++++++-------- .../RichTextFieldTagHelperFixture.cs | 76 ++++++++-------- .../TagHelpers/TextFieldTagHelperFixture.cs | 74 ++++++++-------- 9 files changed, 340 insertions(+), 358 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs index 052830a..ee5f7f9 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs @@ -2,7 +2,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -12,43 +12,11 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class AllFieldTagHelpersFixture : IDisposable +public class AllFieldTagHelpersFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public AllFieldTagHelpersFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-All-Field-Types", "ComponentWithAllFieldTypes") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task ComponentWithAllFieldTypes_RendersFieldsCorrectly() { @@ -59,7 +27,7 @@ public async Task ComponentWithAllFieldTypes_RendersFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildAllFieldTagHelpersWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -92,7 +60,37 @@ public async Task ComponentWithAllFieldTypes_RendersFieldsCorrectly() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildAllFieldTagHelpersWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-All-Field-Types", "ComponentWithAllFieldTypes") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/DateFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/DateFieldTagHelperFixture.cs index a3bdf8b..384b01d 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/DateFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/DateFieldTagHelperFixture.cs @@ -2,7 +2,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -11,43 +11,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class DateFieldTagHelperFixture : IDisposable +public class DateFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public DateFieldTagHelperFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Dates", "ComponentWithDates") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task DateTagHelper_DoesNotResetOtherTagHelperOutput() { @@ -58,7 +26,7 @@ public async Task DateTagHelper_DoesNotResetOtherTagHelperOutput() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildDateFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -83,7 +51,7 @@ public async Task DateTagHelper_GeneratesProperDate() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildDateFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -102,7 +70,37 @@ public async Task DateTagHelper_GeneratesProperDate() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildDateFieldTagHelperWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Dates", "ComponentWithDates") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/FileFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/FileFieldTagHelperFixture.cs index 8006ed5..992bec6 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/FileFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/FileFieldTagHelperFixture.cs @@ -1,7 +1,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -10,43 +10,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class FileFieldTagHelperFixture : IDisposable +public class FileFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public FileFieldTagHelperFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Files", "ComponentWithFiles") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task FileTagHelper_RendersAttributeFromModel() { @@ -57,7 +25,7 @@ public async Task FileTagHelper_RendersAttributeFromModel() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildFileFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -107,7 +75,7 @@ public async Task FileTagHelper_RendersCustomTagsAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildFileFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -168,7 +136,7 @@ public async Task FileTagHelper_OverridesModelAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildFileFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -217,7 +185,7 @@ public async Task FileTagHelper_RendersInnerHtml() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildFileFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -240,7 +208,37 @@ public async Task FileTagHelper_RendersInnerHtml() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildFileFieldTagHelperWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Files", "ComponentWithFiles") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs index 3b0b421..da699e2 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs @@ -1,7 +1,8 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -11,45 +12,11 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class ImageFieldTagHelperFixture : IDisposable +public class ImageFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public ImageFieldTagHelperFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Images", "ComponentWithImages") - .AddViewComponent("Component-1", "Component1") - .AddModelBoundView("Component-2", "Component2") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task ImgTagHelper_GeneratedProperImageWithCustomAttributes() { @@ -60,7 +27,7 @@ public async Task ImgTagHelper_GeneratedProperImageWithCustomAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.PageWithPreview)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -84,7 +51,7 @@ public async Task ImgTagHelper_GeneratesImageTags() Content = new StringContent(Serializer.Serialize(CannedResponses.PageWithPreview)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -108,7 +75,7 @@ public async Task ImgTagHelper_GeneratedProperHtmlWithoutTagName() Content = new StringContent(Serializer.Serialize(CannedResponses.PageWithPreview)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -132,7 +99,7 @@ public async Task ImgTagHelper_GeneratesProperImageUrlIncludingImageParams() Content = new StringContent(Serializer.Serialize(CannedResponses.PageWithPreview)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -158,7 +125,7 @@ public async Task ImgTagHelper_GeneratesProperEditableImageMarkupWithCustomPrope Content = new StringContent(Serializer.Serialize(CannedResponses.EditablePage)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -179,7 +146,39 @@ public async Task ImgTagHelper_GeneratesProperEditableImageMarkupWithCustomPrope public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildImageFieldTagHelperWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Images", "ComponentWithImages") + .AddViewComponent("Component-1", "Component1") + .AddModelBoundView("Component-2", "Component2") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs index 9d0b7e5..3d327cb 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs @@ -1,7 +1,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -10,43 +10,11 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class LinkFieldTagHelperFixture : IDisposable +public class LinkFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public LinkFieldTagHelperFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Links", "ComponentWithLinks") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task LinkTagHelper_DoesNotResetOtherTagHelperOutput() { @@ -57,7 +25,7 @@ public async Task LinkTagHelper_DoesNotResetOtherTagHelperOutput() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -82,7 +50,7 @@ public async Task LinkTagHelper_GeneratesAnchorTags() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -106,7 +74,7 @@ public async Task LinkTagHelper_PrioritizeUserProvidedLinkText() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -130,7 +98,7 @@ public async Task LinkTagHelper_RenderFieldLinkTextIfNoInnerContent() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -154,7 +122,7 @@ public async Task LinkTagHelper_RendersLinkAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -188,7 +156,7 @@ public async Task LinkTagHelper_GeneratesNestedTags() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -212,7 +180,7 @@ public async Task LinkTagHelper_DoesNotTrimUserAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -236,7 +204,7 @@ public async Task LinkTagHelper_RenderFieldAuthorLinkTextInEEIfEditableTrue() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -260,7 +228,7 @@ public async Task LinkTagHelper_RenderFieldCustomLinkTextInEEIfEditableFalse() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -277,7 +245,37 @@ public async Task LinkTagHelper_RenderFieldCustomLinkTextInEEIfEditableFalse() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildLinkFieldTagHelperWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Links", "ComponentWithLinks") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs index 181d140..0b352a7 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs @@ -2,7 +2,7 @@ using System.Net; using AwesomeAssertions; using HtmlAgilityPack; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -11,44 +11,12 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class NumberFieldTagHelperFixture : IDisposable +public class NumberFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { private const decimal TestValue = 1.21M; - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public NumberFieldTagHelperFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Number", "ComponentWithNumber") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task NumberTagHelper_DoesNotResetOtherTagHelperOutput() { @@ -59,7 +27,7 @@ public async Task NumberTagHelper_DoesNotResetOtherTagHelperOutput() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildNumberFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -84,7 +52,7 @@ public async Task NumberHelper_GeneratesProperNumber() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildNumberFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -103,7 +71,36 @@ public async Task NumberHelper_GeneratesProperNumber() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildNumberFieldTagHelperWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Number", "ComponentWithNumber") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs index 3326444..2dbae47 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs @@ -1,6 +1,6 @@ using System.Net; using AwesomeAssertions; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -10,44 +10,11 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class PlaceholderTagHelperFixture : IDisposable +public class PlaceholderTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public PlaceholderTagHelperFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddViewComponent("Component-1", "Component1") - .AddModelBoundView("Component-2", "Component2") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task PageInNormalMode_WithNestedPlaceholderComponent_ComponentIsRenderedCorrectly() { @@ -58,7 +25,7 @@ public async Task PageInNormalMode_WithNestedPlaceholderComponent_ComponentIsRen Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildPlaceholderTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -77,7 +44,7 @@ public async Task PageInEditableMode_WithComponentsAndChromes_ComponentAndChrome Content = new StringContent(Serializer.Serialize(CannedResponses.EditablePage)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildPlaceholderTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -104,7 +71,7 @@ public async Task PageInHorizonEditableMode_WithComponentsAndChromes_ComponentAn Content = new StringContent(Serializer.Serialize(CannedResponses.HorizonEditablePage)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildPlaceholderTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -124,7 +91,38 @@ public async Task PageInHorizonEditableMode_WithComponentsAndChromes_ComponentAn public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildPlaceholderTagHelperWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddViewComponent("Component-1", "Component1") + .AddModelBoundView("Component-2", "Component2") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs index e9e268e..1356d4b 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs @@ -2,7 +2,7 @@ using System.Text.Encodings.Web; using AwesomeAssertions; using HtmlAgilityPack; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -12,43 +12,11 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class RichTextFieldTagHelperFixture : IDisposable +public class RichTextFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public RichTextFieldTagHelperFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-4", "Component4") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task RichTextFieldTagHelper_DoesNotResetOtherTagHelperOutput() { @@ -59,7 +27,7 @@ public async Task RichTextFieldTagHelper_DoesNotResetOtherTagHelperOutput() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildRichTextFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -83,7 +51,7 @@ public async Task RichTextFieldTagHelper_RendersFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildRichTextFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -115,7 +83,7 @@ public async Task RichTextFieldTagHelper_RendersEditableFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.HorizonEditablePage)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildRichTextFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -144,7 +112,37 @@ public async Task RichTextFieldTagHelper_RendersEditableFieldsCorrectly() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildRichTextFieldTagHelperWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-4", "Component4") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/TextFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/TextFieldTagHelperFixture.cs index 920cbfd..10e5490 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/TextFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/TextFieldTagHelperFixture.cs @@ -2,7 +2,7 @@ using System.Text.Encodings.Web; using AwesomeAssertions; using HtmlAgilityPack; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -12,43 +12,11 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class TextFieldTagHelperFixture : IDisposable +public class TextFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { - private readonly TestServer _server; - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public TextFieldTagHelperFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-3", "Component3") - .AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task TextFieldTagHelper_RendersFieldsCorrectly() { @@ -59,7 +27,7 @@ public async Task TextFieldTagHelper_RendersFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildTextFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -94,7 +62,7 @@ public async Task TextFieldTagHelper_RendersEditableFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.HorizonEditablePage)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildTextFieldTagHelperWebApplicationFactory().CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -123,7 +91,37 @@ public async Task TextFieldTagHelper_RendersEditableFieldsCorrectly() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildTextFieldTagHelperWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-3", "Component3") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file From 80e47d88203a6284d48558f6f9e2c6f0e119f2c6 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 16 Sep 2025 16:59:07 +0530 Subject: [PATCH 15/41] Migrate RequestHeadersValidationFixture --- .../RequestHeadersValidationFixture.cs | 41 +++++++++---------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestHeadersValidationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestHeadersValidationFixture.cs index ff45b5c..37d65b6 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestHeadersValidationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestHeadersValidationFixture.cs @@ -1,5 +1,6 @@ -using AwesomeAssertions; -using Microsoft.AspNetCore.TestHost; +using System.Net; +using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.LayoutService.Client.Interfaces; @@ -10,17 +11,17 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures; -public class RequestHeadersValidationFixture : IDisposable +public class RequestHeadersValidationFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { private MockHttpMessageHandler _clientHandler = new(); - private TestServer _server = null!; + private WebApplicationFactory _appFactory = null!; [Fact] public async Task Request_WithNonValidatedHeaders_HeadersAreProperlyValidated() { // Arrange - ConfigureServices(["User-Agent"]); - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + _appFactory = BuildRequestHeadersWebApplicationFactory(new[] { "User-Agent" }); + ISitecoreLayoutClient layoutClient = _appFactory.Services.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -41,8 +42,8 @@ public async Task Request_WithNonValidatedHeaders_HeadersAreProperlyValidated() public async Task Request_WithoutNonValidatedHeaders_ErrorThrown() { // Arrange - ConfigureServices([]); - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + _appFactory = BuildRequestHeadersWebApplicationFactory(Array.Empty()); + ISitecoreLayoutClient layoutClient = _appFactory.Services.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -58,24 +59,23 @@ public async Task Request_WithoutNonValidatedHeaders_ErrorThrown() public void Dispose() { _clientHandler.Dispose(); - _server.Dispose(); + _appFactory?.Dispose(); GC.SuppressFinalize(this); } - private void ConfigureServices(string[] nonValidatedHeaders) + private WebApplicationFactory BuildRequestHeadersWebApplicationFactory(string[] nonValidatedHeaders) { - TestServerBuilder testHostBuilder = new(); _clientHandler = new MockHttpMessageHandler(); Dictionary headers = new() { { "User-Agent", ["site;core"] } }; - testHostBuilder - .ConfigureServices(builder => + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => { - ISitecoreLayoutClientBuilder lsc = builder - .AddSitecoreLayoutService(); + ISitecoreLayoutClientBuilder lsc = services.AddSitecoreLayoutService(); lsc.AddHttpHandler("mock", _ => new HttpClient(_clientHandler) { BaseAddress = new Uri("http://layout.service") }, nonValidatedHeaders) .WithRequestOptions(request => @@ -85,14 +85,13 @@ private void ConfigureServices(string[] nonValidatedHeaders) }) .AsDefaultHandler(); - builder - .AddSitecoreRenderingEngine(); - }) - .Configure(app => + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => { app.UseSitecoreRenderingEngine(); }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + }); } } \ No newline at end of file From 5f6fecb7dbd44a501d310a676b04ad6b2245506b Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Wed, 17 Sep 2025 13:22:33 +0530 Subject: [PATCH 16/41] Migrate ControllerMiddlewareFixture --- .../Fixtures/ControllerMiddlewareFixture.cs | 68 ++++++++++--------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ControllerMiddlewareFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ControllerMiddlewareFixture.cs index 4ea399e..cf80c77 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ControllerMiddlewareFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ControllerMiddlewareFixture.cs @@ -1,46 +1,23 @@ using System.Net; using AwesomeAssertions; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; +using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; using Xunit; namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures; -public class ControllerMiddlewareFixture : IDisposable +public class ControllerMiddlewareFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable { private const string MiddlewareController = "ControllerMiddleware"; private const string GlobalMiddlewareController = "GlobalMiddleware"; - private readonly TestServer _server; - - private readonly MockHttpMessageHandler _mockClientHandler; + private readonly MockHttpMessageHandler _mockClientHandler = new MockHttpMessageHandler(); private readonly Uri _layoutServiceUri = new("http://layout.service"); - public ControllerMiddlewareFixture() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler( - "mock", - _ => new HttpClient(_mockClientHandler) - { - BaseAddress = _layoutServiceUri - }) - .AsDefaultHandler(); - }) - .Configure(_ => { }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - } - [Fact] public async Task HttpClient_IsInvoked() { @@ -49,7 +26,7 @@ public async Task HttpClient_IsInvoked() StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildControllerMiddlewareWebApplicationFactory().CreateClient(); await client.GetAsync(MiddlewareController); _mockClientHandler.WasInvoked.Should().BeTrue(); @@ -63,7 +40,7 @@ public async Task HttpClient_IsNotInvoked() StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildControllerMiddlewareWebApplicationFactory().CreateClient(); await client.GetAsync(GlobalMiddlewareController); _mockClientHandler.WasInvoked.Should().BeFalse(); @@ -77,7 +54,7 @@ public async Task Controller_ReturnsCorrectContent() StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildControllerMiddlewareWebApplicationFactory().CreateClient(); string response = await client.GetStringAsync(GlobalMiddlewareController); response.Should().Be("\"success\""); @@ -91,7 +68,7 @@ public async Task HttpClient_LayoutServiceUriMapped() StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = BuildControllerMiddlewareWebApplicationFactory().CreateClient(); await client.GetAsync(MiddlewareController); _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should() @@ -100,8 +77,35 @@ public async Task HttpClient_LayoutServiceUriMapped() public void Dispose() { - _server.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildControllerMiddlewareWebApplicationFactory() + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddRouting() + .AddSitecoreLayoutService() + .AddHttpHandler( + "mock", + _ => new HttpClient(_mockClientHandler) + { + BaseAddress = _layoutServiceUri + }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + } } \ No newline at end of file From e67407fcfaccfe09adf9f04893225d1adbf70b3d Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Wed, 17 Sep 2025 14:45:00 +0530 Subject: [PATCH 17/41] Migrate ErrorHandlingFixture --- .../Fixtures/ErrorHandlingFixture.cs | 222 +++++++++++++----- 1 file changed, 168 insertions(+), 54 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ErrorHandlingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ErrorHandlingFixture.cs index a476e37..6750c98 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ErrorHandlingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ErrorHandlingFixture.cs @@ -2,7 +2,7 @@ using AutoFixture; using AwesomeAssertions; using HtmlAgilityPack; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Sitecore.AspNetCore.SDK.AutoFixture.Attributes; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Exceptions; @@ -22,77 +22,95 @@ public class ErrorHandlingFixture public static Action ValidHttpClient => f => { - TestServerBuilder testHostBuilder = new(); - MockHttpMessageHandler mockClientHandler = new(); - testHostBuilder - .ConfigureServices(builder => + MockHttpMessageHandler mockClientHandler = new MockHttpMessageHandler(); + WebApplicationFactory factory = new TestWebApplicationFactory() + .WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => { - builder - .AddSitecoreLayoutService() + services.AddRouting(); + services.AddControllersWithViews(); + services.AddSitecoreLayoutService() .AddHttpHandler("valid", _ => new HttpClient(mockClientHandler) { BaseAddress = new Uri("http://layout.service") }) .AsDefaultHandler(); - }) - .Configure(app => + + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => { + app.UseRouting(); app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); }); - - TestServer server = testHostBuilder.BuildServer(new Uri("http://localhost")); + }); f.Inject(mockClientHandler); - f.Inject(server); + f.Inject(factory); }; public static Action InvalidHttpClient => f => { - TestServerBuilder testHostBuilder = new(); - MockHttpMessageHandler mockClientHandler = new(); - testHostBuilder - .ConfigureServices(builder => + MockHttpMessageHandler mockClientHandler = new MockHttpMessageHandler(); + WebApplicationFactory factory = new TestWebApplicationFactory() + .WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => { - builder - .AddSitecoreLayoutService() + services.AddRouting(); + services.AddControllersWithViews(); + services.AddSitecoreLayoutService() .AddHttpHandler("invalid", _ => new HttpClient { BaseAddress = new Uri("http://invalid.url") }) .AsDefaultHandler(); - }) - .Configure(app => + + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => { + app.UseRouting(); app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); }); - - TestServer server = testHostBuilder.BuildServer(new Uri("http://localhost")); + }); f.Inject(mockClientHandler); - f.Inject(server); + f.Inject(factory); }; public static Action InvalidHttpMessageConfiguration => f => { - TestServerBuilder testHostBuilder = new(); - MockHttpMessageHandler mockClientHandler = new(); - testHostBuilder - .ConfigureServices(builder => + MockHttpMessageHandler mockClientHandler = new MockHttpMessageHandler(); + WebApplicationFactory factory = new TestWebApplicationFactory() + .WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => { - builder - .AddSitecoreLayoutService() + services.AddRouting(); + services.AddControllersWithViews(); + services.AddSitecoreLayoutService() .AddHttpHandler("valid", _ => new HttpClient(mockClientHandler) { BaseAddress = new Uri("http://layout.service") }) .MapFromRequest((layoutRequest, httpMessage) => httpMessage.Headers.Add("test", layoutRequest["invalidkey"]!.ToString())) .AsDefaultHandler(); - }) - .Configure(app => + + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => { + app.UseRouting(); app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); }); - - TestServer server = testHostBuilder.BuildServer(new Uri("http://localhost")); + }); f.Inject(mockClientHandler); - f.Inject(server); + f.Inject(factory); }; [Theory] [AutoNSubstituteData(nameof(InvalidHttpMessageConfiguration))] - public async Task HttpMessageConfigurationError_Returns_SitecoreLayoutServiceMessageConfigurationException(TestServer server, MockHttpMessageHandler clientHandler) + public async Task HttpMessageConfigurationError_Returns_SitecoreLayoutServiceMessageConfigurationException(TestWebApplicationFactory factory, MockHttpMessageHandler clientHandler) { // Arrange clientHandler.Responses.Push(new HttpResponseMessage @@ -100,7 +118,33 @@ public async Task HttpMessageConfigurationError_Returns_SitecoreLayoutServiceMes StatusCode = HttpStatusCode.OK }); - ISitecoreLayoutClient layoutClient = server.Services.GetRequiredService(); + WebApplicationFactory configuredFactory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services.AddRouting(); + services.AddControllersWithViews(); + services.AddLogging(); + services.AddSitecoreLayoutService() + .AddHttpHandler("valid", _ => new HttpClient(clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .MapFromRequest((layoutRequest, httpMessage) => httpMessage.Headers.Add("test", layoutRequest["invalidkey"]!.ToString())) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + + // Ensure host is started so services are available + configuredFactory.CreateClient(); + + ISitecoreLayoutClient layoutClient = configuredFactory.Services.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -114,12 +158,18 @@ public async Task HttpMessageConfigurationError_Returns_SitecoreLayoutServiceMes response.Errors.Should().ContainSingle(e => e.GetType() == typeof(SitecoreLayoutServiceMessageConfigurationException)); } - [Theory] - [AutoNSubstituteData(nameof(InvalidHttpClient))] - public async Task HttpRequestTimeoutError_Returns_CouldNotContactSitecoreLayoutServiceClientException(TestServer server) + [Fact] + public async Task HttpRequestTimeoutError_Returns_CouldNotContactSitecoreLayoutServiceClientException() { // Arrange - ISitecoreLayoutClient layoutClient = server.Services.GetRequiredService(); + // Build a local service provider with the layout client registered so tests are independent + IServiceCollection services = new ServiceCollection(); + services.AddLogging(); + services.AddSitecoreLayoutService() + .AddHttpHandler("invalid", _ => new HttpClient { BaseAddress = new Uri("http://invalid.url") }) + .AsDefaultHandler(); + IServiceProvider provider = services.BuildServiceProvider(); + ISitecoreLayoutClient layoutClient = provider.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -135,7 +185,7 @@ public async Task HttpRequestTimeoutError_Returns_CouldNotContactSitecoreLayoutS [Theory] [AutoNSubstituteData(nameof(ValidHttpClient))] - public async Task HttpResponse50xErrors_Return_InvalidResponseSitecoreLayoutServiceClientException(TestServer server, MockHttpMessageHandler clientHandler) + public async Task HttpResponse50xErrors_Return_InvalidResponseSitecoreLayoutServiceClientException(MockHttpMessageHandler clientHandler) { // Arrange HttpStatusCode[] responseStatuses = @@ -160,7 +210,14 @@ public async Task HttpResponse50xErrors_Return_InvalidResponseSitecoreLayoutServ StatusCode = responseStatus }); - ISitecoreLayoutClient layoutClient = server.Services.GetRequiredService(); + // Build a local service provider with the layout client registered so tests are independent + IServiceCollection services = new ServiceCollection(); + services.AddLogging(); + services.AddSitecoreLayoutService() + .AddHttpHandler("valid", _ => new HttpClient(clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + IServiceProvider provider = services.BuildServiceProvider(); + ISitecoreLayoutClient layoutClient = provider.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -185,7 +242,7 @@ public async Task HttpResponse50xErrors_Return_InvalidResponseSitecoreLayoutServ [Theory] [AutoNSubstituteData(nameof(ValidHttpClient))] - public async Task HttpResponse40xErrors_Return_InvalidRequestSitecoreLayoutServiceClientException(TestServer server, MockHttpMessageHandler clientHandler) + public async Task HttpResponse40xErrors_Return_InvalidRequestSitecoreLayoutServiceClientException(MockHttpMessageHandler clientHandler) { // Arrange HttpStatusCode[] responseStatuses = @@ -225,7 +282,14 @@ public async Task HttpResponse40xErrors_Return_InvalidRequestSitecoreLayoutServi StatusCode = responseStatus }); - ISitecoreLayoutClient layoutClient = server.Services.GetRequiredService(); + // Build a local service provider with the layout client registered so tests are independent + IServiceCollection services = new ServiceCollection(); + services.AddLogging(); + services.AddSitecoreLayoutService() + .AddHttpHandler("valid", _ => new HttpClient(clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + IServiceProvider provider = services.BuildServiceProvider(); + ISitecoreLayoutClient layoutClient = provider.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -247,7 +311,7 @@ public async Task HttpResponse40xErrors_Return_InvalidRequestSitecoreLayoutServi [Theory] [AutoNSubstituteData(nameof(ValidHttpClient))] - public async Task HttpResponse404Error_Returns_ContentAndItemNotFoundSitecoreLayoutServiceClientException(TestServer server, MockHttpMessageHandler clientHandler) + public async Task HttpResponse404Error_Returns_ContentAndItemNotFoundSitecoreLayoutServiceClientException(MockHttpMessageHandler clientHandler) { // Arrange const HttpStatusCode responseStatus = HttpStatusCode.NotFound; @@ -258,7 +322,14 @@ public async Task HttpResponse404Error_Returns_ContentAndItemNotFoundSitecoreLay Content = new StringContent("""{ "sitecore": { "sitecoredata": { "context": { "site": { "name": "404test" }}}}}""") }); - ISitecoreLayoutClient layoutClient = server.Services.GetRequiredService(); + // Build a local service provider with the layout client registered so tests are independent + IServiceCollection services = new ServiceCollection(); + services.AddLogging(); + services.AddSitecoreLayoutService() + .AddHttpHandler("valid", _ => new HttpClient(clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + IServiceProvider provider = services.BuildServiceProvider(); + ISitecoreLayoutClient layoutClient = provider.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -281,7 +352,7 @@ public async Task HttpResponse404Error_Returns_ContentAndItemNotFoundSitecoreLay [Theory] [AutoNSubstituteData(nameof(ValidHttpClient))] - public async Task HttpResponseDeserializationError_Returns_InvalidResponseSitecoreLayoutServiceClientException(TestServer server, MockHttpMessageHandler clientHandler) + public async Task HttpResponseDeserializationError_Returns_InvalidResponseSitecoreLayoutServiceClientException(MockHttpMessageHandler clientHandler) { // Arrange HttpStatusCode responseStatus = HttpStatusCode.NotFound; @@ -292,7 +363,14 @@ public async Task HttpResponseDeserializationError_Returns_InvalidResponseSiteco Content = new StringContent("invalid json") }); - ISitecoreLayoutClient layoutClient = server.Services.GetRequiredService(); + // Build a local service provider with the layout client registered so tests are independent + IServiceCollection services = new ServiceCollection(); + services.AddLogging(); + services.AddSitecoreLayoutService() + .AddHttpHandler("valid", _ => new HttpClient(clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + IServiceProvider provider = services.BuildServiceProvider(); + ISitecoreLayoutClient layoutClient = provider.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -308,7 +386,7 @@ public async Task HttpResponseDeserializationError_Returns_InvalidResponseSiteco [Theory] [AutoNSubstituteData(nameof(ValidHttpClient))] - public async Task HttpResponse10xErrors_Return_SitecoreLayoutServiceClientException(TestServer server, MockHttpMessageHandler clientHandler) + public async Task HttpResponse10xErrors_Return_SitecoreLayoutServiceClientException(MockHttpMessageHandler clientHandler) { // Arrange HttpStatusCode[] responseStatuses = @@ -326,7 +404,14 @@ public async Task HttpResponse10xErrors_Return_SitecoreLayoutServiceClientExcept StatusCode = responseStatus }); - ISitecoreLayoutClient layoutClient = server.Services.GetRequiredService(); + // Build a local service provider with the layout client registered so tests are independent + IServiceCollection services = new ServiceCollection(); + services.AddLogging(); + services.AddSitecoreLayoutService() + .AddHttpHandler("valid", _ => new HttpClient(clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + IServiceProvider provider = services.BuildServiceProvider(); + ISitecoreLayoutClient layoutClient = provider.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -348,7 +433,7 @@ public async Task HttpResponse10xErrors_Return_SitecoreLayoutServiceClientExcept [Theory] [AutoNSubstituteData(nameof(ValidHttpClient))] - public async Task HttpResponse30xErrors_Return_SitecoreLayoutServiceClientException(TestServer server, MockHttpMessageHandler clientHandler) + public async Task HttpResponse30xErrors_Return_SitecoreLayoutServiceClientException(MockHttpMessageHandler clientHandler) { // Arrange HttpStatusCode[] responseStatuses = @@ -376,7 +461,14 @@ public async Task HttpResponse30xErrors_Return_SitecoreLayoutServiceClientExcept StatusCode = responseStatus }); - ISitecoreLayoutClient layoutClient = server.Services.GetRequiredService(); + // Build a local service provider with the layout client registered so tests are independent + IServiceCollection services = new ServiceCollection(); + services.AddLogging(); + services.AddSitecoreLayoutService() + .AddHttpHandler("valid", _ => new HttpClient(clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + IServiceProvider provider = services.BuildServiceProvider(); + ISitecoreLayoutClient layoutClient = provider.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -398,14 +490,36 @@ public async Task HttpResponse30xErrors_Return_SitecoreLayoutServiceClientExcept [Theory] [AutoNSubstituteData(nameof(ValidHttpClient))] - public async Task ErrorView_Returns_InvalidResponseSitecoreLayoutServiceClientException(TestServer server, MockHttpMessageHandler clientHandler) + public async Task ErrorView_Returns_InvalidResponseSitecoreLayoutServiceClientException(TestWebApplicationFactory factory, MockHttpMessageHandler clientHandler) { clientHandler.Responses.Push(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest }); - HttpClient client = server.CreateClient(); + WebApplicationFactory configuredFactory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services.AddRouting(); + services.AddControllersWithViews(); + services.AddLogging(); + services.AddSitecoreLayoutService() + .AddHttpHandler("valid", _ => new HttpClient(clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + + HttpClient client = configuredFactory.CreateClient(); // Act string response = await client.GetStringAsync("Error"); From 34535ad4679c14db82c1e7b9c717ca5ccb66188c Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Wed, 17 Sep 2025 14:57:20 +0530 Subject: [PATCH 18/41] Migrate GlobalMiddlewareFixture --- .../Fixtures/GlobalMiddlewareFixture.cs | 70 ++++++++++++------- 1 file changed, 43 insertions(+), 27 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/GlobalMiddlewareFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/GlobalMiddlewareFixture.cs index c0c3243..820ed1d 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/GlobalMiddlewareFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/GlobalMiddlewareFixture.cs @@ -1,5 +1,7 @@ -using System.Net; +using System; +using System.Net; using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -15,7 +17,7 @@ public class GlobalMiddlewareFixture : IDisposable private const string GlobalMiddlewareController = "UsingGlobalMiddleware"; - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly MockHttpMessageHandler _mockClientHandler; @@ -23,27 +25,9 @@ public class GlobalMiddlewareFixture : IDisposable public GlobalMiddlewareFixture() { - TestServerBuilder testHostBuilder = new(); _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => - { - options.AddDefaultPartialView("_ComponentNotFound"); - options.AddPostRenderingAction(httpContext => httpContext.Response.Headers.Append(CustomHeaderName, "value")); - }); - }) - .Configure(app => - { - app.UseSitecoreRenderingEngine(); - }); - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + _factory = BuildGlobalMiddlewareWebApplicationFactory(); } [Fact] @@ -54,7 +38,7 @@ public async Task HttpClient_IsInvoked() StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); await client.GetAsync(GlobalMiddlewareController); _mockClientHandler.WasInvoked.Should().BeTrue(); @@ -65,7 +49,7 @@ public async Task Controller_ReturnsCorrectContent() { _mockClientHandler.Responses.Push(new HttpResponseMessage { StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); string response = await client.GetStringAsync(GlobalMiddlewareController); response.Should().Be("\"success\""); @@ -76,7 +60,7 @@ public async Task HttpClient_LayoutServiceUriMapped() { _mockClientHandler.Responses.Push(new HttpResponseMessage { StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); await client.GetAsync(GlobalMiddlewareController); _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should() @@ -92,7 +76,7 @@ public async Task HttpClient_MissingComponent() Content = new StringContent(Serializer.Serialize(CannedResponses.WithMissingComponent)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); string response = await client.GetStringAsync("WithRoute"); response.Should().Contain("ComponentIsMissing"); @@ -106,7 +90,7 @@ public async Task HttpClient_PostRenderingEnginActionIsExecuted() StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); HttpResponseMessage response = await client.GetAsync(GlobalMiddlewareController); response.Headers.Contains(CustomHeaderName).Should().BeTrue(); @@ -114,8 +98,40 @@ public async Task HttpClient_PostRenderingEnginActionIsExecuted() public void Dispose() { - _server.Dispose(); + _factory.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildGlobalMiddlewareWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddRouting(); + services.AddControllersWithViews(); + + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultPartialView("_ComponentNotFound"); + options.AddPostRenderingAction(httpContext => httpContext.Response.Headers.Append(CustomHeaderName, "value")); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + } } \ No newline at end of file From f9549155e9154bc1bb1c2a8178c917485cd7a5a2 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Wed, 17 Sep 2025 15:12:16 +0530 Subject: [PATCH 19/41] Migrate SitecoreLayoutClientBuilderExtensionsFixture --- ...oreLayoutClientBuilderExtensionsFixture.cs | 52 +++++++++++-------- 1 file changed, 31 insertions(+), 21 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SitecoreLayoutClientBuilderExtensionsFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SitecoreLayoutClientBuilderExtensionsFixture.cs index 85fd063..b76c619 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SitecoreLayoutClientBuilderExtensionsFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SitecoreLayoutClientBuilderExtensionsFixture.cs @@ -1,4 +1,5 @@ using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Options; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; @@ -13,36 +14,19 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures; public class SitecoreLayoutClientBuilderExtensionsFixture : IDisposable { private readonly MockHttpMessageHandler _messageHandler; - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; public SitecoreLayoutClientBuilderExtensionsFixture() { - TestServerBuilder testHostBuilder = new(); _messageHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - ISitecoreLayoutClientBuilder lsc = builder - .AddSitecoreLayoutService(); - - lsc.AddHttpHandler("mock", _ => new HttpClient(_messageHandler) { BaseAddress = new Uri("http://layout.service") }); - - lsc.AddHttpHandler("otherMock", _ => new HttpClient(_messageHandler) { BaseAddress = new Uri("http://layout.service") }) - .AsDefaultHandler(); - }) - .Configure(app => - { - app.UseSitecoreRenderingEngine(); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + _factory = BuildSitecoreLayoutClientBuilderWebApplicationFactory(); } [Fact] public void DefaultHandler_SetsSitecoreLayoutServiceOptions() { // Act - IOptions layoutService = _server.Services.GetRequiredService>(); + IOptions layoutService = _factory.Services.GetRequiredService>(); // Assert layoutService.Value.DefaultHandler.Should().Be("otherMock"); @@ -51,7 +35,33 @@ public void DefaultHandler_SetsSitecoreLayoutServiceOptions() public void Dispose() { _messageHandler.Dispose(); - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildSitecoreLayoutClientBuilderWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + ISitecoreLayoutClientBuilder lsc = services + .AddSitecoreLayoutService(); + + lsc.AddHttpHandler("mock", _ => new HttpClient(_messageHandler) { BaseAddress = new Uri("http://layout.service") }); + + lsc.AddHttpHandler("otherMock", _ => new HttpClient(_messageHandler) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => + { + app.UseSitecoreRenderingEngine(); + }); + }); + } } \ No newline at end of file From 459624d1a75c2f3ccc16ca5e176daf6828239de5 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Wed, 17 Sep 2025 15:49:17 +0530 Subject: [PATCH 20/41] Migtrate RequestDefaultsConfigurationFixture --- .../RequestDefaultsConfigurationFixture.cs | 99 ++++++++++--------- 1 file changed, 54 insertions(+), 45 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs index 387a745..040e364 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs @@ -1,5 +1,7 @@ using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.LayoutService.Client.Interfaces; @@ -14,50 +16,19 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures; public class RequestDefaultsConfigurationFixture : IDisposable { private readonly MockHttpMessageHandler _clientHandler; - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; public RequestDefaultsConfigurationFixture() { - TestServerBuilder testHostBuilder = new(); _clientHandler = new MockHttpMessageHandler(); - - testHostBuilder - .ConfigureServices(builder => - { - ISitecoreLayoutClientBuilder lsc = builder - .AddSitecoreLayoutService() - .WithDefaultRequestOptions(request => - { - request["key1"] = "value1"; - request["key2"] = "value2"; - }); - - lsc.AddHttpHandler("mock", _ => new HttpClient(_clientHandler) { BaseAddress = new Uri("http://layout.service") }) - .WithRequestOptions(request => - { - request["key1"] = "value3"; - request["key3"] = "value4"; - }) - .AsDefaultHandler(); - - lsc.AddHttpHandler("mockwithoutoptions", _ => new HttpClient(_clientHandler) { BaseAddress = new Uri("http://layout.service") }); - - builder - .AddSitecoreRenderingEngine(options => options.MapToRequest((http, sc) => { sc.Path(http.Path); })); - }) - .Configure(app => - { - app.UseSitecoreRenderingEngine(); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + _factory = BuildRequestDefaultsConfigurationWebApplicationFactory(); } [Fact] public async Task Request_OnlyGlobalOptionsProvided_FinalRequestUsesGlobalOptions() { // Arrange - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("test"); @@ -74,9 +45,9 @@ public async Task Request_OnlyGlobalOptionsProvided_FinalRequestUsesGlobalOption public async Task Request_OnlyHandlerOptionsProvided_FinalRequestUsesHandlerOptions() { // Arrange - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); - SitecoreLayoutRequest request = []; + SitecoreLayoutRequest request = new SitecoreLayoutRequest(); // Act SitecoreLayoutResponse response = await layoutClient.Request(request); @@ -90,7 +61,7 @@ public async Task Request_OnlyHandlerOptionsProvided_FinalRequestUsesHandlerOpti public async Task Request_OnlyRequestParameterProvided_FinalRequestUsesRequestParameter() { // Arrange - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new() { @@ -109,9 +80,9 @@ public async Task Request_OnlyRequestParameterProvided_FinalRequestUsesRequestPa public async Task Request_GlobalAndHandlerOptionsProvided_FinalRequestUsesHandlerOptions() { // Arrange - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); - SitecoreLayoutRequest request = []; + SitecoreLayoutRequest request = new SitecoreLayoutRequest(); // Act SitecoreLayoutResponse response = await layoutClient.Request(request); @@ -125,7 +96,7 @@ public async Task Request_GlobalAndHandlerOptionsProvided_FinalRequestUsesHandle public async Task Request_GlobalOptionsAndRequestParametersProvided_FinalRequestUsesRequestParameters() { // Arrange - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new() { { "key2", "requestvalue" } }; @@ -141,7 +112,7 @@ public async Task Request_GlobalOptionsAndRequestParametersProvided_FinalRequest public async Task Request_GlobalAndHandlerOptionsAndRequestParametersProvided_FinalRequestUsesRequestParameters() { // Arrange - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new() { { "key1", "requestvalue" } }; @@ -157,7 +128,7 @@ public async Task Request_GlobalAndHandlerOptionsAndRequestParametersProvided_Fi public async Task Request_GlobalAndHandlerAndRequestSetDifferentParameters_FinalRequestUsesAllParameters() { // Arrange - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new() { { "requestKey", "requestValue" } }; @@ -175,7 +146,7 @@ public async Task Request_GlobalAndHandlerAndRequestSetDifferentParameters_Final public async Task Request_GlobalOptionsProvidedRequestSetsParameterToNull_FinalRequestExcludesParameter() { // Arrange - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new() { @@ -194,7 +165,7 @@ public async Task Request_GlobalOptionsProvidedRequestSetsParameterToNull_FinalR public async Task Request_HandlerOptionsProvidedRequestSetsParameterToNull_FinalRequestExcludesParameter() { // Arrange - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new() { @@ -212,7 +183,45 @@ public async Task Request_HandlerOptionsProvidedRequestSetsParameterToNull_Final public void Dispose() { _clientHandler.Dispose(); - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildRequestDefaultsConfigurationWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + ISitecoreLayoutClientBuilder lsc = services + .AddSitecoreLayoutService() + .WithDefaultRequestOptions(request => + { + request["key1"] = "value1"; + request["key2"] = "value2"; + }); + + lsc.AddHttpHandler("mock", _ => new HttpClient(_clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .WithRequestOptions(request => + { + request["key1"] = "value3"; + request["key3"] = "value4"; + }) + .AsDefaultHandler(); + + lsc.AddHttpHandler("mockwithoutoptions", _ => new HttpClient(_clientHandler) { BaseAddress = new Uri("http://layout.service") }); + + services.AddSitecoreRenderingEngine(options => options.MapToRequest((http, sc) => { sc.Path(http.Path); })); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + } } \ No newline at end of file From ccd8ef74115437979fad7a24e91ba8044ac867ad Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Wed, 17 Sep 2025 15:50:59 +0530 Subject: [PATCH 21/41] Remove unused package- RequestDefaultsConfigurationFixture --- .../Fixtures/RequestDefaultsConfigurationFixture.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs index 040e364..367cf12 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs @@ -1,7 +1,6 @@ using AwesomeAssertions; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.LayoutService.Client.Interfaces; From 6eba6ef702bd2a1d1973e8760d9124a5bf538e47 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Wed, 17 Sep 2025 17:05:25 +0530 Subject: [PATCH 22/41] Migrate RequestExtensionsFixture --- .../Fixtures/RequestExtensionsFixture.cs | 55 ++++++++++++------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestExtensionsFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestExtensionsFixture.cs index 1ffa0e9..c68d6ef 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestExtensionsFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestExtensionsFixture.cs @@ -1,6 +1,8 @@ using System.Net; using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.LayoutService.Client.Interfaces; @@ -14,26 +16,12 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures; public class RequestExtensionsFixture : IDisposable { private readonly MockHttpMessageHandler _clientHandler; - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; public RequestExtensionsFixture() { - TestServerBuilder testHostBuilder = new(); _clientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_clientHandler) { BaseAddress = new Uri("http://layout.service") }) - .AsDefaultHandler(); - }) - .Configure(app => - { - app.UseSitecoreRenderingEngine(); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + _factory = BuildRequestExtensionsWebApplicationFactory(); } [Fact] @@ -44,7 +32,7 @@ public async Task Properties_WithPath_AddedToRequest() StatusCode = HttpStatusCode.OK }); - ISitecoreLayoutClient layoutService = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutService = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("UsingGlobalMiddleware"); @@ -63,7 +51,7 @@ public async Task Properties_WithLanguage_AddedToRequest() StatusCode = HttpStatusCode.OK }); - ISitecoreLayoutClient layoutService = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutService = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("UsingGlobalMiddleware") @@ -83,7 +71,7 @@ public async Task Properties_WithApiKey_AddedToRequest() StatusCode = HttpStatusCode.OK }); - ISitecoreLayoutClient layoutService = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutService = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("UsingGlobalMiddleware") @@ -103,7 +91,7 @@ public async Task Properties_WithSiteName_AddedToRequest() StatusCode = HttpStatusCode.OK }); - ISitecoreLayoutClient layoutService = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutService = _factory.Services.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() .Path("UsingGlobalMiddleware") @@ -118,7 +106,32 @@ public async Task Properties_WithSiteName_AddedToRequest() public void Dispose() { _clientHandler.Dispose(); - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildRequestExtensionsWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_clientHandler) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => options.MapToRequest((http, sc) => { sc.Path(http.Path); })); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + } } \ No newline at end of file From 8e5f51901d2ae054f3ae43646a50d8a785177da2 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Wed, 17 Sep 2025 17:14:07 +0530 Subject: [PATCH 23/41] Migrate RequestMappingFixture --- .../Fixtures/RequestMappingFixture.cs | 115 ++++++++++-------- 1 file changed, 64 insertions(+), 51 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestMappingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestMappingFixture.cs index 9162b96..f6bf771 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestMappingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestMappingFixture.cs @@ -1,6 +1,8 @@ using System.Net; using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Primitives; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -21,7 +23,7 @@ public class RequestMappingFixture : IDisposable private const string QueryStringTestActionMethod = "QueryStringTest"; - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly MockHttpMessageHandler _mockClientHandler; @@ -29,51 +31,8 @@ public class RequestMappingFixture : IDisposable public RequestMappingFixture() { - TestServerBuilder testHostBuilder = new(); _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .MapFromRequest((layoutRequest, httpMessage) => - { - if (layoutRequest.TryGetValue("Authorization", out object? auth)) - { - httpMessage.Headers.Add("Authorization", auth!.ToString()); - } - - if (layoutRequest.TryGetValue("AspNetCookie", out object? aspnet)) - { - httpMessage.Headers.Add("Cookie", aspnet!.ToString()); - } - - httpMessage.RequestUri = layoutRequest.BuildDefaultSitecoreLayoutRequestUri(httpMessage.RequestUri!, ["param1", "param2"]); - }) - .AsDefaultHandler(); - - builder.AddSitecoreRenderingEngine(options => - options.MapToRequest((httpRequest, layoutRequest) => - { - layoutRequest.Path(httpRequest.Path); - foreach (KeyValuePair q in httpRequest.Query) - { - layoutRequest.Add(q.Key, q.Value.ToString()); - } - - layoutRequest.Add("testnullvalue", null); - - // simulate there is an authorization cookie in the HTTP request - httpRequest.Headers.Append("Authorization", TestAuthHeader); - layoutRequest.Add("Authorization", httpRequest.Headers.Authorization); - - layoutRequest.Add("AspNetCookie", TestCookie); - })); - }) - .Configure(_ => { }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + _factory = BuildRequestMappingWebApplicationFactory(); } [Fact] @@ -87,7 +46,7 @@ public async Task HttpRequest_WithValidQueryStringParams_GeneratesCorrectLayoutS StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act await client.GetAsync(MiddlewareController + "/" + QueryStringTestActionMethod + "?" + testQueryString); @@ -108,7 +67,7 @@ public async Task HttpRequest_WithInvalidQueryStringParams_GeneratesCorrectLayou StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act await client.GetAsync(MiddlewareController + "/" + QueryStringTestActionMethod + "?" + testQueryString); @@ -129,7 +88,7 @@ public async Task HttpRequest_WithUnencodedQueryStringParams_GeneratesCorrectLay StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act await client.GetAsync(MiddlewareController + "/" + QueryStringTestActionMethod + "?" + testQueryString); @@ -145,7 +104,7 @@ public async Task HttpRequest_WithAuthenticationHeaders_HeadersMappedToLayoutSer // Arrange _mockClientHandler.Responses.Push(new HttpResponseMessage { StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act await client.GetAsync(MiddlewareController + "/" + QueryStringTestActionMethod) @@ -162,7 +121,7 @@ public async Task HttpRequest_WithCookie_CookieMappedToLayoutServiceRequest() // Arrange _mockClientHandler.Responses.Push(new HttpResponseMessage { StatusCode = HttpStatusCode.OK }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act await client.GetAsync(MiddlewareController + "/" + QueryStringTestActionMethod) @@ -175,8 +134,62 @@ await client.GetAsync(MiddlewareController + "/" + QueryStringTestActionMethod) public void Dispose() { - _server.Dispose(); + _factory.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildRequestMappingWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .MapFromRequest((layoutRequest, httpMessage) => + { + if (layoutRequest.TryGetValue("Authorization", out object? auth)) + { + httpMessage.Headers.Add("Authorization", auth!.ToString()); + } + + if (layoutRequest.TryGetValue("AspNetCookie", out object? aspnet)) + { + httpMessage.Headers.Add("Cookie", aspnet!.ToString()); + } + + httpMessage.RequestUri = layoutRequest.BuildDefaultSitecoreLayoutRequestUri(httpMessage.RequestUri!, new[] { "param1", "param2" }); + }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + options.MapToRequest((httpRequest, layoutRequest) => + { + layoutRequest.Path(httpRequest.Path); + foreach (KeyValuePair q in httpRequest.Query) + { + layoutRequest.Add(q.Key, q.Value.ToString()); + } + + layoutRequest.Add("testnullvalue", null); + + // simulate there is an authorization cookie in the HTTP request + httpRequest.Headers.Append("Authorization", TestAuthHeader); + layoutRequest.Add("Authorization", httpRequest.Headers.Authorization); + + layoutRequest.Add("AspNetCookie", TestCookie); + })); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + } } \ No newline at end of file From 7bcfb2f4e95e619b9435157c4fc8bd9a99a5aa04 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Thu, 18 Sep 2025 10:05:35 +0530 Subject: [PATCH 24/41] Migrate Tracking Fixtures --- .../Tracking/AttributeBasedTrackingFixture.cs | 81 +++++++++------- .../Fixtures/Tracking/TrackingFixture.cs | 94 +++++++++++-------- .../Fixtures/Tracking/TrackingProxyFixture.cs | 49 ++++++---- 3 files changed, 135 insertions(+), 89 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/AttributeBasedTrackingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/AttributeBasedTrackingFixture.cs index c1e0a9b..a072be8 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/AttributeBasedTrackingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/AttributeBasedTrackingFixture.cs @@ -1,5 +1,6 @@ using System.Net; using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -24,7 +25,7 @@ public class AttributeBasedTrackingFixture : IDisposable "SC_ANALYTICS_GLOBAL_COOKIE=0f82f53555ce4304a1ee8ae99ab9f9a8|False; expires = Fri, 15 - Mar - 2030 13:15:08 GMT; path =/; HttpOnly" ]; - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly MockHttpMessageHandler _mockClientHandler; @@ -34,35 +35,8 @@ public class AttributeBasedTrackingFixture : IDisposable public AttributeBasedTrackingFixture() { - TestServerBuilder testHostBuilder = new(); _mockClientHandler = new MockHttpMessageHandler(); - - _ = testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) - { - BaseAddress = _layoutServiceUri - }) - .AsDefaultHandler(); - - builder.AddSitecoreRenderingEngine(options => - { - options - .AddDefaultComponentRenderer(); - }) - .WithTracking(); - - builder.AddSitecoreVisitorIdentification(o => o.SitecoreInstanceUri = _cmInstanceUri); - }) - .Configure(app => - { - app.UseSitecoreVisitorIdentification(); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + _factory = BuildAttributeBasedTrackingWebApplicationFactory(); } [Fact] @@ -80,7 +54,7 @@ public async Task SitecoreLayoutServiceResponseMetadata_ProxyCookies() } }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act HttpResponseMessage response = await client.GetAsync(new Uri("/AttributeBased", UriKind.Relative)); @@ -100,7 +74,7 @@ public async Task SitecoreLayoutServer_ProxyCookiesFromRequest() Content = new StringContent(Serializer.Serialize(CannedResponses.WithVisitorIdentificationLayoutPlaceholder)), }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/AttributeBased", UriKind.Relative)); request.Headers.Add("Cookie", ["ASP.NET_SessionId=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax", "SC_ANALYTICS_GLOBAL_COOKIE=0f82f53555ce4304a1ee8ae99ab9f9a8|False; expires = Fri, 15 - Mar - 2030 13:15:08 GMT; path =/; HttpOnly"]); @@ -124,7 +98,7 @@ public async Task SitecoreRequests_ToLayouts_MustIncludeVisitorIdentificationJs( Content = new StringContent(Serializer.Serialize(CannedResponses.WithVisitorIdentificationLayoutPlaceholder)), }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/AttributeBased", UriKind.Relative)); // Act @@ -138,8 +112,49 @@ public async Task SitecoreRequests_ToLayouts_MustIncludeVisitorIdentificationJs( public void Dispose() { - _server.Dispose(); + _factory.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildAttributeBasedTrackingWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddRouting(); + services.AddControllersWithViews(); + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) + { + BaseAddress = _layoutServiceUri + }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddDefaultComponentRenderer(); + }) + .WithTracking(); + + services.AddSitecoreVisitorIdentification(o => o.SitecoreInstanceUri = _cmInstanceUri); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreVisitorIdentification(); + + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingFixture.cs index f5db9a0..cd1e1d1 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingFixture.cs @@ -1,6 +1,7 @@ using System.Net; using AwesomeAssertions; using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -25,7 +26,7 @@ public class TrackingFixture : IDisposable "SC_ANALYTICS_GLOBAL_COOKIE=0f82f53555ce4304a1ee8ae99ab9f9a8|False; expires = Fri, 15 - Mar - 2030 13:15:08 GMT; path =/; HttpOnly" ]; - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly MockHttpMessageHandler _mockClientHandler; @@ -35,39 +36,8 @@ public class TrackingFixture : IDisposable public TrackingFixture() { - TestServerBuilder testHostBuilder = new(); _mockClientHandler = new MockHttpMessageHandler(); - - _ = testHostBuilder - .ConfigureServices(builder => - { - builder.Configure(options => - { - options.ForwardedHeaders = ForwardedHeaders.XForwardedFor; - }); - - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - builder.AddSitecoreRenderingEngine(options => - { - options - .AddDefaultComponentRenderer(); - }) - .WithTracking(); - - builder.AddSitecoreVisitorIdentification(o => o.SitecoreInstanceUri = _cmInstanceUri); - }) - .Configure(app => - { - app.UseForwardedHeaders(); - app.UseSitecoreVisitorIdentification(); - app.UseSitecoreRenderingEngine(); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + _factory = BuildTrackingWebApplicationFactory(); } [Fact] @@ -80,7 +50,7 @@ public async Task SitecoreResponse_WithRobotDetection_MustIncludeVisitorIdentifi Content = new StringContent(Serializer.Serialize(CannedResponses.WithVisitorIdentificationLayoutPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); // Act @@ -108,7 +78,7 @@ public async Task SitecoreRenderingHostResponseMetadata_ProxyCookiesWithLSRespon } }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act HttpRequestMessage browserRequest = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); @@ -134,7 +104,7 @@ public async Task SitecoreLayoutServer_ProxyCookiesFromRequest() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage browserRequest = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); browserRequest.Headers.Add("Cookie", ["ASP.NET_SessionId=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax", "SC_ANALYTICS_GLOBAL_COOKIE=0f82f53555ce4304a1ee8ae99ab9f9a8|False; expires = Fri, 15 - Mar - 2030 13:15:08 GMT; path =/; HttpOnly"]); @@ -159,7 +129,7 @@ public async Task SitecoreLayoutServiceRequest_IPAddress_MustBeResolvedCorrectly Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); request.Headers.Add("X-Forwarded-For", "192.168.1.0, 172.217.16.14"); @@ -187,7 +157,7 @@ public async Task SitecoreLayoutServiceResponseMetadata_ProxyCookies() } }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act HttpResponseMessage response = await client.GetAsync(new Uri("/", UriKind.Relative)); @@ -200,8 +170,54 @@ public async Task SitecoreLayoutServiceResponseMetadata_ProxyCookies() public void Dispose() { - _server.Dispose(); + _factory.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildTrackingWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor; + }); + + services.AddRouting(); + services.AddControllersWithViews(); + + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddDefaultComponentRenderer(); + }) + .WithTracking(); + + services.AddSitecoreVisitorIdentification(o => o.SitecoreInstanceUri = _cmInstanceUri); + }); + + builder.Configure(app => + { + app.UseForwardedHeaders(); + app.UseRouting(); + app.UseSitecoreVisitorIdentification(); + app.UseSitecoreRenderingEngine(); + + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingProxyFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingProxyFixture.cs index 5715e8e..6771efe 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingProxyFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingProxyFixture.cs @@ -1,6 +1,7 @@ using System.Net; using AwesomeAssertions; using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -15,62 +16,76 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Tra public class TrackingProxyFixture : IDisposable { - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); private readonly Uri _cmInstanceUri = new("http://layout.service"); public TrackingProxyFixture() { - TestServerBuilder testHostBuilder = new(); _mockClientHandler.Responses.Push(new HttpResponseMessage(HttpStatusCode.OK)); + _factory = BuildTrackingProxyWebApplicationFactory(); + } + + private WebApplicationFactory BuildTrackingProxyWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); - _ = testHostBuilder - .ConfigureServices(builder => + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => { - builder.Configure(options => + services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; }); - builder + services.AddRouting(); + services.AddControllersWithViews(); + + services .AddSitecoreLayoutService() .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => + services.AddSitecoreRenderingEngine(options => { options.AddDefaultComponentRenderer(); }) .WithTracking(); - builder.AddSitecoreVisitorIdentification(options => + services.AddSitecoreVisitorIdentification(options => { options.SitecoreInstanceUri = _cmInstanceUri; }); - builder.AddSingleton(_ => + services.AddSingleton(_ => { return new CustomHttpClientFactory( - () => - new HttpClient(_mockClientHandler)); + () => new HttpClient(_mockClientHandler)); }); - }) - .Configure(app => + }); + + builder.Configure(app => { app.UseForwardedHeaders(); + app.UseRouting(); app.UseSitecoreVisitorIdentification(); app.UseSitecoreRenderingEngine(); - }); - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); } [Fact] public async Task SitecoreRequests_ToLayouts_MustBeProxied() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/layouts/System/VisitorIdentification.js", UriKind.Relative)); request.Headers.Add("Cookie", ["ASP.NET_SessionId=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax", "SC_ANALYTICS_GLOBAL_COOKIE=0f82f53555ce4304a1ee8ae99ab9f9a8|False; expires = Fri, 15 - Mar - 2030 13:15:08 GMT; path =/; HttpOnly"]); request.Headers.Add("X-Forwarded-For", "172.217.16.14"); @@ -91,7 +106,7 @@ public async Task SitecoreRequests_ToLayouts_MustBeProxied() public void Dispose() { - _server.Dispose(); + _factory.Dispose(); _mockClientHandler.Dispose(); GC.SuppressFinalize(this); } From 2e6b7037e5d40969cc61641a133d15988696749b Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Thu, 18 Sep 2025 10:33:43 +0530 Subject: [PATCH 25/41] Migrate Localization fixtures --- .../AdvanceLocalizationFixture.cs | 43 +++++++++++------- .../DefaultLocalizationFixture.cs | 36 +++++++++------ .../Localization/LocalizationFixture.cs | 40 +++++++++++------ ...lizationUsingAttributeMiddlewareFixture.cs | 44 ++++++++++++------- 4 files changed, 103 insertions(+), 60 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs index 5483406..2c9e24d 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs @@ -4,6 +4,7 @@ using HtmlAgilityPack; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc.Razor; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -15,31 +16,40 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Loc public class AdvanceLocalizationFixture : IDisposable { - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly MockHttpMessageHandler _mockClientHandler; private readonly Uri _layoutServiceUri = new("http://layout.service"); public AdvanceLocalizationFixture() { - TestServerBuilder testHostBuilder = new(); _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => + _factory = BuildAdvanceLocalizationWebApplicationFactory(); + } + + private WebApplicationFactory BuildAdvanceLocalizationWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => { - builder.AddLocalization(options => options.ResourcesPath = "Resources"); - builder.AddSitecoreLayoutService() + services.AddLocalization(options => options.ResourcesPath = "Resources"); + services.AddRouting(); + services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); + + services.AddSitecoreLayoutService() .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => + services.AddSitecoreRenderingEngine(options => { options.AddModelBoundView("Component-4", "Component4") .AddDefaultComponentRenderer(); }); - builder.AddMvc() - .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); - }) - .Configure(app => + }); + + builder.Configure(app => { app.UseRouting(); app.UseRequestLocalization(options => @@ -62,8 +72,7 @@ public AdvanceLocalizationFixture() endpoints.MapDefaultControllerRoute(); }); }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + }); } [Fact] @@ -76,7 +85,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act await client.GetStringAsync(new Uri("content/da/UsingGlobalMiddleware", UriKind.Relative)); @@ -94,7 +103,7 @@ public async Task LocalizedRequest_PicksDefaultView() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -118,7 +127,7 @@ public async Task LocalizedRequest_PicksLocalizedView() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("content/da", UriKind.Relative)); @@ -135,7 +144,7 @@ public async Task LocalizedRequest_PicksLocalizedView() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs index 19f429b..ace6556 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs @@ -1,5 +1,6 @@ using System.Net; using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -12,19 +13,28 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Loc public class DefaultLocalizationFixture : IDisposable { - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly MockHttpMessageHandler _mockClientHandler; private readonly Uri _layoutServiceUri = new("http://layout.service"); public DefaultLocalizationFixture() { - TestServerBuilder testHostBuilder = new(); _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => + _factory = BuildDefaultLocalizationWebApplicationFactory(); + } + + private WebApplicationFactory BuildDefaultLocalizationWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => { - builder.AddLocalization(options => options.ResourcesPath = "Resources"); - builder + services.AddLocalization(options => options.ResourcesPath = "Resources"); + services.AddRouting(); + services.AddControllersWithViews(); + services .AddSitecoreLayoutService().WithDefaultRequestOptions(request => { request @@ -32,14 +42,15 @@ public DefaultLocalizationFixture() }) .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => + services.AddSitecoreRenderingEngine(options => { options .AddModelBoundView("Component-4", "Component4") .AddDefaultComponentRenderer(); }); - }) - .Configure(app => + }); + + builder.Configure(app => { app.UseRouting(); @@ -51,8 +62,7 @@ public DefaultLocalizationFixture() endpoints.MapDefaultControllerRoute(); }); }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + }); } [Fact] @@ -65,7 +75,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act await client.GetStringAsync(new Uri("/da/UsingGlobalMiddleware", UriKind.Relative)); @@ -76,7 +86,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs index 871719d..c2eb426 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs @@ -2,6 +2,7 @@ using System.Net; using AwesomeAssertions; using Microsoft.AspNetCore.Localization; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -13,35 +14,47 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Loc public class LocalizationFixture : IDisposable { - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly MockHttpMessageHandler _mockClientHandler; private readonly Uri _layoutServiceUri = new("http://layout.service"); public LocalizationFixture() { - TestServerBuilder testHostBuilder = new(); _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => + _factory = BuildLocalizationWebApplicationFactory(); + } + + private WebApplicationFactory BuildLocalizationWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => { - builder.AddLocalization(options => options.ResourcesPath = "Resources"); - builder + services.AddLocalization(options => options.ResourcesPath = "Resources"); + services.AddRouting(); + services.AddControllersWithViews(); + + services .AddSitecoreLayoutService() .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => + + services.AddSitecoreRenderingEngine(options => { options .AddModelBoundView("Component-4", "Component4") .AddDefaultComponentRenderer(); }); - }) - .Configure(app => + }); + + builder.Configure(app => { app.UseRouting(); app.UseRequestLocalization(options => { - List supportedCultures = [new("en"), new("ru-RU")]; + List supportedCultures = new() { new("en"), new("ru-RU") }; options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); options.SupportedCultures = supportedCultures; @@ -56,8 +69,7 @@ public LocalizationFixture() endpoints.MapDefaultControllerRoute(); }); }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + }); } [Fact] @@ -70,7 +82,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act await client.GetStringAsync(new Uri("/ru-RU/UsingGlobalMiddleware", UriKind.Relative)); @@ -81,7 +93,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs index 6fc2bc6..ada28c4 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs @@ -3,6 +3,7 @@ using System.Net.Http.Headers; using AwesomeAssertions; using Microsoft.AspNetCore.Localization; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -14,30 +15,42 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Loc public class LocalizationUsingAttributeMiddlewareFixture : IDisposable { - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly MockHttpMessageHandler _mockClientHandler; private readonly Uri _layoutServiceUri = new("http://layout.service"); public LocalizationUsingAttributeMiddlewareFixture() { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => + _mockClientHandler = new MockHttpMessageHandler(); + _factory = BuildLocalizationUsingAttributeWebApplicationFactory(); + } + + private WebApplicationFactory BuildLocalizationUsingAttributeWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => { - builder.AddLocalization(options => options.ResourcesPath = "Resources"); - builder + services.AddLocalization(options => options.ResourcesPath = "Resources"); + services.AddRouting(); + services.AddControllersWithViews(); + + services .AddSitecoreLayoutService() .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) .AsDefaultHandler(); - builder.AddSitecoreRenderingEngine(options => + + services.AddSitecoreRenderingEngine(options => { options .AddModelBoundView("Component-4", "Component4") .AddDefaultComponentRenderer(); }); - }) - .Configure(app => + }); + + builder.Configure(app => { app.UseRouting(); app.UseRequestLocalization(options => @@ -55,8 +68,7 @@ public LocalizationUsingAttributeMiddlewareFixture() endpoints.MapDefaultControllerRoute(); }); }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + }); } [Theory] @@ -72,7 +84,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_FromTheR Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act await client.GetStringAsync(new Uri($"/{routeLanguage}/UsingAttribute/UseLocalizeWithAttribute", UriKind.Relative)); @@ -95,7 +107,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_FromAcce Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.Clear(); if (!string.IsNullOrWhiteSpace(acceptLanguageHeader)) @@ -125,7 +137,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_RouteLan Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.Clear(); if (!string.IsNullOrWhiteSpace(acceptLanguageHeader)) @@ -143,7 +155,7 @@ public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage_RouteLan public void Dispose() { _mockClientHandler.Dispose(); - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } } \ No newline at end of file From b93f305a66bb443889462ee7f36ff6023a333cb5 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Thu, 18 Sep 2025 11:24:04 +0530 Subject: [PATCH 26/41] Restructure methods to fix warnings --- .../AdvanceLocalizationFixture.cs | 98 +++++++++---------- .../DefaultLocalizationFixture.cs | 50 +++++----- .../Localization/LocalizationFixture.cs | 50 +++++----- ...lizationUsingAttributeMiddlewareFixture.cs | 92 ++++++++--------- .../Fixtures/Tracking/TrackingProxyFixture.cs | 60 ++++++------ 5 files changed, 175 insertions(+), 175 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs index 2c9e24d..d4a3a7c 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/AdvanceLocalizationFixture.cs @@ -26,55 +26,6 @@ public AdvanceLocalizationFixture() _factory = BuildAdvanceLocalizationWebApplicationFactory(); } - private WebApplicationFactory BuildAdvanceLocalizationWebApplicationFactory() - { - WebApplicationFactory factory = new TestWebApplicationFactory(); - - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services.AddLocalization(options => options.ResourcesPath = "Resources"); - services.AddRouting(); - services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); - - services.AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options.AddModelBoundView("Component-4", "Component4") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseRequestLocalization(options => - { - List supportedCultures = [new("en"), new("da")]; - options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); - options.SupportedCultures = supportedCultures; - options.SupportedUICultures = supportedCultures; - options.UseSitecoreRequestLocalization(); - }); - app.UseSitecoreRenderingEngine(); - - app.UseEndpoints(endpoints => - { - // ReSharper disable once RouteTemplates.RouteParameterConstraintNotResolved - Custom constraint - endpoints.MapControllerRoute( - name: "default", - pattern: "content/{culture:culture}/{**sitecoreRoute}", - defaults: new { controller = "Home", action = "Index" }); - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } - [Fact] public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() { @@ -147,4 +98,53 @@ public void Dispose() _factory.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildAdvanceLocalizationWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddLocalization(options => options.ResourcesPath = "Resources"); + services.AddRouting(); + services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); + + services.AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddModelBoundView("Component-4", "Component4") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseRequestLocalization(options => + { + List supportedCultures = [new("en"), new("da")]; + options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); + options.SupportedCultures = supportedCultures; + options.SupportedUICultures = supportedCultures; + options.UseSitecoreRequestLocalization(); + }); + app.UseSitecoreRenderingEngine(); + + app.UseEndpoints(endpoints => + { + // ReSharper disable once RouteTemplates.RouteParameterConstraintNotResolved - Custom constraint + endpoints.MapControllerRoute( + name: "default", + pattern: "content/{culture:culture}/{**sitecoreRoute}", + defaults: new { controller = "Home", action = "Index" }); + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs index ace6556..2a56532 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/DefaultLocalizationFixture.cs @@ -23,6 +23,31 @@ public DefaultLocalizationFixture() _factory = BuildDefaultLocalizationWebApplicationFactory(); } + [Fact] + public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() + { + // Arrange + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) + }); + + HttpClient client = _factory.CreateClient(); + + // Act + await client.GetStringAsync(new Uri("/da/UsingGlobalMiddleware", UriKind.Relative)); + + _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=da"); + } + + public void Dispose() + { + _mockClientHandler.Dispose(); + _factory.Dispose(); + GC.SuppressFinalize(this); + } + private WebApplicationFactory BuildDefaultLocalizationWebApplicationFactory() { WebApplicationFactory factory = new TestWebApplicationFactory(); @@ -64,29 +89,4 @@ private WebApplicationFactory BuildDefaultLocalizatio }); }); } - - [Fact] - public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() - { - // Arrange - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) - }); - - HttpClient client = _factory.CreateClient(); - - // Act - await client.GetStringAsync(new Uri("/da/UsingGlobalMiddleware", UriKind.Relative)); - - _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=da"); - } - - public void Dispose() - { - _mockClientHandler.Dispose(); - _factory.Dispose(); - GC.SuppressFinalize(this); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs index c2eb426..6536795 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs @@ -24,6 +24,31 @@ public LocalizationFixture() _factory = BuildLocalizationWebApplicationFactory(); } + [Fact] + public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() + { + // Arrange + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) + }); + + HttpClient client = _factory.CreateClient(); + + // Act + await client.GetStringAsync(new Uri("/ru-RU/UsingGlobalMiddleware", UriKind.Relative)); + + _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=ru-RU"); + } + + public void Dispose() + { + _mockClientHandler.Dispose(); + _factory.Dispose(); + GC.SuppressFinalize(this); + } + private WebApplicationFactory BuildLocalizationWebApplicationFactory() { WebApplicationFactory factory = new TestWebApplicationFactory(); @@ -71,29 +96,4 @@ private WebApplicationFactory BuildLocalizationWebApp }); }); } - - [Fact] - public async Task LocalizationRouteProvider_SetsCorrectRequestsLanguage() - { - // Arrange - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) - }); - - HttpClient client = _factory.CreateClient(); - - // Act - await client.GetStringAsync(new Uri("/ru-RU/UsingGlobalMiddleware", UriKind.Relative)); - - _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should().Contain("sc_lang=ru-RU"); - } - - public void Dispose() - { - _mockClientHandler.Dispose(); - _factory.Dispose(); - GC.SuppressFinalize(this); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs index ada28c4..7f1d5e7 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationUsingAttributeMiddlewareFixture.cs @@ -25,52 +25,6 @@ public LocalizationUsingAttributeMiddlewareFixture() _factory = BuildLocalizationUsingAttributeWebApplicationFactory(); } - private WebApplicationFactory BuildLocalizationUsingAttributeWebApplicationFactory() - { - WebApplicationFactory factory = new TestWebApplicationFactory(); - - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services.AddLocalization(options => options.ResourcesPath = "Resources"); - services.AddRouting(); - services.AddControllersWithViews(); - - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-4", "Component4") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseRequestLocalization(options => - { - List supportedCultures = [new("en"), new("uk-UA"), new("da-DK")]; - - options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); - options.SupportedCultures = supportedCultures; - options.SupportedUICultures = supportedCultures; - options.UseSitecoreRequestLocalization(); - }); - app.UseEndpoints(endpoints => - { - endpoints.MapSitecoreLocalizedRoute("Localized", "UseLocalizeWithAttribute", "UsingAttribute"); - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } - [Theory] [InlineData("br", "en")] [InlineData("en", "en")] @@ -158,4 +112,50 @@ public void Dispose() _factory.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildLocalizationUsingAttributeWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddLocalization(options => options.ResourcesPath = "Resources"); + services.AddRouting(); + services.AddControllersWithViews(); + + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-4", "Component4") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseRequestLocalization(options => + { + List supportedCultures = [new("en"), new("uk-UA"), new("da-DK")]; + + options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); + options.SupportedCultures = supportedCultures; + options.SupportedUICultures = supportedCultures; + options.UseSitecoreRequestLocalization(); + }); + app.UseEndpoints(endpoints => + { + endpoints.MapSitecoreLocalizedRoute("Localized", "UseLocalizeWithAttribute", "UsingAttribute"); + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingProxyFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingProxyFixture.cs index 6771efe..621315e 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingProxyFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Tracking/TrackingProxyFixture.cs @@ -27,6 +27,36 @@ public TrackingProxyFixture() _factory = BuildTrackingProxyWebApplicationFactory(); } + [Fact] + public async Task SitecoreRequests_ToLayouts_MustBeProxied() + { + // Arrange + HttpClient client = _factory.CreateClient(); + HttpRequestMessage request = new(HttpMethod.Get, new Uri("/layouts/System/VisitorIdentification.js", UriKind.Relative)); + request.Headers.Add("Cookie", ["ASP.NET_SessionId=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax", "SC_ANALYTICS_GLOBAL_COOKIE=0f82f53555ce4304a1ee8ae99ab9f9a8|False; expires = Fri, 15 - Mar - 2030 13:15:08 GMT; path =/; HttpOnly"]); + request.Headers.Add("X-Forwarded-For", "172.217.16.14"); + + // Act + await client.SendAsync(request); + + // Asserts + _mockClientHandler.Requests.Should().ContainSingle("A call to rendering middleware is not expected."); + _mockClientHandler.Requests[0].RequestUri!.Host.Should().Be(_cmInstanceUri.Host); + _mockClientHandler.Requests[0].RequestUri!.Scheme.Should().Be(_cmInstanceUri.Scheme); + _mockClientHandler.Requests[0].RequestUri!.PathAndQuery.Should().Be("/layouts/System/VisitorIdentification.js"); + _mockClientHandler.Requests[0].Headers.Should().Contain(h => h.Key.Equals("Cookie")); + _mockClientHandler.Requests[0].Headers.GetValues("x-forwarded-for").First().ToUpperInvariant().Should().Be("172.217.16.14"); + _mockClientHandler.Requests[0].Headers.GetValues("x-forwarded-host").First().ToUpperInvariant().Should().Be("LOCALHOST"); + _mockClientHandler.Requests[0].Headers.GetValues("x-forwarded-proto").First().ToUpperInvariant().Should().Be("HTTP"); + } + + public void Dispose() + { + _factory.Dispose(); + _mockClientHandler.Dispose(); + GC.SuppressFinalize(this); + } + private WebApplicationFactory BuildTrackingProxyWebApplicationFactory() { WebApplicationFactory factory = new TestWebApplicationFactory(); @@ -80,34 +110,4 @@ private WebApplicationFactory BuildTrackingProxyWebAp }); }); } - - [Fact] - public async Task SitecoreRequests_ToLayouts_MustBeProxied() - { - // Arrange - HttpClient client = _factory.CreateClient(); - HttpRequestMessage request = new(HttpMethod.Get, new Uri("/layouts/System/VisitorIdentification.js", UriKind.Relative)); - request.Headers.Add("Cookie", ["ASP.NET_SessionId=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax", "SC_ANALYTICS_GLOBAL_COOKIE=0f82f53555ce4304a1ee8ae99ab9f9a8|False; expires = Fri, 15 - Mar - 2030 13:15:08 GMT; path =/; HttpOnly"]); - request.Headers.Add("X-Forwarded-For", "172.217.16.14"); - - // Act - await client.SendAsync(request); - - // Asserts - _mockClientHandler.Requests.Should().ContainSingle("A call to rendering middleware is not expected."); - _mockClientHandler.Requests[0].RequestUri!.Host.Should().Be(_cmInstanceUri.Host); - _mockClientHandler.Requests[0].RequestUri!.Scheme.Should().Be(_cmInstanceUri.Scheme); - _mockClientHandler.Requests[0].RequestUri!.PathAndQuery.Should().Be("/layouts/System/VisitorIdentification.js"); - _mockClientHandler.Requests[0].Headers.Should().Contain(h => h.Key.Equals("Cookie")); - _mockClientHandler.Requests[0].Headers.GetValues("x-forwarded-for").First().ToUpperInvariant().Should().Be("172.217.16.14"); - _mockClientHandler.Requests[0].Headers.GetValues("x-forwarded-host").First().ToUpperInvariant().Should().Be("LOCALHOST"); - _mockClientHandler.Requests[0].Headers.GetValues("x-forwarded-proto").First().ToUpperInvariant().Should().Be("HTTP"); - } - - public void Dispose() - { - _factory.Dispose(); - _mockClientHandler.Dispose(); - GC.SuppressFinalize(this); - } } \ No newline at end of file From 1f6c2ed3aa6ab039ad518d76a800defb735106f6 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Thu, 18 Sep 2025 14:14:15 +0530 Subject: [PATCH 27/41] Migrate ExperienceEditor fixtures --- .../ExperienceEditorCustomRoutingFixture.cs | 102 ++++++++----- .../ExperienceEditorFixture.cs | 136 ++++++++++-------- ...xperienceEditorParsePathByItemIdFixture.cs | 64 +++++---- .../ForwardHeadersToLayoutServiceFixture.cs | 20 +-- 4 files changed, 191 insertions(+), 131 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorCustomRoutingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorCustomRoutingFixture.cs index 11b0c75..e1f37d2 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorCustomRoutingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorCustomRoutingFixture.cs @@ -1,55 +1,34 @@ using System.Net; using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using NSubstitute; using Sitecore.AspNetCore.SDK.ExperienceEditor.Extensions; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.LayoutService.Client.Interfaces; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Request; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Response; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Response.Model; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Serialization; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; using Sitecore.AspNetCore.SDK.TestData; using Xunit; +using Route = Sitecore.AspNetCore.SDK.LayoutService.Client.Response.Model.Route; namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.ExperienceEditor; public class ExperienceEditorCustomRoutingFixture : IDisposable { - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; public ExperienceEditorCustomRoutingFixture() { - TestServerBuilder testHostBuilder = new(); - _ = testHostBuilder - .ConfigureServices(builder => - { - builder.AddSingleton(Substitute.For()); - builder.AddSitecoreRenderingEngine(options => - { - options.AddDefaultComponentRenderer(); - }).WithExperienceEditor(options => - { - options.Endpoint = TestConstants.EEMiddlewarePostEndpoint; - options.JssEditingSecret = TestConstants.JssEditingSecret; - - options.MapToRequest((sitecoreResponse, scPath, httpRequest) => - httpRequest.Path = scPath + "/" + sitecoreResponse.Sitecore?.Route?.DatabaseName); - }); - }) - .Configure(app => - { - app.UseSitecoreExperienceEditor(); - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapFallbackToController("Default", "Home"); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + _factory = BuildExperienceEditorCustomRoutingWebApplicationFactory(); } public void Dispose() { - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } @@ -57,7 +36,7 @@ public void Dispose() public async Task EECustomRoute_MapsToCorrectRoute_WhenCustomRouteSetInOptions() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRequest); // Act @@ -76,4 +55,63 @@ public async Task EECustomRoute_MapsToCorrectRoute_WhenCustomRouteSetInOptions() responseString.Should().EndWith("}"); responseString.Should().Contain("master"); } + + private WebApplicationFactory BuildExperienceEditorCustomRoutingWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + ISitecoreLayoutClient layoutClientSub = Substitute.For(); + SitecoreLayoutRequest sampleRequest = []; + SitecoreLayoutResponse sampleResponse = new(sampleRequest) + { + Content = new SitecoreLayoutResponseContent + { + Sitecore = new SitecoreData + { + Route = new Route + { + DatabaseName = "master" + } + }, + ContextRawData = string.Empty + } + }; + + layoutClientSub.Request(Arg.Any()) + .Returns(Task.FromResult(sampleResponse)); + + services.AddSingleton(layoutClientSub); + services.AddRouting(); + services.AddSitecoreLayoutService(); + services.AddControllersWithViews(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultComponentRenderer(); + }).WithExperienceEditor(options => + { + options.Endpoint = TestConstants.EEMiddlewarePostEndpoint; + options.JssEditingSecret = TestConstants.JssEditingSecret; + + options.MapToRequest((sitecoreResponse, scPath, httpRequest) => + httpRequest.Path = scPath + "/" + sitecoreResponse.Sitecore?.Route?.DatabaseName); + }); + }); + + builder.Configure(app => + { + app.UseSitecoreExperienceEditor(); + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapFallbackToController("Default", "Home"); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorFixture.cs index 8d9515c..fc561b6 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorFixture.cs @@ -1,9 +1,11 @@ using System.Net; using System.Text; using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using NSubstitute; using Sitecore.AspNetCore.SDK.ExperienceEditor.Extensions; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.LayoutService.Client.Interfaces; using Sitecore.AspNetCore.SDK.LayoutService.Client.Request; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -15,43 +17,18 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Exp public class ExperienceEditorFixture : IDisposable { - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; public ExperienceEditorFixture() { - TestServerBuilder testHostBuilder = new(); - _ = testHostBuilder - .ConfigureServices(builder => - { - builder.AddSingleton(Substitute.For()); - builder.AddSitecoreRenderingEngine(options => - { - options.AddDefaultComponentRenderer(); - }).WithExperienceEditor(options => - { - options.Endpoint = TestConstants.EEMiddlewarePostEndpoint; - options.JssEditingSecret = TestConstants.JssEditingSecret; - }); - }) - .Configure(app => - { - app.UseSitecoreExperienceEditor(); - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapFallbackToController("Default", "Home"); - }); - }); - - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + _factory = BuildExperienceEditorWebApplicationFactory(); } [Fact] public async Task EEEndpoint_SendsNonWrappedResponse_WhenGetRequest() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act HttpResponseMessage response = await client.GetAsync(TestConstants.EEMiddlewarePostEndpoint); @@ -66,7 +43,7 @@ public async Task EEEndpoint_SendsNonWrappedResponse_WhenGetRequest() public async Task EEEndpoint_SendsNonWrappedResponse_WhenGetRequestInSampleEndPoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); // Act HttpResponseMessage response = await client.GetAsync(TestConstants.SampleEndPoint); @@ -81,7 +58,7 @@ public async Task EEEndpoint_SendsNonWrappedResponse_WhenGetRequestInSampleEndPo public async Task EEEndpoint_Sends400ErrorCodeInResponse_WhenEmptyStringSentInRequestBody() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(string.Empty, Encoding.UTF8, "application/json"); // Act @@ -97,7 +74,7 @@ public async Task EEEndpoint_Sends400ErrorCodeInResponse_WhenEmptyStringSentInRe public async Task EEEndpoint_Sends400ErrorCodeInResponse_WhenInvalidRequestBody() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new("abcnnmkksmvkdmfvkdkvmkdmv"); HttpResponseMessage response = await client @@ -112,9 +89,9 @@ public async Task EEEndpoint_Sends400ErrorCodeInResponse_WhenInvalidRequestBody( public async Task EEEndpoint_SendsNonWrappedResponse_WhenPostedToNonEEEndpoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRequest); - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); // Act HttpResponseMessage response = await client @@ -135,7 +112,7 @@ public async Task EEEndpoint_SendsNonWrappedResponse_WhenPostedToNonEEEndpoint() public async Task EEEndpoint_SendsCorrectResponse_WhenCorrectDataSentInRequestBody() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRequest); // Act @@ -159,7 +136,7 @@ public async Task EEEndpoint_SendsCorrectResponse_WhenCorrectDataSentInRequestBo public async Task EEEndpoint_SendsCorrectResponse_WhenLargeDataSentInRequestBody() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EELargeRequest); // Act @@ -180,9 +157,9 @@ public async Task EEEndpoint_SendsCorrectResponse_WhenLargeDataSentInRequestBody public async Task EEEndpoint_ByPassesLayoutServiceRequest_WhenCorrectDataSentInRequestBody() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRequest); - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); // Act HttpResponseMessage response = await client @@ -198,8 +175,8 @@ public async Task EEEndpoint_ByPassesLayoutServiceRequest_WhenCorrectDataSentInR public async Task EEEndpoint_MakeLayoutServiceRequest_WhenGetRequest() { // Arrange - HttpClient client = _server.CreateClient(); - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + HttpClient client = _factory.CreateClient(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); // Act HttpResponseMessage response = await client @@ -217,9 +194,9 @@ public async Task EEEndpoint_MakeLayoutServiceRequest_WhenGetRequest() public async Task EEEndpoint_MakesLayoutServiceRequest_WhenInvalidRequest_SendToSampleEEndPoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new("invalidPostRequest"); - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); // Act HttpResponseMessage response = await client @@ -234,8 +211,8 @@ public async Task EEEndpoint_MakesLayoutServiceRequest_WhenInvalidRequest_SendTo public async Task EEEndpoint_MakesLayoutServiceRequest_WhenPostedToNonEEEndpoint() { // Arrange - HttpClient client = _server.CreateClient(); - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + HttpClient client = _factory.CreateClient(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); // Act HttpResponseMessage response = await client.PostAsync(TestConstants.SampleEndPoint, new StringContent(string.Empty, Encoding.UTF8, "application/json")); @@ -249,10 +226,10 @@ public async Task EEEndpoint_MakesLayoutServiceRequest_WhenPostedToNonEEEndpoint public async Task EEEndpoint_MakesLayoutServiceRequest_WhenValidRequest_SendToSampleEndPoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRequest); - ISitecoreLayoutClient layoutClient = _server.Services.GetRequiredService(); + ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); // Act HttpResponseMessage response = await client.PostAsync(TestConstants.SampleEndPoint, content); @@ -266,7 +243,7 @@ public async Task EEEndpoint_MakesLayoutServiceRequest_WhenValidRequest_SendToSa public async Task EEEndpoint_ChangePostToGet_WhenPostedToEEEndpoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRoutingRequest); // Act @@ -284,7 +261,7 @@ public async Task EEEndpoint_ChangePostToGet_WhenPostedToEEEndpoint() public async Task EEEndpoint_NotChangePostToGet_WhenPostedToNonEEEndpoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRoutingRequest); // Act @@ -307,7 +284,7 @@ public async Task EEEndpoint_NotChangePostToGet_WhenPostedToNonEEEndpoint() public async Task EEEndpoint_SendsInvalidResponse_WhenPostedToNonEEEndpoint(string invalidEndPoint) { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRequest); // Act @@ -328,7 +305,7 @@ public async Task EEEndpoint_SendsInvalidResponse_WhenPostedToNonEEEndpoint(stri public async Task EEEndpoint_SendsCorrectResponse_withoutCaseSensitiveEndPoint(string validEndPoint) { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRequest); // Act @@ -347,7 +324,7 @@ public async Task EEEndpoint_SendsCorrectResponse_withoutCaseSensitiveEndPoint(s public async Task EEEndpoint_ReturnSuccess_WhenRequestContainEmptyPath() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EEEmptyRoutingRequest); // Act @@ -366,7 +343,7 @@ public async Task EEEndpoint_ReturnSuccess_WhenRequestContainEmptyPath() public async Task EEEndpoint_NotChangeToGET_WhenRequestSendToDefaultRouting_ToSampleRoutingPoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EEDefaultRoutingRequest); // Act @@ -384,7 +361,7 @@ public async Task EEEndpoint_NotChangeToGET_WhenRequestSendToDefaultRouting_ToSa public async Task EEEndpoint_NotChangeToGet_whenInvalidRequest_SendToSampleRoutingEndPoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new("InvalidPost"); // Act @@ -402,7 +379,7 @@ public async Task EEEndpoint_NotChangeToGet_whenInvalidRequest_SendToSampleRouti public async Task ReturnSuccess_whenRequestSendWithoutPath_ToSampleRoutingEndPoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EmptyPathRequest); // Act @@ -420,7 +397,7 @@ public async Task ReturnSuccess_whenRequestSendWithoutPath_ToSampleRoutingEndPoi public async Task EEEndpoint_Send400ErrorCode_WhenIncompleteRequest_EEEndPoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EEIncompleteRequest); // Act @@ -437,7 +414,7 @@ public async Task EEEndpoint_Send400ErrorCode_WhenIncompleteRequest_EEEndPoint() public async Task EEndpoint_ReturnSuccess_WhenRequestContainDefaultPath() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EEDefaultRoutingRequest); // Act @@ -454,7 +431,7 @@ public async Task EEndpoint_ReturnSuccess_WhenRequestContainDefaultPath() public async Task EEEndpoint_SendsWrappedResponse_WhenRequestContainLongPath() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EELongPathRequest); // Act @@ -471,7 +448,7 @@ public async Task EEEndpoint_SendsWrappedResponse_WhenRequestContainLongPath() public async Task EEEndpoint_Sends400Error_WhenRequestDoesNotHaveItemPath() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EmptyPathRequest); // Act @@ -488,7 +465,7 @@ public async Task EEEndpoint_Sends400Error_WhenRequestDoesNotHaveItemPath() public async Task EEEndpoint_ChangePostToGet_WhenRequestHaveCaseSensitivePath() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.CaseSensitiveItemPathRequest); // Act @@ -506,7 +483,7 @@ public async Task EEEndpoint_ChangePostToGet_WhenRequestHaveCaseSensitivePath() public async Task NotChangeToGet_WhenRequestContainCaseSensitivePath_PostToNonEEEndPoint() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.CaseSensitiveItemPathRequest); // Act @@ -524,7 +501,7 @@ public async Task NotChangeToGet_WhenRequestContainCaseSensitivePath_PostToNonEE public async Task EEEndpoint_SendsUnauthorizedErrorCodeInResponse_WhenWrongSecret() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRequestWithWrongRequestedSecret, Encoding.UTF8, "application/json"); // Act @@ -540,7 +517,7 @@ public async Task EEEndpoint_SendsUnauthorizedErrorCodeInResponse_WhenWrongSecre public async Task EEEndpoint_SendsUnauthorizedErrorCodeInResponse_WhenNoSecret() { // Arrange - HttpClient client = _server.CreateClient(); + HttpClient client = _factory.CreateClient(); StringContent content = new(TestConstants.EESampleRequestWithNoSecret, Encoding.UTF8, "application/json"); // Act @@ -554,7 +531,42 @@ public async Task EEEndpoint_SendsUnauthorizedErrorCodeInResponse_WhenNoSecret() public void Dispose() { - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } + + private WebApplicationFactory BuildExperienceEditorWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddRouting(); + services.AddSitecoreLayoutService(); + services.AddSingleton(Substitute.For()); + services.AddControllersWithViews(); + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultComponentRenderer(); + }).WithExperienceEditor(options => + { + options.Endpoint = TestConstants.EEMiddlewarePostEndpoint; + options.JssEditingSecret = TestConstants.JssEditingSecret; + }); + }); + + builder.Configure(app => + { + app.UseSitecoreExperienceEditor(); + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapFallbackToController("Default", "Home"); + }); + }); + }); + } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorParsePathByItemIdFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorParsePathByItemIdFixture.cs index 83488f6..9d070fb 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorParsePathByItemIdFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorParsePathByItemIdFixture.cs @@ -1,10 +1,11 @@ using System.Dynamic; using System.Text; using AwesomeAssertions; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using NSubstitute; -using Sitecore.AspNetCore.SDK.ExperienceEditor.Configuration; using Sitecore.AspNetCore.SDK.ExperienceEditor.Extensions; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.LayoutService.Client.Interfaces; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; using Sitecore.AspNetCore.SDK.TestData; @@ -23,15 +24,11 @@ public class ExperienceEditorParsePathByItemIdFixture : IDisposable private const string PreviewRequestWithoutItemPath = """{"id":"jss-sample-app","args":["/?sc_itemid=%7bcfdd7ba2-e646-5294-87fc-6fad34451a97%7d&sc_ee_fb=false&sc_lang=en&sc_mode=preview&sc_debug=0&sc_trace=0&sc_prof=0&sc_ri=0&sc_rb=0","{\"sitecore\":{\"context\":{\"pageEditing\":false,\"site\":{\"name\":\"jss-sample-app\"},\"pageState\":\"preview\",\"language\":\"en\"},\"route\":{\"name\":\"sample-1\",\"displayName\":\"sample-1\",\"fields\":{\"pageTitle\":{\"value\":\"Sample 1 Page Title\"}},\"databaseName\":\"master\",\"deviceId\":\"fe5d7fdf-89c0-4d99-9aa3-b5fbd009c9f3\",\"itemId\":\"cfdd7ba2-e646-5294-87fc-6fad34451a97\",\"itemLanguage\":\"en\",\"itemVersion\":1,\"layoutId\":\"5179e218-3df6-5af7-8147-d2d4c05da992\",\"templateId\":\"dfe73d70-9835-584e-b0f5-28c58ab064d7\",\"templateName\":\"App Route\",\"placeholders\":{\"jss-main\":[{\"uid\":\"9157cc8c-5760-5114-9f2d-93cbe39b30dc\",\"componentName\":\"ContentBlock\",\"dataSource\":\"{27F322AF-3D30-5F2F-ADA2-DAB630D35EC6}\",\"params\":{},\"fields\":{\"heading\":{\"value\":\"GraphQL Sample 1\"},\"content\":{\"value\":\"

A child route here to illustrate the power of GraphQL queries. Back to GraphQL route

\\n\"}}}]}}}}","{\"language\":\"en\",\"dictionary\":{\"Documentation\":\"Documentation\",\"GraphQL\":\"GraphQL\",\"Styleguide\":\"Styleguide\",\"styleguide-sample\":\"This is a dictionary entry in English as a demonstration\"},\"httpContext\":{\"request\":{\"url\":\"https://sc100xm1cm:443/?sc_itemid={cfdd7ba2-e646-5294-87fc-6fad34451a97}&sc_ee_fb=false&sc_lang=en&sc_mode=preview&sc_debug=0&sc_trace=0&sc_prof=0&sc_ri=0&sc_rb=0\",\"path\":\"/\",\"querystring\":{\"sc_itemid\":\"{cfdd7ba2-e646-5294-87fc-6fad34451a97}\",\"sc_ee_fb\":\"false\",\"sc_lang\":\"en\",\"sc_mode\":\"preview\",\"sc_debug\":\"0\",\"sc_trace\":\"0\",\"sc_prof\":\"0\",\"sc_ri\":\"0\",\"sc_rb\":\"0\"},\"userAgent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.45 Safari/537.36 Edg/84.0.522.20\"}}}"],"functionName":"renderView","moduleName":"server.bundle","jssEditingSecret":"mysecret"}"""; - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; public ExperienceEditorParsePathByItemIdFixture() { - _server = CreateTestServer(options => - { - options.Endpoint = TestConstants.EEMiddlewarePostEndpoint; - options.JssEditingSecret = TestConstants.JssEditingSecret; - }); + _factory = BuildExperienceEditorWebApplicationFactory(); } [Fact] @@ -41,7 +38,7 @@ public async Task EE_SendPathWhenItemLoadedByItemID() const string eeUrl = TestConstants.EEMiddlewarePostEndpoint; // Act - string response = await SendPost(_server, eeUrl, PreviewRequest); + string response = await SendPost(_factory, eeUrl, PreviewRequest); dynamic? json = Serializer.Deserialize(response); string? actualPath = json?.html.ToString(); @@ -56,7 +53,7 @@ public async Task EE_SendPathWhenItemLoadedByItemIDIsEmpty() const string eeUrl = TestConstants.EEMiddlewarePostEndpoint; // Act - string response = await SendPost(_server, eeUrl, PreviewRequestWithNullItemPath); + string response = await SendPost(_factory, eeUrl, PreviewRequestWithNullItemPath); dynamic? json = Serializer.Deserialize(response); string? actualPath = json?.html.ToString(); @@ -71,7 +68,7 @@ public async Task EE_SendPathWhenItemLoadedWithoutItemID() const string eeUrl = TestConstants.EEMiddlewarePostEndpoint; // Act - string response = await SendPost(_server, eeUrl, PreviewRequestWithoutItemPath); + string response = await SendPost(_factory, eeUrl, PreviewRequestWithoutItemPath); dynamic? json = Serializer.Deserialize(response); string? actualPath = json?.html.ToString(); @@ -81,14 +78,14 @@ public async Task EE_SendPathWhenItemLoadedWithoutItemID() public void Dispose() { - _server.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - private static async Task SendPost(TestServer server, string eeUrl, string requestBody) + private static async Task SendPost(WebApplicationFactory factory, string eeUrl, string requestBody) { // Act - HttpClient client = server.CreateClient(); + HttpClient client = factory.CreateClient(); HttpResponseMessage response = await client .PostAsync(eeUrl, new StringContent(requestBody)) .ConfigureAwait(false); @@ -96,19 +93,31 @@ private static async Task SendPost(TestServer server, string eeUrl, stri return await response.Content.ReadAsStringAsync().ConfigureAwait(false); } - private static TestServer CreateTestServer(Action eeOptions) => - new TestServerBuilder() - .ConfigureServices(builder => + private WebApplicationFactory BuildExperienceEditorWebApplicationFactory() + { + WebApplicationFactory factory = new TestWebApplicationFactory(); + + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => { - builder.AddSingleton(Substitute.For()); - builder.AddSitecoreRenderingEngine(options => - { - options.AddDefaultComponentRenderer(); - }) - .WithExperienceEditor(eeOptions); - builder.AddSingleton(); - }) - .Configure(app => + services + .AddRouting() + .AddSitecoreLayoutService(); + services.AddSingleton(Substitute.For()); + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultComponentRenderer(); + }).WithExperienceEditor(options => + { + options.Endpoint = TestConstants.EEMiddlewarePostEndpoint; + options.JssEditingSecret = TestConstants.JssEditingSecret; + }); + + services.AddControllersWithViews(); + }); + + builder.Configure(app => { app.UseSitecoreExperienceEditor(); app.UseMiddleware(); @@ -118,8 +127,9 @@ private static TestServer CreateTestServer(Action eeOpt { endpoints.MapFallbackToController("Default", "Home"); }); - }) - .BuildServer(new Uri("http://localhost")); + }); + }); + } #pragma warning disable CS9113 #pragma warning disable CA1822 diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs index f8de6d8..4a92acd 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs @@ -180,6 +180,16 @@ public void Dispose() GC.SuppressFinalize(this); } + private static HttpRequestMessage BrowserWhitelistedHeaders() + { + HttpRequestMessage request = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); + + // whitelisted Headers + request.Headers.Add("x-forwarded-proto", "https"); + + return request; + } + private WebApplicationFactory BuildForwardHeadersToLayoutServiceWebApplicationFactory() { return factory.WithWebHostBuilder(builder => @@ -230,14 +240,4 @@ private WebApplicationFactory BuildForwardHeadersToLa }); }); } - - private static HttpRequestMessage BrowserWhitelistedHeaders() - { - HttpRequestMessage request = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); - - // whitelisted Headers - request.Headers.Add("x-forwarded-proto", "https"); - - return request; - } } \ No newline at end of file From 7b07bc714fda0178e4491474926335efe489ed3a Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Thu, 18 Sep 2025 14:38:49 +0530 Subject: [PATCH 28/41] Migrate Benchmarks tests --- .../ExperienceEditorMiddlewareBenchmarks.cs | 31 +++++---- .../RenderingEngineBenchmarks.cs | 53 ++++++++------- .../TrackingBenchmarks.cs | 67 ++++++++++--------- 3 files changed, 83 insertions(+), 68 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/ExperienceEditorMiddlewareBenchmarks.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/ExperienceEditorMiddlewareBenchmarks.cs index d5b44f2..9447e68 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/ExperienceEditorMiddlewareBenchmarks.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/ExperienceEditorMiddlewareBenchmarks.cs @@ -1,6 +1,8 @@ using System.Diagnostics.CodeAnalysis; using BenchmarkDotNet.Attributes; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using NSubstitute; @@ -17,19 +19,24 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks; [ExcludeFromCodeCoverage] public class ExperienceEditorMiddlewareBenchmarks : IDisposable { - private readonly TestServer _server; + private readonly WebApplicationFactory _factory; private readonly HttpClient _client; private readonly StringContent _content; private RenderingEngineBenchmarks? _baseLineTestInstance; public ExperienceEditorMiddlewareBenchmarks() { - TestServerBuilder testHostBuilder = new(); - testHostBuilder - .ConfigureServices(builder => + WebApplicationFactory factory = new TestWebApplicationFactory(); + + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => { - builder.AddSingleton(Substitute.For()); - builder.AddSitecoreRenderingEngine(options => + services.AddRouting(); + + services.AddSingleton(Substitute.For()); + + services.AddSitecoreRenderingEngine(options => { options.AddDefaultComponentRenderer(); }).WithExperienceEditor(options => @@ -37,17 +44,17 @@ public ExperienceEditorMiddlewareBenchmarks() options.Endpoint = TestConstants.EEMiddlewarePostEndpoint; options.JssEditingSecret = TestConstants.JssEditingSecret; }); - }) - .Configure(app => + }); + + builder.Configure(app => { app.UseSitecoreExperienceEditor(); app.UseRouting(); app.UseSitecoreRenderingEngine(); }); + }); - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - - _client = _server.CreateClient(); + _client = _factory.CreateClient(); _content = new StringContent(TestConstants.EESampleRequest); } @@ -76,7 +83,7 @@ public async Task RegularExperienceEditorRequestHandling() public void Dispose() { - _server.Dispose(); + _factory.Dispose(); _client.Dispose(); _content.Dispose(); _baseLineTestInstance?.Dispose(); diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/RenderingEngineBenchmarks.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/RenderingEngineBenchmarks.cs index 2bd3f89..0cf340d 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/RenderingEngineBenchmarks.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/RenderingEngineBenchmarks.cs @@ -2,11 +2,12 @@ using System.Net; using BenchmarkDotNet.Attributes; using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; -using Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests; using Sitecore.AspNetCore.SDK.TestData; namespace Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks; @@ -16,38 +17,38 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks; [ExcludeFromCodeCoverage] public class RenderingEngineBenchmarks : IDisposable { - private TestServer? _server; + private WebApplicationFactory? _factory; private HttpClient? _client; private MockHttpMessageHandler? _mockClientHandler; [GlobalSetup] public void Setup() - { - TestServerBuilder testHostBuilder = new(); - _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => - { - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = new Uri("http://layout.service") }) - .AsDefaultHandler(); + { + _mockClientHandler = new MockHttpMessageHandler(); - builder.AddSitecoreRenderingEngine(options => + _factory = new WebApplicationFactory() + .WithWebHostBuilder(builder => { - options.AddDefaultComponentRenderer(); - }); - }) - .Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - }); + builder.ConfigureServices(services => + { + services.AddRouting(); + services.AddSitecoreLayoutService(); + services.AddHttpClient("mock").ConfigurePrimaryHttpMessageHandler(() => _mockClientHandler!); + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultComponentRenderer(); + }); + }); - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + }); + }); - _client = _server.CreateClient(); - } + _client = _factory.CreateClient(); + } [Benchmark(Baseline = true)] public async Task RegularHomePageRequest() @@ -71,8 +72,8 @@ public async Task RegularHomePageRequest() public void Dispose() { - _server?.Dispose(); _client?.Dispose(); + _factory?.Dispose(); _mockClientHandler?.Dispose(); GC.SuppressFinalize(this); } diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/TrackingBenchmarks.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/TrackingBenchmarks.cs index 0b9137a..1430f92 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/TrackingBenchmarks.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/TrackingBenchmarks.cs @@ -2,13 +2,13 @@ using System.Net; using BenchmarkDotNet.Attributes; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.AspNetCore.TestHost; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; -using Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests; using Sitecore.AspNetCore.SDK.TestData; using Sitecore.AspNetCore.SDK.Tracking; using Sitecore.AspNetCore.SDK.Tracking.VisitorIdentification; @@ -21,7 +21,7 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks; [ExcludeFromCodeCoverage] public class TrackingBenchmarks : IDisposable { - private TestServer? _server; + private WebApplicationFactory? _factory; private HttpClient? _client; private MockHttpMessageHandler? _mockClientHandler; private RenderingEngineBenchmarks? _baseLineTestInstance; @@ -29,23 +29,22 @@ public class TrackingBenchmarks : IDisposable [GlobalSetup(Target = nameof(RegularHomePageRequestWithTracking))] public void TrackingBenchmarksSetup() { - TestServerBuilder testHostBuilder = new(); _mockClientHandler = new MockHttpMessageHandler(); - testHostBuilder - .ConfigureServices(builder => + + _factory = new WebApplicationFactory() + .WithWebHostBuilder(builder => { - builder.Configure(options => + builder.ConfigureServices(services => { - options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | - ForwardedHeaders.XForwardedProto; - }); - - builder - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = new Uri("http://layout.service") }) - .AsDefaultHandler(); + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | + ForwardedHeaders.XForwardedProto; + }); - builder.AddSitecoreRenderingEngine(options => + services.AddSitecoreLayoutService(); + services.AddHttpClient("mock").ConfigurePrimaryHttpMessageHandler(() => _mockClientHandler!); + services.AddSitecoreRenderingEngine(options => { options.AddDefaultComponentRenderer(); }).ForwardHeaders(options => @@ -66,22 +65,15 @@ public void TrackingBenchmarksSetup() }) .WithTracking(); - builder.AddSitecoreVisitorIdentification(options => - { - options.SitecoreInstanceUri = new Uri("http://layout.service"); + services.AddSitecoreVisitorIdentification(options => + { + options.SitecoreInstanceUri = new Uri("http://layout.service"); + }); + services.AddSingleton(); }); - }) - .Configure(app => - { - app.UseForwardedHeaders(); - app.UseRouting(); - app.UseSitecoreVisitorIdentification(); - app.UseSitecoreRenderingEngine(); }); - _server = testHostBuilder.BuildServer(new Uri("http://localhost")); - - _client = _server.CreateClient(); + _client = _factory.CreateClient(); } [GlobalSetup(Target = nameof(RegularHomePageRequest))] @@ -119,10 +111,25 @@ public async Task RegularHomePageRequestWithTracking() public void Dispose() { - _server?.Dispose(); _client?.Dispose(); + _factory?.Dispose(); _mockClientHandler?.Dispose(); _baseLineTestInstance?.Dispose(); GC.SuppressFinalize(this); } + + private class PipelineStartupFilter : IStartupFilter + { + public Action Configure(Action next) + { + return app => + { + app.UseForwardedHeaders(); + app.UseRouting(); + app.UseSitecoreVisitorIdentification(); + app.UseSitecoreRenderingEngine(); + next(app); + }; + } + } } \ No newline at end of file From 09a1244baa78c90071a40da03041df59f1d36f9a Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Mon, 22 Sep 2025 10:32:09 +0530 Subject: [PATCH 29/41] revert syntax changes --- .../Fixtures/Localization/LocalizationFixture.cs | 2 +- .../Fixtures/RequestDefaultsConfigurationFixture.cs | 4 ++-- .../Fixtures/RequestMappingFixture.cs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs index 6536795..e3cb321 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Localization/LocalizationFixture.cs @@ -79,7 +79,7 @@ private WebApplicationFactory BuildLocalizationWebApp app.UseRouting(); app.UseRequestLocalization(options => { - List supportedCultures = new() { new("en"), new("ru-RU") }; + List supportedCultures = [new("en"), new("ru-RU")]; options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en"); options.SupportedCultures = supportedCultures; diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs index 367cf12..1cd9eaa 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestDefaultsConfigurationFixture.cs @@ -46,7 +46,7 @@ public async Task Request_OnlyHandlerOptionsProvided_FinalRequestUsesHandlerOpti // Arrange ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); - SitecoreLayoutRequest request = new SitecoreLayoutRequest(); + SitecoreLayoutRequest request = []; // Act SitecoreLayoutResponse response = await layoutClient.Request(request); @@ -81,7 +81,7 @@ public async Task Request_GlobalAndHandlerOptionsProvided_FinalRequestUsesHandle // Arrange ISitecoreLayoutClient layoutClient = _factory.Services.GetRequiredService(); - SitecoreLayoutRequest request = new SitecoreLayoutRequest(); + SitecoreLayoutRequest request = []; // Act SitecoreLayoutResponse response = await layoutClient.Request(request); diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestMappingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestMappingFixture.cs index f6bf771..4f03387 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestMappingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestMappingFixture.cs @@ -162,7 +162,7 @@ private WebApplicationFactory BuildRequestMappingWebA httpMessage.Headers.Add("Cookie", aspnet!.ToString()); } - httpMessage.RequestUri = layoutRequest.BuildDefaultSitecoreLayoutRequestUri(httpMessage.RequestUri!, new[] { "param1", "param2" }); + httpMessage.RequestUri = layoutRequest.BuildDefaultSitecoreLayoutRequestUri(httpMessage.RequestUri!, ["param1", "param2"]); }) .AsDefaultHandler(); From 28d9311e0ea32bd00be3b6521ee03827bbc69a24 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Mon, 22 Sep 2025 15:35:22 +0530 Subject: [PATCH 30/41] Explicitly start the host without creating an unused client --- .../Fixtures/ErrorHandlingFixture.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ErrorHandlingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ErrorHandlingFixture.cs index 6750c98..6f85972 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ErrorHandlingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ErrorHandlingFixture.cs @@ -142,7 +142,7 @@ public async Task HttpMessageConfigurationError_Returns_SitecoreLayoutServiceMes }); // Ensure host is started so services are available - configuredFactory.CreateClient(); + _ = configuredFactory.Server; ISitecoreLayoutClient layoutClient = configuredFactory.Services.GetRequiredService(); From a6558e60a5b14994e0acdf2b419b27925074fa32 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 23 Sep 2025 16:11:08 +0530 Subject: [PATCH 31/41] test(fixture): reuse TestWebApplicationFactory across integration tests --- .../Binding/ComplexModelBindingFixture.cs | 70 +++++---- .../CustomModelContextBindingFixture.cs | 69 +++++---- .../Binding/CustomResolverBindingFixture.cs | 72 ++++----- .../ModelBindingErrorHandlingFixture.cs | 70 +++++---- .../Fixtures/Binding/ModelBindingFixture.cs | 56 +++---- .../Binding/ViewFieldsBindingFixture.cs | 70 +++++---- .../Fixtures/ControllerMiddlewareFixture.cs | 69 +++++---- .../LoggingComponentRendererFixture.cs | 70 +++++---- .../MultipleComponentsAddedFixture.cs | 71 ++++----- .../PartialViewRendererFixture.cs | 71 ++++----- .../ForwardHeadersToLayoutServiceFixture.cs | 119 ++++++++------- .../Fixtures/Multisite/MultisiteFixture.cs | 144 +++++++++--------- .../Fixtures/Pages/PagesEditingFixture.cs | 101 ++++++------ .../Pages/PagesSetupRoutingFixture.cs | 104 +++++++------ .../EdgeSitemapProxyFixture.cs | 72 +++++---- .../SearchOptimization/SitemapProxyFixture.cs | 63 ++++---- .../TagHelpers/AllFieldTagHelpersFixture.cs | 71 +++++---- .../TagHelpers/DateFieldTagHelperFixture.cs | 73 ++++----- .../TagHelpers/FileFieldTagHelperFixture.cs | 79 +++++----- .../TagHelpers/ImageFieldTagHelperFixture.cs | 85 ++++++----- .../TagHelpers/LinkFieldTagHelperFixture.cs | 89 ++++++----- .../TagHelpers/NumberFieldTagHelperFixture.cs | 73 +++++---- .../TagHelpers/PlaceholderTagHelperFixture.cs | 77 +++++----- .../RichTextFieldTagHelperFixture.cs | 75 ++++----- .../TagHelpers/TextFieldTagHelperFixture.cs | 72 ++++----- 25 files changed, 1051 insertions(+), 934 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs index c049f8f..c3fec8a 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs @@ -11,11 +11,45 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class ComplexModelBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class ComplexModelBindingFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public ComplexModelBindingFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Complex-Component", StringComparison.OrdinalIgnoreCase), "ComplexComponent") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } + [Fact] public async Task SitecoreLayoutModelBinders_BindDataCorrectly() { @@ -26,7 +60,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildComplexModelBindingWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -73,37 +107,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildComplexModelBindingWebApplicationFactory() - { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Complex-Component", StringComparison.OrdinalIgnoreCase), "ComplexComponent") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs index 6f9b810..b8b808e 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomModelContextBindingFixture.cs @@ -13,10 +13,43 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class CustomModelContextBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class CustomModelContextBindingFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public CustomModelContextBindingFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Custom-Model-Context-Component", StringComparison.OrdinalIgnoreCase), "CustomModelContextComponent") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task SitecoreLayoutModelBinders_BindDataCorrectly() @@ -42,7 +75,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(jObject!.ToJsonString(Serializer.GetOptions())) }); - HttpClient client = BuildCustomModelContextBindingWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -79,37 +112,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildCustomModelContextBindingWebApplicationFactory() - { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Custom-Model-Context-Component", StringComparison.OrdinalIgnoreCase), "CustomModelContextComponent") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs index b1e5838..58f3673 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/CustomResolverBindingFixture.cs @@ -12,10 +12,45 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class CustomResolverBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class CustomResolverBindingFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public CustomResolverBindingFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("PartialDesignDynamicPlaceholder") + .AddModelBoundView(name => name.Equals("Navigation", StringComparison.OrdinalIgnoreCase), "CustomResolver") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task SitecoreLayoutModelBinders_BindDataCorrectly() @@ -28,7 +63,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(json) }); - HttpClient client = BuildCustomResolverBindingWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -49,38 +84,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildCustomResolverBindingWebApplicationFactory() - { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("PartialDesignDynamicPlaceholder") - .AddModelBoundView(name => name.Equals("Navigation", StringComparison.OrdinalIgnoreCase), "CustomResolver") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs index d2ef243..4aef340 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingErrorHandlingFixture.cs @@ -11,11 +11,45 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class ModelBindingErrorHandlingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class ModelBindingErrorHandlingFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public ModelBindingErrorHandlingFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Component-With-Missing-Data", StringComparison.OrdinalIgnoreCase), "ComponentWithMissingData") + .AddModelBoundView(name => name.Equals("Component-Without-Id", StringComparison.OrdinalIgnoreCase), "ComponentWithoutId"); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } + [Fact] public async Task SitecoreLayoutModelBinders_HandleMissingDataCorrectly() { @@ -26,7 +60,7 @@ public async Task SitecoreLayoutModelBinders_HandleMissingDataCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithMissingData)) }); - HttpClient client = BuildModelBindingErrorHandlingWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -62,37 +96,7 @@ public async Task SitecoreLayoutModelBinders_HandleMissingDataCorrectly() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildModelBindingErrorHandlingWebApplicationFactory() - { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Component-With-Missing-Data", StringComparison.OrdinalIgnoreCase), "ComponentWithMissingData") - .AddModelBoundView(name => name.Equals("Component-Without-Id", StringComparison.OrdinalIgnoreCase), "ComponentWithoutId"); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs index c628759..7393cc6 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ModelBindingFixture.cs @@ -11,11 +11,35 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class ModelBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class ModelBindingFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public ModelBindingFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + } + [Fact] public async Task SitecoreRouteModelBinding_ReturnsCorrectData() { @@ -25,7 +49,7 @@ public async Task SitecoreRouteModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildModelBindingWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreRoute"); // assert that the SitecoreRouteProperty attribute binding worked @@ -47,7 +71,7 @@ public async Task SitecoreContextModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildModelBindingWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreContext"); // assert that the SitecoreContextProperty attribute binding worked @@ -67,7 +91,7 @@ public async Task SitecoreResponseModelBinding_ReturnsCorrectData() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildModelBindingWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string response = await client.GetStringAsync("WithBoundSitecoreResponse"); // assert that the SitecoreLayoutResponse attribute binding worked @@ -77,29 +101,7 @@ public async Task SitecoreResponseModelBinding_ReturnsCorrectData() public void Dispose() { _mockClientHandler.Dispose(); + _factory?.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildModelBindingWebApplicationFactory() - { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - services.AddSitecoreRenderingEngine(); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs index 396d53f..2517dfd 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ViewFieldsBindingFixture.cs @@ -11,11 +11,45 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Binding; -public class ViewFieldsBindingFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class ViewFieldsBindingFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public ViewFieldsBindingFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Component-5", StringComparison.OrdinalIgnoreCase), "Component5") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } + [Fact] public async Task SitecoreLayoutModelBinders_BindDataCorrectly() { @@ -26,7 +60,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildViewFieldsBindingWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -53,37 +87,7 @@ public async Task SitecoreLayoutModelBinders_BindDataCorrectly() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildViewFieldsBindingWebApplicationFactory() - { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Component-5", StringComparison.OrdinalIgnoreCase), "Component5") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ControllerMiddlewareFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ControllerMiddlewareFixture.cs index cf80c77..8449c37 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ControllerMiddlewareFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ControllerMiddlewareFixture.cs @@ -8,7 +8,7 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures; -public class ControllerMiddlewareFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class ControllerMiddlewareFixture : IClassFixture>, IDisposable { private const string MiddlewareController = "ControllerMiddleware"; @@ -18,6 +18,36 @@ public class ControllerMiddlewareFixture(TestWebApplicationFactory _factory; + + public ControllerMiddlewareFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddRouting() + .AddSitecoreLayoutService() + .AddHttpHandler( + "mock", + _ => new HttpClient(_mockClientHandler) + { + BaseAddress = _layoutServiceUri + }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); + }); + }); + } + [Fact] public async Task HttpClient_IsInvoked() { @@ -26,7 +56,7 @@ public async Task HttpClient_IsInvoked() StatusCode = HttpStatusCode.OK }); - HttpClient client = BuildControllerMiddlewareWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); await client.GetAsync(MiddlewareController); _mockClientHandler.WasInvoked.Should().BeTrue(); @@ -40,7 +70,7 @@ public async Task HttpClient_IsNotInvoked() StatusCode = HttpStatusCode.OK }); - HttpClient client = BuildControllerMiddlewareWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); await client.GetAsync(GlobalMiddlewareController); _mockClientHandler.WasInvoked.Should().BeFalse(); @@ -54,7 +84,7 @@ public async Task Controller_ReturnsCorrectContent() StatusCode = HttpStatusCode.OK }); - HttpClient client = BuildControllerMiddlewareWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string response = await client.GetStringAsync(GlobalMiddlewareController); response.Should().Be("\"success\""); @@ -68,7 +98,7 @@ public async Task HttpClient_LayoutServiceUriMapped() StatusCode = HttpStatusCode.OK }); - HttpClient client = BuildControllerMiddlewareWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); await client.GetAsync(MiddlewareController); _mockClientHandler.Requests.Single().RequestUri!.AbsoluteUri.Should() @@ -78,34 +108,7 @@ public async Task HttpClient_LayoutServiceUriMapped() public void Dispose() { _mockClientHandler.Dispose(); + _factory?.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildControllerMiddlewareWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddRouting() - .AddSitecoreLayoutService() - .AddHttpHandler( - "mock", - _ => new HttpClient(_mockClientHandler) - { - BaseAddress = _layoutServiceUri - }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs index 15ce5fd..4bc3350 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/LoggingComponentRendererFixture.cs @@ -12,11 +12,45 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.CustomRenderTypes; -public class LoggingComponentRendererFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class LoggingComponentRendererFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public LoggingComponentRendererFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddSingleton(new IntegrationTestLoggerProvider()); + + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } + [Fact] public async Task CustomRenderTypes_DefaultRendererWritesToLogWithoutRenderingHtml() { @@ -27,7 +61,7 @@ public async Task CustomRenderTypes_DefaultRendererWritesToLogWithoutRenderingHt Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLoggingComponentRendererWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -45,37 +79,7 @@ public async Task CustomRenderTypes_DefaultRendererWritesToLogWithoutRenderingHt public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildLoggingComponentRendererWebApplicationFactory() - { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services.AddSingleton(new IntegrationTestLoggerProvider()); - - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - services.AddSitecoreRenderingEngine(options => - { - options.AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs index 3aab1a0..13774a2 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs @@ -12,10 +12,44 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.CustomRenderTypes; -public class MultipleComponentsAddedFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class MultipleComponentsAddedFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public MultipleComponentsAddedFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView(name => name.Equals("Component-3", StringComparison.OrdinalIgnoreCase), "Component3") + .AddModelBoundView(name => name.Equals("Component-6", StringComparison.OrdinalIgnoreCase), "Component6") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task CustomRenderTypes_MultipleComponentsBoundsInCorrectOrder() @@ -27,7 +61,7 @@ public async Task CustomRenderTypes_MultipleComponentsBoundsInCorrectOrder() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildMultipleComponentsAddedWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -53,38 +87,7 @@ public async Task CustomRenderTypes_MultipleComponentsBoundsInCorrectOrder() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildMultipleComponentsAddedWebApplicationFactory() - { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView(name => name.Equals("Component-3", StringComparison.OrdinalIgnoreCase), "Component3") - .AddModelBoundView(name => name.Equals("Component-6", StringComparison.OrdinalIgnoreCase), "Component6") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs index be183e7..3f67fcb 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs @@ -11,10 +11,44 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.CustomRenderTypes; -public class PartialViewRendererFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class PartialViewRendererFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public PartialViewRendererFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddPartialView(name => name.Equals("Component-6", StringComparison.OrdinalIgnoreCase), "_PartialView") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task CustomRenderTypes_PartialViewRendersCorrectly() @@ -26,7 +60,7 @@ public async Task CustomRenderTypes_PartialViewRendersCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildPartialViewWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -43,38 +77,7 @@ public async Task CustomRenderTypes_PartialViewRendersCorrectly() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildPartialViewWebApplicationFactory() - { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddPartialView(name => name.Equals("Component-6", StringComparison.OrdinalIgnoreCase), "_PartialView") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs index 4a92acd..a9b2684 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ForwardHeaders/ForwardHeadersToLayoutServiceFixture.cs @@ -11,12 +11,65 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.ForwardHeaders; -public class ForwardHeadersToLayoutServiceFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class ForwardHeadersToLayoutServiceFixture : IClassFixture>, IDisposable { private const string TestHeaderRhResponse = "testHeaderResponseFromRenderingHost"; private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public ForwardHeadersToLayoutServiceFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | + ForwardedHeaders.XForwardedProto; + }); + + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) + { + BaseAddress = _layoutServiceUri + }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultComponentRenderer(); + }).ForwardHeaders(options => + { + options.HeadersWhitelist.Add("HEADERTOCOPY"); + options.HeadersWhitelist.Add("Cookie"); + options.RequestHeadersFilters.Add( + (_, result) => + { + result.AppendValue("testNonWhitelistedHeader", "testNonWhitelistedHeaderValue"); + result.AppendValue("headerToModify", "newModifiedHeaderValue"); + result.AppendValue("cookie", "NewAddedCookie=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax"); + }); + + options.ResponseHeadersFilters.Add( + (_, result) => + { + result.AppendValue(TestHeaderRhResponse, "testHeaderResponseValueFromRenderingHost"); + }); + }); + }); + + builder.Configure(app => + { + app.UseForwardedHeaders(); + app.UseSitecoreRenderingEngine(); + }); + }); + } + [Fact] public async Task SitecoreLayoutServiceRequest_FiltersHeaders() { @@ -27,7 +80,7 @@ public async Task SitecoreLayoutServiceRequest_FiltersHeaders() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)), }); - HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = BrowserWhitelistedHeaders(); request.Headers.Add("connection", string.Empty); request.Headers.Add("keep-alive", "sometestvalueshere"); @@ -63,7 +116,7 @@ public async Task SitecoreLayoutServiceRequest_FiltersHeaders_CaseSensitive() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); request.Headers.Add("COOKIE", "testValue"); @@ -85,7 +138,7 @@ public async Task SitecoreLayoutServiceRequest_FiltersHeaders_NonWhitelistedHead Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/", UriKind.Relative)); request.Headers.Add("testNonWhitelistedHeader", "testNonWhitelistedHeaderValue"); @@ -106,7 +159,7 @@ public async Task SitecoreLayoutServiceRequest_FiltersHeadersNegativeCasesEmptyH Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = BrowserWhitelistedHeaders(); request.Headers.Add("connection", string.Empty); @@ -132,7 +185,7 @@ public async Task SitecoreResponse_Headers_CopiedToResponse_AreFilteredAndModifi _mockClientHandler.Responses.Push(responseMsg); - HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = BrowserWhitelistedHeaders(); request.Headers.Add("headerToModify", "oldHeaderValue"); request.Headers.Add("HEADERTOCOPY", "sometestvalueshere"); @@ -160,7 +213,7 @@ public async Task SitecoreResponse_Headers_CopiedToResponse_WhitelistedFilteredA _mockClientHandler.Responses.Push(responseMsg); - HttpClient client = BuildForwardHeadersToLayoutServiceWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = BrowserWhitelistedHeaders(); request.Headers.Add("Cookie", ["ASP.NET_SessionId=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax", "SC_ANALYTICS_GLOBAL_COOKIE=0f82f53555ce4304a1ee8ae99ab9f9a8|False; expires = Fri, 15 - Mar - 2030 13:15:08 GMT; path =/; HttpOnly"]); @@ -177,6 +230,7 @@ public async Task SitecoreResponse_Headers_CopiedToResponse_WhitelistedFilteredA public void Dispose() { _mockClientHandler.Dispose(); + _factory?.Dispose(); GC.SuppressFinalize(this); } @@ -189,55 +243,4 @@ private static HttpRequestMessage BrowserWhitelistedHeaders() return request; } - - private WebApplicationFactory BuildForwardHeadersToLayoutServiceWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services.Configure(options => - { - options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | - ForwardedHeaders.XForwardedProto; - }); - - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) - { - BaseAddress = _layoutServiceUri - }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options.AddDefaultComponentRenderer(); - }).ForwardHeaders(options => - { - options.HeadersWhitelist.Add("HEADERTOCOPY"); - options.HeadersWhitelist.Add("Cookie"); - options.RequestHeadersFilters.Add( - (_, result) => - { - result.AppendValue("testNonWhitelistedHeader", "testNonWhitelistedHeaderValue"); - result.AppendValue("headerToModify", "newModifiedHeaderValue"); - result.AppendValue("cookie", "NewAddedCookie=rku2oxmotbrkwkfxe0cpfrvn; path=/; HttpOnly; SameSite=Lax"); - }); - - options.ResponseHeadersFilters.Add( - (_, result) => - { - result.AppendValue(TestHeaderRhResponse, "testHeaderResponseValueFromRenderingHost"); - }); - }); - }); - - builder.Configure(app => - { - app.UseForwardedHeaders(); - app.UseSitecoreRenderingEngine(); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs index 0c77e3f..b3a8cc1 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs @@ -15,12 +15,77 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Multisite; -public class MultisiteFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class MultisiteFixture : IClassFixture>, IDisposable { private const string DefaultSiteName = "defaultSiteName"; private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public MultisiteFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + IGraphQLClient? mockedGraphQLClient = Substitute.For(); + mockedGraphQLClient + .SendQueryAsync(Arg.Any()) + .Returns(new GraphQLResponse + { + Data = new SiteInfoCollectionResult + { + Site = new Site + { + SiteInfoCollection = new[] + { + new SiteInfo { HostName = "host1", Name = "siteForHost1" }, + new SiteInfo { HostName = "host2", Name = "siteForHost2" }, + new SiteInfo { HostName = "foo.bar", Name = "fooSite" }, + new SiteInfo { HostName = "*.test.com", Name = "wildcardSite" }, + new SiteInfo { HostName = "concrete.test.com", Name = "concrete" }, + new SiteInfo { HostName = "multiHostname1.test.com | multiHostname2.test.com ", Name = "multiHostNameTestSite" } + } + } + } + }); + + services + .AddSitecoreLayoutService().WithDefaultRequestOptions(request => + { + request + .SiteName(DefaultSiteName); + if (!request.ContainsKey(RequestKeys.Language)) + { + request.Language("en"); + } + }) + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultPartialView("_ComponentNotFound"); + }); + + services.AddSingleton(mockedGraphQLClient); + services.AddMultisite(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseMultisite(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapFallbackToController("Index", "Multisite"); + }); + }); + }); + } + [Theory] [InlineData("host1", "siteForHost1")] [InlineData("host2", "siteForHost2")] @@ -33,7 +98,7 @@ public class MultisiteFixture(TestWebApplicationFactory BuildMultisiteWebApplicationFactory() - { - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK - }); - - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService().WithDefaultRequestOptions(request => - { - request - .SiteName(DefaultSiteName); - if (!request.ContainsKey(RequestKeys.Language)) - { - request.Language("en"); - } - }) - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - IGraphQLClient? mockedGraphQLClient = Substitute.For(); - mockedGraphQLClient - .SendQueryAsync(Arg.Any()) - .Returns(new GraphQLResponse - { - Data = new SiteInfoCollectionResult - { - Site = new Site - { - SiteInfoCollection = new[] - { - new SiteInfo { HostName = "host1", Name = "siteForHost1" }, - new SiteInfo { HostName = "host2", Name = "siteForHost2" }, - new SiteInfo { HostName = "foo.bar", Name = "fooSite" }, - new SiteInfo { HostName = "*.test.com", Name = "wildcardSite" }, - new SiteInfo { HostName = "concrete.test.com", Name = "concrete" }, - new SiteInfo { HostName = "multiHostname1.test.com | multiHostname2.test.com ", Name = "multiHostNameTestSite" } - } - } - } - }); - - services.AddSitecoreRenderingEngine(options => - { - options.AddDefaultPartialView("_ComponentNotFound"); - }); - - services.AddSingleton(mockedGraphQLClient); - services.AddMultisite(); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseMultisite(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapFallbackToController("Index", "Multisite"); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesEditingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesEditingFixture.cs index 0062d2f..414434e 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesEditingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesEditingFixture.cs @@ -6,7 +6,6 @@ using NSubstitute; using Sitecore.AspNetCore.SDK.GraphQL.Request; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; -using Sitecore.AspNetCore.SDK.Pages.Configuration; using Sitecore.AspNetCore.SDK.Pages.Extensions; using Sitecore.AspNetCore.SDK.Pages.Middleware; using Sitecore.AspNetCore.SDK.Pages.Request.Handlers.GraphQL; @@ -16,15 +15,64 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Pages; -public class PagesEditingFixture(TestWebApplicationFactory factory) : IClassFixture> +public class PagesEditingFixture : IClassFixture>, IDisposable { + private readonly TestWebApplicationFactory _sourceFactory; + private readonly WebApplicationFactory _factory; + + public PagesEditingFixture(TestWebApplicationFactory factory) + { + _sourceFactory = factory; + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddSitecoreLayoutService() + .AddSitecorePagesHandler() + .AddGraphQLWithContextHandler("default", TestConstants.ContextId, siteName: TestConstants.SiteName) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultPartialView("_ComponentNotFound"); + }) + .WithSitecorePages(TestConstants.ContextId, options => { options.EditingSecret = TestConstants.JssEditingSecret; }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseMiddleware(); + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Pages}/{action=Index}"); + + endpoints.MapControllerRoute( + "pages-config", + TestConstants.ConfigRoute, + new { controller = "PagesSetup", action = "Config" }); + + endpoints.MapControllerRoute( + "pages-render", + TestConstants.RenderRoute, + new { controller = "PagesSetup", action = "Render" }); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } + [Fact] public async Task EditingRequest_ValidRequest_ReturnsChromeDecoratedResponse() { // Arrange - factory.MockGraphQLClient.SendQueryAsync(Arg.Any()).Returns(TestConstants.SimpleEditingLayoutQueryResponse); - factory.MockGraphQLClient.SendQueryAsync(Arg.Any()).Returns(TestConstants.DictionaryResponseWithoutPaging); - HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); + _sourceFactory.MockGraphQLClient.SendQueryAsync(Arg.Any()).Returns(TestConstants.SimpleEditingLayoutQueryResponse); + _sourceFactory.MockGraphQLClient.SendQueryAsync(Arg.Any()).Returns(TestConstants.DictionaryResponseWithoutPaging); + + HttpClient client = _factory.CreateClient(); string url = $"/Pages/index?mode=edit&secret={TestConstants.JssEditingSecret}&sc_itemid={TestConstants.TestItemId}&sc_version=1&sc_layoutKind=final"; // Act @@ -39,46 +87,9 @@ public async Task EditingRequest_ValidRequest_ReturnsChromeDecoratedResponse() responseBody.Should().Contain(""); } - private WebApplicationFactory BuildPagesWebApplicationFactory() + public void Dispose() { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services.AddSitecoreLayoutService() - .AddSitecorePagesHandler() - .AddGraphQLWithContextHandler("default", TestConstants.ContextId, siteName: TestConstants.SiteName) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options.AddDefaultPartialView("_ComponentNotFound"); - }) - .WithSitecorePages(TestConstants.ContextId, options => { options.EditingSecret = TestConstants.JssEditingSecret; }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseMiddleware(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllerRoute( - name: "default", - pattern: "{controller=Pages}/{action=Index}"); - - endpoints.MapControllerRoute( - "pages-config", - TestConstants.ConfigRoute, - new { controller = "PagesSetup", action = "Config" }); - - endpoints.MapControllerRoute( - "pages-render", - TestConstants.RenderRoute, - new { controller = "PagesSetup", action = "Render" }); - }); - }); - }); + _factory.Dispose(); + GC.SuppressFinalize(this); } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs index 4091e3e..e72b305 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs @@ -11,13 +11,58 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Pages; -public class PagesSetupRoutingFixture(TestWebApplicationFactory factory) : IClassFixture> +public class PagesSetupRoutingFixture : IClassFixture>, IDisposable { + private readonly WebApplicationFactory _factory; + + public PagesSetupRoutingFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddSitecoreLayoutService() + .AddSitecorePagesHandler() + .AddGraphQLWithContextHandler("default", TestConstants.ContextId, siteName: TestConstants.SiteName) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options.AddDefaultPartialView("_ComponentNotFound"); + }) + .WithSitecorePages(TestConstants.ContextId, options => { options.EditingSecret = TestConstants.JssEditingSecret; }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseMiddleware(); + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Pages}/{action=Index}"); + + endpoints.MapControllerRoute( + "pages-config", + TestConstants.ConfigRoute, + new { controller = "PagesSetup", action = "Config" }); + + endpoints.MapControllerRoute( + "pages-render", + TestConstants.RenderRoute, + new { controller = "PagesSetup", action = "Render" }); + }); + }); + }); + TestServer startedServer = _factory.Server; + } + [Fact] public async Task ConfigRoute_MissingSecret_ReturnsBadRequest() { // Arrange - HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string url = $"{TestConstants.ConfigRoute}?secret="; // Act @@ -32,7 +77,7 @@ public async Task ConfigRoute_MissingSecret_ReturnsBadRequest() public async Task ConfigRoute_InvalidSecret_ReturnsBadRequest() { // Arrange - HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string url = $"{TestConstants.ConfigRoute}?secret=invalid_secret_value"; // Act @@ -47,7 +92,7 @@ public async Task ConfigRoute_InvalidSecret_ReturnsBadRequest() public async Task ConfigRoute_InvalidRequestOrigin_ReturnsBadRequest() { // Arrange - HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string url = $"{TestConstants.ConfigRoute}?secret={TestConstants.JssEditingSecret}"; client.DefaultRequestHeaders.Add("Origin", "http://invalid_origin_domain.com"); @@ -63,7 +108,7 @@ public async Task ConfigRoute_InvalidRequestOrigin_ReturnsBadRequest() public async Task ConfigRoute_ValidCall_ReturnsCorrectObject() { // Arrange - HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string url = $"{TestConstants.ConfigRoute}?secret={TestConstants.JssEditingSecret}"; client.DefaultRequestHeaders.Add("Origin", "https://pages.sitecorecloud.io"); @@ -84,7 +129,7 @@ public async Task ConfigRoute_ValidCall_ReturnsCorrectObject() public async Task RenderRoute_MissingSecret_ReturnsBadRequest() { // Arrange - HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string url = $"{TestConstants.RenderRoute}?secret="; // Act @@ -99,7 +144,7 @@ public async Task RenderRoute_MissingSecret_ReturnsBadRequest() public async Task RenderRoute_InvalidSecret_ReturnsBadRequest() { // Arrange - HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); string url = $"{TestConstants.RenderRoute}?secret=invalid_secret_value"; // Act @@ -114,7 +159,7 @@ public async Task RenderRoute_InvalidSecret_ReturnsBadRequest() public async Task RenderRoute_ValidCall_ReturnsCorrectResponse() { // Arrange - HttpClient client = BuildPagesWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); Guid itemId = Guid.NewGuid(); string language = "en"; string layoutKind = "final"; @@ -133,46 +178,9 @@ public async Task RenderRoute_ValidCall_ReturnsCorrectResponse() response.StatusCode.Should().Be(HttpStatusCode.Redirect); } - private WebApplicationFactory BuildPagesWebApplicationFactory() + public void Dispose() { - return factory - .WithWebHostBuilder(builder => - { - builder.ConfigureTestServices(services => - { - services.AddSitecoreLayoutService() - .AddSitecorePagesHandler() - .AddGraphQLWithContextHandler("default", TestConstants.ContextId, siteName: TestConstants.SiteName) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options.AddDefaultPartialView("_ComponentNotFound"); - }) - .WithSitecorePages(TestConstants.ContextId, options => { options.EditingSecret = TestConstants.JssEditingSecret; }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseMiddleware(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllerRoute( - name: "default", - pattern: "{controller=Pages}/{action=Index}"); - - endpoints.MapControllerRoute( - "pages-config", - TestConstants.ConfigRoute, - new { controller = "PagesSetup", action = "Config" }); - - endpoints.MapControllerRoute( - "pages-render", - TestConstants.RenderRoute, - new { controller = "PagesSetup", action = "Render" }); - }); - }); - }); + _factory.Dispose(); + GC.SuppressFinalize(this); } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs index 690f0e8..220103b 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs @@ -3,6 +3,7 @@ using GraphQL; using GraphQL.Client.Abstractions; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using NSubstitute; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Mocks; @@ -13,45 +14,16 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.SearchOptimization; -public class EdgeSitemapProxyFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class EdgeSitemapProxyFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly ISitemapService _mockSitemapService = Substitute.For(); private readonly Uri _edgeSitemapUrl = new("https://xmcloud-test.com/sitemap.xml"); + private readonly WebApplicationFactory _factory; - [Fact] - public async Task EdgeSitemap_MustBeProxied() + public EdgeSitemapProxyFixture(TestWebApplicationFactory factory) { - // Arrange - HttpClient client = BuildEdgeSitemapWebApplicationFactory().CreateClient(); - HttpRequestMessage request = new(HttpMethod.Get, new Uri("/sitemap.xml", UriKind.Relative)); - _mockSitemapService.GetSitemapUrl(Arg.Any(), Arg.Any()) - .Returns(_edgeSitemapUrl.AbsoluteUri); - - // Act - await client.SendAsync(request); - - // Asserts - _mockClientHandler.Requests.Should().ContainSingle(); - _mockClientHandler.Requests[0].RequestUri!.Host.Should().Be(_edgeSitemapUrl.Host); - _mockClientHandler.Requests[0].RequestUri!.Scheme.Should().Be(_edgeSitemapUrl.Scheme); - _mockClientHandler.Requests[0].RequestUri!.PathAndQuery.Should().Be("/sitemap.xml"); - } - - public void Dispose() - { - _mockClientHandler.Dispose(); - GC.SuppressFinalize(this); - } - - private WebApplicationFactory BuildEdgeSitemapWebApplicationFactory() - { - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK - }); - - return factory.WithWebHostBuilder(builder => + _factory = factory.WithWebHostBuilder(builder => { builder.ConfigureServices(services => { @@ -89,5 +61,39 @@ private WebApplicationFactory BuildEdgeSitemapWebAppl app.UseSitemap(); }); }); + + TestServer startedServer = _factory.Server; + } + + [Fact] + public async Task EdgeSitemap_MustBeProxied() + { + // Arrange - push per-test response + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK + }); + + _mockSitemapService.GetSitemapUrl(Arg.Any(), Arg.Any()) + .Returns(_edgeSitemapUrl.AbsoluteUri); + + HttpClient client = _factory.CreateClient(); + HttpRequestMessage request = new(HttpMethod.Get, new Uri("/sitemap.xml", UriKind.Relative)); + + // Act + await client.SendAsync(request); + + // Asserts + _mockClientHandler.Requests.Should().ContainSingle(); + _mockClientHandler.Requests[0].RequestUri!.Host.Should().Be(_edgeSitemapUrl.Host); + _mockClientHandler.Requests[0].RequestUri!.Scheme.Should().Be(_edgeSitemapUrl.Scheme); + _mockClientHandler.Requests[0].RequestUri!.PathAndQuery.Should().Be("/sitemap.xml"); + } + + public void Dispose() + { + _mockClientHandler.Dispose(); + _factory.Dispose(); + GC.SuppressFinalize(this); } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/SitemapProxyFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/SitemapProxyFixture.cs index 5434b61..31f3718 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/SitemapProxyFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/SitemapProxyFixture.cs @@ -1,6 +1,7 @@ using System.Net; using AwesomeAssertions; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.Mocks; using Sitecore.AspNetCore.SDK.SearchOptimization.Extensions; @@ -8,16 +9,46 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.SearchOptimization; -public class SitemapProxyFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class SitemapProxyFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _cdInstanceUri = new("http://cd"); + private readonly WebApplicationFactory _factory; + + public SitemapProxyFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK + }); + + builder.ConfigureServices(services => + { + services.AddSingleton(_ => + { + return new CustomHttpClientFactory( + () => new HttpClient(_mockClientHandler)); + }); + + services.AddSitemap(c => c.Url = _cdInstanceUri); + }); + + builder.Configure(app => + { + app.UseSitemap(); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task SitemapRequest_MustBeProxied() { // Arrange - HttpClient client = BuildSitemapProxyWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); HttpRequestMessage request = new(HttpMethod.Get, new Uri("/sitemap.xml", UriKind.Relative)); // Act @@ -33,33 +64,7 @@ public async Task SitemapRequest_MustBeProxied() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildSitemapProxyWebApplicationFactory() - { - _mockClientHandler.Responses.Push(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK - }); - - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services.AddSingleton(_ => - { - return new CustomHttpClientFactory( - () => new HttpClient(_mockClientHandler)); - }); - - services.AddSitemap(c => c.Url = _cdInstanceUri); - }); - - builder.Configure(app => - { - app.UseSitemap(); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs index ee5f7f9..d6b06c6 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs @@ -3,6 +3,7 @@ using AwesomeAssertions; using HtmlAgilityPack; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -12,10 +13,44 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class AllFieldTagHelpersFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class AllFieldTagHelpersFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public AllFieldTagHelpersFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-All-Field-Types", "ComponentWithAllFieldTypes") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task ComponentWithAllFieldTypes_RendersFieldsCorrectly() @@ -27,7 +62,7 @@ public async Task ComponentWithAllFieldTypes_RendersFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildAllFieldTagHelpersWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -60,37 +95,7 @@ public async Task ComponentWithAllFieldTypes_RendersFieldsCorrectly() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildAllFieldTagHelpersWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-All-Field-Types", "ComponentWithAllFieldTypes") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/DateFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/DateFieldTagHelperFixture.cs index 384b01d..65998bc 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/DateFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/DateFieldTagHelperFixture.cs @@ -3,6 +3,7 @@ using AwesomeAssertions; using HtmlAgilityPack; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -11,10 +12,44 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class DateFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class DateFieldTagHelperFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public DateFieldTagHelperFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Dates", "ComponentWithDates") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task DateTagHelper_DoesNotResetOtherTagHelperOutput() @@ -26,7 +61,7 @@ public async Task DateTagHelper_DoesNotResetOtherTagHelperOutput() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildDateFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -51,7 +86,7 @@ public async Task DateTagHelper_GeneratesProperDate() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildDateFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -70,37 +105,7 @@ public async Task DateTagHelper_GeneratesProperDate() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildDateFieldTagHelperWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Dates", "ComponentWithDates") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/FileFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/FileFieldTagHelperFixture.cs index 992bec6..6c3e315 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/FileFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/FileFieldTagHelperFixture.cs @@ -2,6 +2,7 @@ using AwesomeAssertions; using HtmlAgilityPack; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -10,10 +11,46 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class FileFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class FileFieldTagHelperFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public FileFieldTagHelperFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Files", "ComponentWithFiles") + .AddDefaultComponentRenderer(); + }); + + services.AddControllersWithViews(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task FileTagHelper_RendersAttributeFromModel() @@ -25,7 +62,7 @@ public async Task FileTagHelper_RendersAttributeFromModel() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildFileFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -75,7 +112,7 @@ public async Task FileTagHelper_RendersCustomTagsAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildFileFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -136,7 +173,7 @@ public async Task FileTagHelper_OverridesModelAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildFileFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -185,7 +222,7 @@ public async Task FileTagHelper_RendersInnerHtml() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildFileFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -208,37 +245,7 @@ public async Task FileTagHelper_RendersInnerHtml() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildFileFieldTagHelperWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Files", "ComponentWithFiles") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs index da699e2..4729488 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs @@ -2,6 +2,7 @@ using AwesomeAssertions; using HtmlAgilityPack; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; @@ -12,10 +13,48 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class ImageFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class ImageFieldTagHelperFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public ImageFieldTagHelperFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Images", "ComponentWithImages") + .AddViewComponent("Component-1", "Component1") + .AddModelBoundView("Component-2", "Component2") + .AddDefaultComponentRenderer(); + }); + + services.AddControllersWithViews(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task ImgTagHelper_GeneratedProperImageWithCustomAttributes() @@ -27,7 +66,7 @@ public async Task ImgTagHelper_GeneratedProperImageWithCustomAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.PageWithPreview)) }); - HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -51,7 +90,7 @@ public async Task ImgTagHelper_GeneratesImageTags() Content = new StringContent(Serializer.Serialize(CannedResponses.PageWithPreview)) }); - HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -75,7 +114,7 @@ public async Task ImgTagHelper_GeneratedProperHtmlWithoutTagName() Content = new StringContent(Serializer.Serialize(CannedResponses.PageWithPreview)) }); - HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -99,7 +138,7 @@ public async Task ImgTagHelper_GeneratesProperImageUrlIncludingImageParams() Content = new StringContent(Serializer.Serialize(CannedResponses.PageWithPreview)) }); - HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -125,7 +164,7 @@ public async Task ImgTagHelper_GeneratesProperEditableImageMarkupWithCustomPrope Content = new StringContent(Serializer.Serialize(CannedResponses.EditablePage)) }); - HttpClient client = BuildImageFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -146,39 +185,7 @@ public async Task ImgTagHelper_GeneratesProperEditableImageMarkupWithCustomPrope public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildImageFieldTagHelperWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Images", "ComponentWithImages") - .AddViewComponent("Component-1", "Component1") - .AddModelBoundView("Component-2", "Component2") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs index 3d327cb..3ae6957 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs @@ -2,6 +2,7 @@ using AwesomeAssertions; using HtmlAgilityPack; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -10,10 +11,46 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class LinkFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class LinkFieldTagHelperFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public LinkFieldTagHelperFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Links", "ComponentWithLinks") + .AddDefaultComponentRenderer(); + }); + + services.AddControllersWithViews(); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task LinkTagHelper_DoesNotResetOtherTagHelperOutput() @@ -25,7 +62,7 @@ public async Task LinkTagHelper_DoesNotResetOtherTagHelperOutput() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -50,7 +87,7 @@ public async Task LinkTagHelper_GeneratesAnchorTags() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -74,7 +111,7 @@ public async Task LinkTagHelper_PrioritizeUserProvidedLinkText() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -98,7 +135,7 @@ public async Task LinkTagHelper_RenderFieldLinkTextIfNoInnerContent() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -122,7 +159,7 @@ public async Task LinkTagHelper_RendersLinkAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -156,7 +193,7 @@ public async Task LinkTagHelper_GeneratesNestedTags() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -180,7 +217,7 @@ public async Task LinkTagHelper_DoesNotTrimUserAttributes() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -204,7 +241,7 @@ public async Task LinkTagHelper_RenderFieldAuthorLinkTextInEEIfEditableTrue() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -228,7 +265,7 @@ public async Task LinkTagHelper_RenderFieldCustomLinkTextInEEIfEditableFalse() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildLinkFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -245,37 +282,7 @@ public async Task LinkTagHelper_RenderFieldCustomLinkTextInEEIfEditableFalse() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildLinkFieldTagHelperWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Links", "ComponentWithLinks") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs index 0b352a7..6af834c 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs @@ -3,6 +3,7 @@ using AwesomeAssertions; using HtmlAgilityPack; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -11,12 +12,47 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class NumberFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class NumberFieldTagHelperFixture : IClassFixture>, IDisposable { private const decimal TestValue = 1.21M; private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public NumberFieldTagHelperFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-With-Number", "ComponentWithNumber") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + // ensure host started so services are available and analyzers are happy + TestServer startedServer = _factory.Server; + } + [Fact] public async Task NumberTagHelper_DoesNotResetOtherTagHelperOutput() { @@ -27,7 +63,7 @@ public async Task NumberTagHelper_DoesNotResetOtherTagHelperOutput() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildNumberFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -52,7 +88,7 @@ public async Task NumberHelper_GeneratesProperNumber() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildNumberFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -71,36 +107,7 @@ public async Task NumberHelper_GeneratesProperNumber() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildNumberFieldTagHelperWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-With-Number", "ComponentWithNumber") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs index 2dbae47..20fe6c1 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs @@ -1,6 +1,7 @@ using System.Net; using AwesomeAssertions; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -10,10 +11,45 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class PlaceholderTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class PlaceholderTagHelperFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public PlaceholderTagHelperFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddViewComponent("Component-1", "Component1") + .AddModelBoundView("Component-2", "Component2") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task PageInNormalMode_WithNestedPlaceholderComponent_ComponentIsRenderedCorrectly() @@ -25,7 +61,7 @@ public async Task PageInNormalMode_WithNestedPlaceholderComponent_ComponentIsRen Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildPlaceholderTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -44,7 +80,7 @@ public async Task PageInEditableMode_WithComponentsAndChromes_ComponentAndChrome Content = new StringContent(Serializer.Serialize(CannedResponses.EditablePage)) }); - HttpClient client = BuildPlaceholderTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -71,7 +107,7 @@ public async Task PageInHorizonEditableMode_WithComponentsAndChromes_ComponentAn Content = new StringContent(Serializer.Serialize(CannedResponses.HorizonEditablePage)) }); - HttpClient client = BuildPlaceholderTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -91,38 +127,7 @@ public async Task PageInHorizonEditableMode_WithComponentsAndChromes_ComponentAn public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildPlaceholderTagHelperWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddViewComponent("Component-1", "Component1") - .AddModelBoundView("Component-2", "Component2") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs index 1356d4b..68b4720 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs @@ -3,6 +3,7 @@ using AwesomeAssertions; using HtmlAgilityPack; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; @@ -12,10 +13,44 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class RichTextFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class RichTextFieldTagHelperFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public RichTextFieldTagHelperFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-4", "Component4") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + TestServer startedServer = _factory.Server; + } [Fact] public async Task RichTextFieldTagHelper_DoesNotResetOtherTagHelperOutput() @@ -27,7 +62,7 @@ public async Task RichTextFieldTagHelper_DoesNotResetOtherTagHelperOutput() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildRichTextFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -51,7 +86,7 @@ public async Task RichTextFieldTagHelper_RendersFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildRichTextFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -83,7 +118,7 @@ public async Task RichTextFieldTagHelper_RendersEditableFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.HorizonEditablePage)) }); - HttpClient client = BuildRichTextFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -112,37 +147,7 @@ public async Task RichTextFieldTagHelper_RendersEditableFieldsCorrectly() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildRichTextFieldTagHelperWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-4", "Component4") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/TextFieldTagHelperFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/TextFieldTagHelperFixture.cs index 10e5490..5eea888 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/TextFieldTagHelperFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/TextFieldTagHelperFixture.cs @@ -12,10 +12,44 @@ // ReSharper disable StringLiteralTypo namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures.TagHelpers; -public class TextFieldTagHelperFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class TextFieldTagHelperFixture : IClassFixture>, IDisposable { private readonly MockHttpMessageHandler _mockClientHandler = new(); private readonly Uri _layoutServiceUri = new("http://layout.service"); + private readonly WebApplicationFactory _factory; + + public TextFieldTagHelperFixture(TestWebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + services + .AddSitecoreLayoutService() + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) + .AsDefaultHandler(); + + services.AddSitecoreRenderingEngine(options => + { + options + .AddModelBoundView("Component-3", "Component3") + .AddDefaultComponentRenderer(); + }); + }); + + builder.Configure(app => + { + app.UseRouting(); + app.UseSitecoreRenderingEngine(); + app.UseEndpoints(endpoints => + { + endpoints.MapDefaultControllerRoute(); + }); + }); + }); + + _ = _factory.Server; + } [Fact] public async Task TextFieldTagHelper_RendersFieldsCorrectly() @@ -27,7 +61,7 @@ public async Task TextFieldTagHelper_RendersFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.WithNestedPlaceholder)) }); - HttpClient client = BuildTextFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -62,7 +96,7 @@ public async Task TextFieldTagHelper_RendersEditableFieldsCorrectly() Content = new StringContent(Serializer.Serialize(CannedResponses.HorizonEditablePage)) }); - HttpClient client = BuildTextFieldTagHelperWebApplicationFactory().CreateClient(); + HttpClient client = _factory.CreateClient(); // Act string response = await client.GetStringAsync(new Uri("/", UriKind.Relative)); @@ -91,37 +125,7 @@ public async Task TextFieldTagHelper_RendersEditableFieldsCorrectly() public void Dispose() { _mockClientHandler.Dispose(); + _factory.Dispose(); GC.SuppressFinalize(this); } - - private WebApplicationFactory BuildTextFieldTagHelperWebApplicationFactory() - { - return factory.WithWebHostBuilder(builder => - { - builder.ConfigureServices(services => - { - services - .AddSitecoreLayoutService() - .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler) { BaseAddress = _layoutServiceUri }) - .AsDefaultHandler(); - - services.AddSitecoreRenderingEngine(options => - { - options - .AddModelBoundView("Component-3", "Component3") - .AddDefaultComponentRenderer(); - }); - }); - - builder.Configure(app => - { - app.UseRouting(); - app.UseSitecoreRenderingEngine(); - app.UseEndpoints(endpoints => - { - endpoints.MapDefaultControllerRoute(); - }); - }); - }); - } } \ No newline at end of file From 3c2b7f2a371be47e5e07781d2e0b43505365e334 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Fri, 26 Sep 2025 08:54:55 +0530 Subject: [PATCH 32/41] add default response and start TestServer in MultisiteFixture and setting up the response in the constructor consistently in EdgeSitemapProxyFixture --- .../Fixtures/Multisite/MultisiteFixture.cs | 8 ++++++++ .../SearchOptimization/EdgeSitemapProxyFixture.cs | 6 ++++++ 2 files changed, 14 insertions(+) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs index b3a8cc1..2653482 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Multisite/MultisiteFixture.cs @@ -84,6 +84,14 @@ public MultisiteFixture(TestWebApplicationFactory fac }); }); }); + + // provide a default per-fixture response so startup/concurrent requests don't consume per-test responses + _mockClientHandler.Responses.Push(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK + }); + + _ = _factory.Server; } [Theory] diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs index 220103b..1f4c3eb 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs @@ -62,6 +62,12 @@ public EdgeSitemapProxyFixture(TestWebApplicationFactory Date: Tue, 30 Sep 2025 09:39:40 +0530 Subject: [PATCH 33/41] Use the same approach TestServerBuilder used: register a simple mock ISitecoreLayoutClient singleton instead of constructing a sampleRequest/sampleResponse.- ExperienceEditorCustomRoutingFixture.cs --- .../ExperienceEditorCustomRoutingFixture.cs | 22 +------------------ 1 file changed, 1 insertion(+), 21 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorCustomRoutingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorCustomRoutingFixture.cs index e1f37d2..6a67f60 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorCustomRoutingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/ExperienceEditor/ExperienceEditorCustomRoutingFixture.cs @@ -64,27 +64,7 @@ private WebApplicationFactory BuildExperienceEditorCu { builder.ConfigureTestServices(services => { - ISitecoreLayoutClient layoutClientSub = Substitute.For(); - SitecoreLayoutRequest sampleRequest = []; - SitecoreLayoutResponse sampleResponse = new(sampleRequest) - { - Content = new SitecoreLayoutResponseContent - { - Sitecore = new SitecoreData - { - Route = new Route - { - DatabaseName = "master" - } - }, - ContextRawData = string.Empty - } - }; - - layoutClientSub.Request(Arg.Any()) - .Returns(Task.FromResult(sampleResponse)); - - services.AddSingleton(layoutClientSub); + services.AddSingleton(Substitute.For()); services.AddRouting(); services.AddSitecoreLayoutService(); services.AddControllersWithViews(); From 16b6bbc250d313168f9f469da9eb697b4f628c1e Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 30 Sep 2025 09:56:11 +0530 Subject: [PATCH 34/41] wire layout service to mock HttpClient in RenderingEngine benchmarks --- .../RenderingEngineBenchmarks.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/RenderingEngineBenchmarks.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/RenderingEngineBenchmarks.cs index 0cf340d..0bd58fa 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/RenderingEngineBenchmarks.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/RenderingEngineBenchmarks.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.DependencyInjection; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Interfaces; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; using Sitecore.AspNetCore.SDK.TestData; @@ -32,8 +33,12 @@ public void Setup() builder.ConfigureServices(services => { services.AddRouting(); - services.AddSitecoreLayoutService(); - services.AddHttpClient("mock").ConfigurePrimaryHttpMessageHandler(() => _mockClientHandler!); + + ISitecoreLayoutClientBuilder layoutBuilder = services.AddSitecoreLayoutService(); + layoutBuilder + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler!) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => { options.AddDefaultComponentRenderer(); From b5853768f0c7d24774e18fb1266e6b6708edb51c Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 30 Sep 2025 10:28:53 +0530 Subject: [PATCH 35/41] use app.Start() in TestWebApplicationProgram --- .../TestWebApplicationProgram.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/TestWebApplicationProgram.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/TestWebApplicationProgram.cs index ee04bae..ee6d61e 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/TestWebApplicationProgram.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/TestWebApplicationProgram.cs @@ -12,7 +12,7 @@ }); WebApplication app = builder.Build(); -app.Run(); +app.Start(); /// /// Partial class allowing this TestProgram to be created by a WebApplicationFactory for integration testing. From 05d4eaff7b8717ac703df88e7f82943b9db55ebb Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 30 Sep 2025 10:52:37 +0530 Subject: [PATCH 36/41] Add comment explaining variable startedServer --- .../Fixtures/Binding/ComplexModelBindingFixture.cs | 1 + .../Fixtures/Binding/CustomModelContextBindingFixture.cs | 1 + .../Fixtures/Binding/CustomResolverBindingFixture.cs | 1 + .../Fixtures/Binding/ModelBindingErrorHandlingFixture.cs | 1 + .../Fixtures/Binding/ViewFieldsBindingFixture.cs | 1 + .../CustomRenderTypes/LoggingComponentRendererFixture.cs | 1 + .../Fixtures/CustomRenderTypes/MultipleComponentsAddedFixture.cs | 1 + .../Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs | 1 + .../Fixtures/Pages/PagesEditingFixture.cs | 1 + .../Fixtures/Pages/PagesSetupRoutingFixture.cs | 1 + .../Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs | 1 + .../Fixtures/SearchOptimization/SitemapProxyFixture.cs | 1 + .../Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs | 1 + .../Fixtures/TagHelpers/DateFieldTagHelperFixture.cs | 1 + .../Fixtures/TagHelpers/FileFieldTagHelperFixture.cs | 1 + .../Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs | 1 + .../Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs | 1 + .../Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs | 1 + .../Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs | 1 + .../Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs | 1 + 20 files changed, 20 insertions(+) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs index c3fec8a..93c5c8a 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs @@ -47,6 +47,7 @@ public ComplexModelBindingFixture(TestWebApplicationFactory }); }); + // Accessing _factory.Server forces the TestServer to start. The variable is unused; this is intentional. TestServer startedServer = _factory.Server; } diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs index e72b305..5cfb5f9 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs @@ -55,6 +55,7 @@ public PagesSetupRoutingFixture(TestWebApplicationFactory }); }); + // Accessing _factory.Server forces the TestServer to start. The variable is unused; this is intentional. TestServer startedServer = _factory.Server; } diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs index d6b06c6..8b97584 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs @@ -49,6 +49,7 @@ public AllFieldTagHelpersFixture(TestWebApplicationFactory Date: Tue, 30 Sep 2025 11:24:52 +0530 Subject: [PATCH 37/41] Use the same layout-service builder pattern previously used in TrackingBenchmarks --- .../TrackingBenchmarks.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/TrackingBenchmarks.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/TrackingBenchmarks.cs index 1430f92..1df7f8c 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/TrackingBenchmarks.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Benchmarks/TrackingBenchmarks.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.DependencyInjection; using Sitecore.AspNetCore.SDK.AutoFixture.Mocks; using Sitecore.AspNetCore.SDK.LayoutService.Client.Extensions; +using Sitecore.AspNetCore.SDK.LayoutService.Client.Interfaces; using Sitecore.AspNetCore.SDK.RenderingEngine.Extensions; using Sitecore.AspNetCore.SDK.TestData; using Sitecore.AspNetCore.SDK.Tracking; @@ -42,8 +43,11 @@ public void TrackingBenchmarksSetup() ForwardedHeaders.XForwardedProto; }); - services.AddSitecoreLayoutService(); - services.AddHttpClient("mock").ConfigurePrimaryHttpMessageHandler(() => _mockClientHandler!); + ISitecoreLayoutClientBuilder layoutBuilder = services.AddSitecoreLayoutService(); + layoutBuilder + .AddHttpHandler("mock", _ => new HttpClient(_mockClientHandler!) { BaseAddress = new Uri("http://layout.service") }) + .AsDefaultHandler(); + services.AddSitecoreRenderingEngine(options => { options.AddDefaultComponentRenderer(); From 496fa6086aa2961d693201f8928cbff41a78cde2 Mon Sep 17 00:00:00 2001 From: krishanthaudayakumara Date: Tue, 30 Sep 2025 11:29:38 +0530 Subject: [PATCH 38/41] Minor change of new line after single line comment --- .../Fixtures/Pages/PagesSetupRoutingFixture.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs index 5cfb5f9..ec343d3 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs @@ -55,6 +55,7 @@ public PagesSetupRoutingFixture(TestWebApplicationFactory Date: Tue, 30 Sep 2025 13:33:39 +0530 Subject: [PATCH 39/41] use _ = _factory.Server; to clearly indicate the variable is intentionally unused --- .../Fixtures/Binding/ComplexModelBindingFixture.cs | 2 +- .../Fixtures/Binding/CustomModelContextBindingFixture.cs | 2 +- .../Fixtures/Binding/CustomResolverBindingFixture.cs | 2 +- .../Fixtures/Binding/ModelBindingErrorHandlingFixture.cs | 2 +- .../Fixtures/Binding/ViewFieldsBindingFixture.cs | 2 +- .../CustomRenderTypes/LoggingComponentRendererFixture.cs | 2 +- .../CustomRenderTypes/MultipleComponentsAddedFixture.cs | 2 +- .../Fixtures/CustomRenderTypes/PartialViewRendererFixture.cs | 2 +- .../Fixtures/Pages/PagesEditingFixture.cs | 2 +- .../Fixtures/Pages/PagesSetupRoutingFixture.cs | 2 +- .../Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs | 2 +- .../Fixtures/SearchOptimization/SitemapProxyFixture.cs | 2 +- .../Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs | 2 +- .../Fixtures/TagHelpers/DateFieldTagHelperFixture.cs | 2 +- .../Fixtures/TagHelpers/FileFieldTagHelperFixture.cs | 2 +- .../Fixtures/TagHelpers/ImageFieldTagHelperFixture.cs | 2 +- .../Fixtures/TagHelpers/LinkFieldTagHelperFixture.cs | 2 +- .../Fixtures/TagHelpers/NumberFieldTagHelperFixture.cs | 2 +- .../Fixtures/TagHelpers/PlaceholderTagHelperFixture.cs | 2 +- .../Fixtures/TagHelpers/RichTextFieldTagHelperFixture.cs | 2 +- 20 files changed, 20 insertions(+), 20 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs index 93c5c8a..d975c67 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Binding/ComplexModelBindingFixture.cs @@ -48,7 +48,7 @@ public ComplexModelBindingFixture(TestWebApplicationFactory }); // Accessing _factory.Server forces the TestServer to start. The variable is unused; this is intentional. - TestServer startedServer = _factory.Server; + _ = _factory.Server; } [Fact] diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs index ec343d3..e596976 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/Pages/PagesSetupRoutingFixture.cs @@ -57,7 +57,7 @@ public PagesSetupRoutingFixture(TestWebApplicationFactory }); // Accessing _factory.Server forces the TestServer to start. The variable is unused; this is intentional. - TestServer startedServer = _factory.Server; + _ = _factory.Server; } [Fact] diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs index 8b97584..e0bfcd8 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/TagHelpers/AllFieldTagHelpersFixture.cs @@ -50,7 +50,7 @@ public AllFieldTagHelpersFixture(TestWebApplicationFactory Date: Tue, 30 Sep 2025 13:37:44 +0530 Subject: [PATCH 40/41] using the more modern collection expression syntax for consistency in EdgeSitemapProxyFixture --- .../Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs index a86d497..4f797b6 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/SearchOptimization/EdgeSitemapProxyFixture.cs @@ -46,7 +46,7 @@ public EdgeSitemapProxyFixture(TestWebApplicationFactory Date: Tue, 30 Sep 2025 13:59:32 +0530 Subject: [PATCH 41/41] Refactor RequestHeadersValidationFixture to implement similar constructor pattern like other fixtures --- .../Fixtures/RequestHeadersValidationFixture.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestHeadersValidationFixture.cs b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestHeadersValidationFixture.cs index 37d65b6..ef1e623 100644 --- a/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestHeadersValidationFixture.cs +++ b/tests/Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests/Fixtures/RequestHeadersValidationFixture.cs @@ -11,16 +11,22 @@ namespace Sitecore.AspNetCore.SDK.RenderingEngine.Integration.Tests.Fixtures; -public class RequestHeadersValidationFixture(TestWebApplicationFactory factory) : IClassFixture>, IDisposable +public class RequestHeadersValidationFixture : IClassFixture>, IDisposable { + private readonly TestWebApplicationFactory _factory; private MockHttpMessageHandler _clientHandler = new(); private WebApplicationFactory _appFactory = null!; + public RequestHeadersValidationFixture(TestWebApplicationFactory factory) + { + _factory = factory; + } + [Fact] public async Task Request_WithNonValidatedHeaders_HeadersAreProperlyValidated() { // Arrange - _appFactory = BuildRequestHeadersWebApplicationFactory(new[] { "User-Agent" }); + _appFactory = BuildRequestHeadersWebApplicationFactory(["User-Agent"]); ISitecoreLayoutClient layoutClient = _appFactory.Services.GetRequiredService(); SitecoreLayoutRequest request = new SitecoreLayoutRequest() @@ -71,7 +77,7 @@ private WebApplicationFactory BuildRequestHeadersWebA { "User-Agent", ["site;core"] } }; - return factory.WithWebHostBuilder(builder => + return _factory.WithWebHostBuilder(builder => { builder.ConfigureServices(services => {