Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,192 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Fixtures.Common.Api;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
/// <summary>
/// Contains unit tests for the <see cref="CachedAuthorizationHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CachedAuthorizationHandlerTests
{
private const string AUTHORIZATION_ENDPOINT = "http://localhost:5214/api/v1/auth/get-authorization";
private const string LOGIN_ENDPOINT = "http://localhost:5214/api/v1/auth/login";
private readonly HybridCache _hybridCache;
/// <summary>
/// Initializes a new instance of the <see cref="CachedAuthorizationHandlerTests"/> class.
/// </summary>
public CachedAuthorizationHandlerTests()
{
ServiceCollection services = new();
services.AddHybridCache();
_hybridCache = services.BuildServiceProvider().GetRequiredService<HybridCache>();
}
[Fact]
public async Task SendAsync_WhenAuthorizationRequestIsServedTwice_ShouldCallInnerHandlerOnlyOnce()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}"""));
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
// Act
HttpResponseMessage firstResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
HttpResponseMessage secondResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
// Assert
Assert.Single(messageHandler.Requests);
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
Assert.Equal(await firstResponse.Content.ReadAsStringAsync(), await secondResponse.Content.ReadAsStringAsync());
}
[Fact]
public async Task SendAsync_WhenNonAuthorizationRequestIsServedTwice_ShouldCallInnerHandlerTwice()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]"""));
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenLoginRequestFollowsCachedAuthorizationRequest_ShouldInvalidateCachedAuthorization()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}"""));
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
// Act
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
await client.PostAsync(LOGIN_ENDPOINT, new StringContent("""{"username":"testuser","password":"TestPass123!"}""", Encoding.UTF8, "application/json"), CancellationToken.None);
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
// Assert
Assert.Equal(3, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenAuthorizationReturnsUnauthorized_ShouldNotRetainTheCachedResponse()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.Unauthorized, """{"title":"Unauthorized"}"""));
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
// Act
HttpResponseMessage firstResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
HttpResponseMessage secondResponse = await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
Assert.Equal(HttpStatusCode.Unauthorized, firstResponse.StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, secondResponse.StatusCode);
}
[Fact]
public async Task SendAsync_WhenAuthorizationReturnsNotFound_ShouldNotRetainTheCachedResponse()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.NotFound, """{"title":"NotFound"}"""));
HttpClient client = CreateClient(userId: Guid.NewGuid(), messageHandler);
// Act
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenAuthorizationRequestIsMadeWithoutAuthenticatedUser_ShouldStillCacheTheResponse()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}"""));
HttpClient client = CreateClient(userId: null, messageHandler);
// Act
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
await client.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
// Assert
Assert.Single(messageHandler.Requests);
}
[Fact]
public async Task SendAsync_WhenDifferentUsersRequestAuthorization_ShouldServeSeparateCachedResponses()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"role":"Admin","permissions":[]}"""));
HttpClient firstClient = CreateClient(userId: Guid.NewGuid(), messageHandler);
HttpClient secondClient = CreateClient(userId: Guid.NewGuid(), messageHandler);
// Act
await firstClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
await firstClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
// Assert
Assert.Equal(1, messageHandler.Requests.Count);
// Act
await secondClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
await secondClient.GetAsync(AUTHORIZATION_ENDPOINT, CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
/// <summary>
/// Creates an <see cref="HttpClient"/> that pipes requests through a <see cref="CachedAuthorizationHandler"/> backed by the given inner handler.
/// </summary>
/// <param name="userId">The user id claim placed on the current HTTP context user, <see langword="null"/> for anonymous requests.</param>
/// <param name="messageHandler">The message handler backing the inner <see cref="HttpClient"/> pipeline.</param>
/// <returns>The created <see cref="HttpClient"/>.</returns>
private HttpClient CreateClient(Guid? userId, TestApiHttpMessageHandler messageHandler)
{
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
DefaultHttpContext httpContext = new();
if (userId is not null)
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuthentication"));
httpContextAccessor.HttpContext.Returns(httpContext);
CachedAuthorizationHandler authorizationHandler = new(_hybridCache, httpContextAccessor)
{
InnerHandler = messageHandler
};
return new HttpClient(authorizationHandler);
}
/// <summary>
/// Creates an <see cref="HttpResponseMessage"/> with the given status code and JSON body.
/// </summary>
/// <param name="statusCode">The HTTP status code of the response.</param>
/// <param name="json">The JSON payload of the response body.</param>
/// <returns>The created <see cref="HttpResponseMessage"/>.</returns>
private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json)
{
return new HttpResponseMessage(statusCode)
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
}
}
@@ -0,0 +1,157 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Fixtures.Common.Api;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
/// <summary>
/// Contains unit tests for the <see cref="CachedThemeHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CachedThemeHandlerTests
{
private readonly HybridCache _hybridCache;
private readonly ThemeCachePreferenceService _themeCachePreferenceService;
/// <summary>
/// Initializes a new instance of the <see cref="CachedThemeHandlerTests"/> class.
/// </summary>
public CachedThemeHandlerTests()
{
ServiceCollection services = new();
services.AddHybridCache();
_hybridCache = services.BuildServiceProvider().GetRequiredService<HybridCache>();
_themeCachePreferenceService = new ThemeCachePreferenceService(_hybridCache);
}
[Fact]
public async Task SendAsync_WhenThemeGetRequestIsServedTwice_ShouldCallInnerHandlerOnlyOnce()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}"""));
HttpClient client = CreateClient(messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/templates/shared/layout", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/templates/shared/layout", CancellationToken.None);
// Assert
Assert.Single(messageHandler.Requests);
}
[Fact]
public async Task SendAsync_WhenNonThemeGetRequestIsServedTwice_ShouldCallInnerHandlerTwice()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]"""));
HttpClient client = CreateClient(messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenThemeMutationIsPerformed_ShouldInvalidateCachedThemeResponses()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}"""));
HttpClient client = CreateClient(messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
await client.PutAsync("http://localhost:5214/api/v1/themes/current", new StringContent("""{"themeId":"lumina-default"}""", Encoding.UTF8, "application/json"), CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
// Assert
Assert.Equal(3, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenThemeGetRequestFails_ShouldNotRetainTheFailedResponse()
{
// Arrange
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.InternalServerError));
HttpClient client = CreateClient(messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenThemeGetResponseExceedsMaxCacheableSize_ShouldNotCacheIt()
{
// Arrange
byte[] largeContent = new byte[600 * 1024];
TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(largeContent) });
HttpClient client = CreateClient(messageHandler);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/assets/preview.png", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/assets/preview.png", CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
[Fact]
public async Task SendAsync_WhenUserDisablesThemeCaching_ShouldCallInnerHandlerForEveryRequest()
{
// Arrange
Guid userId = Guid.NewGuid();
TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}"""));
HttpClient client = CreateClient(messageHandler, userId: userId);
await _themeCachePreferenceService.SetAsync(userId, isEnabled: false, CancellationToken.None);
// Act
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None);
// Assert
Assert.Equal(2, messageHandler.Requests.Count);
}
private HttpClient CreateClient(TestApiHttpMessageHandler messageHandler, Guid? userId = null)
{
IHttpContextAccessor httpContextAccessor = Substitute.For<IHttpContextAccessor>();
if (userId is not null)
{
DefaultHttpContext httpContext = new();
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuthentication"));
httpContextAccessor.HttpContext.Returns(httpContext);
}
CachedThemeHandler themeHandler = new(_hybridCache, httpContextAccessor, _themeCachePreferenceService)
{
InnerHandler = messageHandler
};
return new HttpClient(themeHandler);
}
private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json)
{
return new HttpResponseMessage(statusCode)
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Services;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
/// <summary>
/// Contains unit tests for the <see cref="ScriptIdentifierHelper"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScriptIdentifierHelperTests
{
[Fact]
public void GenerateScriptId_WhenCalled_ShouldReturnScriptPrefixedIdentifier()
{
// Act
string scriptId = ScriptIdentifierHelper.GenerateScriptId();
// Assert
Assert.StartsWith("script_", scriptId);
Assert.True(Guid.TryParse(scriptId.AsSpan("script_".Length), out _));
}
[Fact]
public void GenerateScriptId_WhenCalledTwice_ShouldReturnDistinctIdentifiers()
{
// Act
string firstScriptId = ScriptIdentifierHelper.GenerateScriptId();
string secondScriptId = ScriptIdentifierHelper.GenerateScriptId();
// Assert
Assert.NotEqual(firstScriptId, secondScriptId);
}
[Fact]
public void ClearIdentifier_WhenCalledWithGeneratedIdentifier_ShouldNotThrow()
{
// Arrange
string scriptId = ScriptIdentifierHelper.GenerateScriptId();
// Act
ScriptIdentifierHelper.ClearIdentifier(scriptId);
// Assert
Assert.NotNull(scriptId);
}
}
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Services;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
/// <summary>
/// Contains unit tests for the <see cref="ThemeCachePreferenceService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeCachePreferenceServiceTests
{
private readonly HybridCache _hybridCache;
private readonly ThemeCachePreferenceService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeCachePreferenceService"/> class.
/// </summary>
public ThemeCachePreferenceServiceTests()
{
ServiceCollection services = new();
services.AddHybridCache();
_hybridCache = services.BuildServiceProvider().GetRequiredService<HybridCache>();
_sut = new ThemeCachePreferenceService(_hybridCache);
}
[Fact]
public async Task GetAsync_WhenNoPreferenceStored_ShouldReturnDefaultValue()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: true, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task GetAsync_WhenNoPreferenceStoredAndDefaultIsFalse_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: false, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task SetAsync_WhenPreferenceStored_ShouldReturnTheStoredValue()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None);
bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: false, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task SetAsync_WhenPreferenceOverwritten_ShouldReturnTheNewValue()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None);
await _sut.SetAsync(userId, isEnabled: false, CancellationToken.None);
bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: true, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task SetAsync_WhenStoredForOneUser_ShouldNotAffectAnotherUser()
{
// Arrange
Guid firstUserId = Guid.NewGuid();
Guid secondUserId = Guid.NewGuid();
// Act
await _sut.SetAsync(firstUserId, isEnabled: true, CancellationToken.None);
bool firstUserResult = await _sut.GetAsync(firstUserId, isCachingEnabledByDefault: false, CancellationToken.None);
bool secondUserResult = await _sut.GetAsync(secondUserId, isCachingEnabledByDefault: false, CancellationToken.None);
// Assert
Assert.True(firstUserResult);
Assert.False(secondUserResult);
}
}
@@ -0,0 +1,293 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Services;
/// <summary>
/// Contains unit tests for the <see cref="UrlService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UrlServiceTests
{
private readonly IHttpContextAccessor _mockHttpContextAccessor;
private readonly UrlService _sut;
/// <summary>
/// Initializes a new instance of the <see cref="UrlServiceTests"/> class.
/// </summary>
public UrlServiceTests()
{
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
_sut = new UrlService(_mockHttpContextAccessor);
}
[Fact]
public void GetAbsoluteUrl_WhenRouteTemplateIsNotDefined_ShouldThrowArgumentException()
{
// Act
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.GetAbsoluteUrl("/not-a-real-route"));
// Assert
Assert.Equal("routeTemplate", exception.ParamName);
Assert.Contains("The route template '/not-a-real-route' is not defined in the WebRoutes constants.", exception.Message);
}
[Fact]
public void GetAbsoluteUrl_WhenHttpContextIsNull_ShouldReturnNull()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Null(url);
}
[Fact]
public void GetAbsoluteUrl_WhenCalled_ShouldReplaceCulturePlaceholderAndBuildAbsoluteUrl()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "http";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Equal("http://localhost:5012/en-us/auth/api-login", url);
}
[Fact]
public void GetAbsoluteUrl_WhenCalledWithAdditionalRouteValues_ShouldReplacePlaceholders()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "http";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
Guid id = Guid.NewGuid();
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
// Assert
Assert.Equal($"http://localhost:5012/en-us/libraries/manage/api-item/{id}", url);
}
[Fact]
public void GetAbsoluteUrl_WhenPathBaseIsPresent_ShouldIncludePathBase()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "de-de");
httpContext.Request.PathBase = "/lumina";
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "https";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW);
// Assert
Assert.Equal("https://localhost:5012/lumina/de-de/auth/register", url);
}
[Fact]
public void GetAbsoluteUrl_WhenRouteTemplateDoesNotStartWithSlash_ShouldPrependSlash()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "http";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.FileSystem.GET_TYPE);
// Assert
Assert.Equal("http://localhost:5012/file-system/api-get-type", url);
}
[Fact]
public void GetRelativeUrl_WhenRouteTemplateIsNotDefined_ShouldThrowArgumentException()
{
// Act
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.GetRelativeUrl("/not-a-real-route"));
// Assert
Assert.Equal("routeTemplate", exception.ParamName);
Assert.Contains("The route template '/not-a-real-route' is not defined in the WebRoutes constants.", exception.Message);
}
[Fact]
public void GetRelativeUrl_WhenHttpContextIsNull_ShouldReturnNull()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Null(url);
}
[Fact]
public void GetRelativeUrl_WhenCalled_ShouldReturnCultureLocalizedPathWithoutSchemeOrHost()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Equal("/en-us/auth/api-login", url);
}
[Fact]
public void GetRelativeUrl_WhenCultureRouteValueIsAbsent_ShouldFallBackToDefaultCulture()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: null));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN);
// Assert
Assert.Equal("/en-US/auth/api-login", url);
}
[Fact]
public void GetRelativeUrl_WhenCalledWithAdditionalRouteValues_ShouldReplacePlaceholders()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
Guid id = Guid.NewGuid();
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
// Assert
Assert.Equal($"/en-us/libraries/manage/api-item/{id}", url);
}
[Fact]
public void GetRelativeUrl_WhenRouteTemplateDoesNotStartWithSlash_ShouldPrependSlash()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.FileSystem.GET_TYPE);
// Assert
Assert.Equal("/file-system/api-get-type", url);
}
[Fact]
public void GetRelativeUrl_WhenPathBaseIsPresent_ShouldIncludePathBaseWithoutSchemeOrHost()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "de-de");
httpContext.Request.PathBase = "/lumina";
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "https";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.REGISTER_VIEW);
// Assert
Assert.Equal("/lumina/de-de/auth/register", url);
}
[Fact]
public void GetRelativeUrl_WhenOptionalRouteValueIsNotSupplied_ShouldRemoveOptionalSegment()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN_VIEW);
// Assert
Assert.Equal("/en-us/auth/login", url);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void GetRelativeUrl_WhenOptionalRouteValueIsEmpty_ShouldRemoveOptionalSegment(string? returnUrl)
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN_VIEW, new { returnUrl });
// Assert
Assert.Equal("/en-us/auth/login", url);
}
[Fact]
public void GetRelativeUrl_WhenOptionalRouteValueIsSupplied_ShouldReplaceOptionalPlaceholder()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(culture: "en-us"));
// Act
string? url = _sut.GetRelativeUrl(WebRoutes.Authentication.LOGIN_VIEW, new { returnUrl = "libraries" });
// Assert
Assert.Equal("/en-us/auth/login/libraries", url);
}
[Fact]
public void GetAbsoluteUrl_WhenOptionalRouteValueIsNotSupplied_ShouldBuildWellFormedUrl()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "en-us");
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "http";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
string? url = _sut.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW);
// Assert
Assert.Equal("http://localhost:5012/en-us/auth/login", url);
}
[Fact]
public void GetAbsoluteUrl_WhenCalled_ShouldComposeSchemeAndHostWithRelativeUrl()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create(culture: "de-de");
httpContext.Request.PathBase = "/lumina";
httpContext.Request.Host = new HostString("localhost:5012");
httpContext.Request.Scheme = "https";
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
Guid id = Guid.NewGuid();
// Act
string? relativeUrl = _sut.GetRelativeUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
string? absoluteUrl = _sut.GetAbsoluteUrl(WebRoutes.LibraryManagement.DELETE_LIBRARY, new { id });
// Assert
Assert.NotNull(relativeUrl);
Assert.Equal($"https://localhost:5012{relativeUrl}", absoluteUrl);
}
}