From 468f1846f1bc77adc3fa94c65e2001c0059c4ae1 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 28 Oct 2026 23:50:00 +0200 Subject: [PATCH] Implements tests for commit 2e9f7d8496ee7169ec981173293212944186f091 --- .../ValidatorUtilitiesTestRequest.cs | 5 +- .../ValidatorUtilitiesTestRequestFixture.cs | 22 +- .../UpdateUserSettingsCommandFixture.cs | 42 +- .../UpdateUserSettingsRequestFixture.cs | 42 +- .../UsersManagement/UserSettingsDtoFixture.cs | 56 ++- .../Users/UserSettingsRepositoryTests.cs | 50 ++ .../GetUserSettingsEndpointTests.cs | 30 +- .../UpdateUserSettingsEndpointTests.cs | 383 ++++++++++++++- .../GetUserSettingsEndpointTests.cs | 42 ++ .../UpdateUserSettingsEndpointTests.cs | 39 ++ .../UpdateUserSettingsEndpointTests.cs | 220 +++++++++ .../UpdateUserSettingsRequestMappingTests.cs | 30 +- .../Utilities/ValidatorUtilitiesTests.cs | 121 +++++ .../UpdateUserSettingsCommandHandlerTests.cs | 22 +- ...UpdateUserSettingsCommandValidatorTests.cs | 449 ++++++++++++++++++ .../UserSettingsConfigurationTests.cs | 39 ++ .../UserSettingsTests.cs | 129 ++++- .../UpdateUserSettingsEndpointTests.cs | 38 ++ 18 files changed, 1711 insertions(+), 48 deletions(-) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs index b31ea1e9..c15401c5 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs @@ -36,4 +36,7 @@ public sealed record ValidatorUtilitiesTestRequest( int? InclusiveNullableIntValue, string? EqualValue, string? EqualComparisonValue, - string? TextualEnumValue); + string? TextualEnumValue, + double? NullableDoubleValue, + double? NullableDoubleComparisonValue, + double? InclusiveNullableDoubleValue); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs index db7cd22f..8fa4849d 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs @@ -15,6 +15,9 @@ namespace Lumina.Application.Fixtures.Common.Utilities; public class ValidatorUtilitiesTestRequestFixture { private const string ValidPattern = "^[a-z]{3}-\\d{3}$"; + private const double VALID_NULLABLE_DOUBLE_VALUE = 7.5; + private const double VALID_NULLABLE_DOUBLE_COMPARISON_VALUE = 5.0; + private const double VALID_INCLUSIVE_NULLABLE_DOUBLE_VALUE = 5.0; /// /// Creates a new instance with randomized test data that satisfies all validation rules. @@ -45,6 +48,12 @@ public class ValidatorUtilitiesTestRequestFixture /// Optional. The value that must equal the comparison value. /// Optional. The comparison value. /// Optional. The textual enum value that must be a member name of the test enumeration. + /// Optional. The nullable double value that must be greater than or equal to the selected comparison value. + /// Optional. The nullable double comparison value selected from the request. + /// Optional. The nullable double value that must be between 1 and 10. + /// Whether to generate the nullable double value, or leave it . + /// Whether to generate the nullable double comparison value, or leave it . + /// Whether to generate the inclusive nullable double value, or leave it . /// A configured instance. public ValidatorUtilitiesTestRequest Create( int? intValue = null, @@ -72,7 +81,13 @@ public class ValidatorUtilitiesTestRequestFixture int? inclusiveNullableIntValue = null, string? equalValue = null, string? equalComparisonValue = null, - string? textualEnumValue = null) + string? textualEnumValue = null, + double? nullableDoubleValue = null, + double? nullableDoubleComparisonValue = null, + double? inclusiveNullableDoubleValue = null, + bool includeNullableDoubleValue = true, + bool includeNullableDoubleComparisonValue = true, + bool includeInclusiveNullableDoubleValue = true) { string resolvedPattern = patternValue ?? ValidPattern; return new Faker() @@ -102,7 +117,10 @@ public class ValidatorUtilitiesTestRequestFixture InclusiveNullableIntValue: inclusiveNullableIntValue ?? f.Random.Int(1, 10), EqualValue: equalValue ?? "same", EqualComparisonValue: equalComparisonValue ?? "same", - TextualEnumValue: textualEnumValue ?? f.PickRandom().ToString())) + TextualEnumValue: textualEnumValue ?? f.PickRandom().ToString(), + NullableDoubleValue: includeNullableDoubleValue ? nullableDoubleValue ?? VALID_NULLABLE_DOUBLE_VALUE : null, + NullableDoubleComparisonValue: includeNullableDoubleComparisonValue ? nullableDoubleComparisonValue ?? VALID_NULLABLE_DOUBLE_COMPARISON_VALUE : null, + InclusiveNullableDoubleValue: includeInclusiveNullableDoubleValue ? inclusiveNullableDoubleValue ?? VALID_INCLUSIVE_NULLABLE_DOUBLE_VALUE : null)) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs index b66d28e9..b2d5e636 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs @@ -41,6 +41,15 @@ public class UpdateUserSettingsCommandFixture /// Optional. The time a peak of the VU meter is held before it starts falling. /// Optional. The number of level units the display of the VU meter falls per second when the input level drops. /// Optional. The number of level units the peak of the VU meter falls per second after its hold time elapsed. + /// Whether to generate the VU meter orientation, or leave it . + /// Whether to generate the VU meter segment count, or leave it . + /// Whether to generate the VU meter segment gap, or leave it . + /// Whether to generate the VU meter medium threshold, or leave it . + /// Whether to generate the VU meter high threshold, or leave it . + /// Whether to generate the VU meter peak marker setting, or leave it . + /// Whether to generate the VU meter peak hold duration, or leave it . + /// Whether to generate the VU meter release rate, or leave it . + /// Whether to generate the VU meter peak release rate, or leave it . /// The created command. public UpdateUserSettingsCommand Create( bool? isPaginationEnabled = null, @@ -64,11 +73,24 @@ public class UpdateUserSettingsCommandFixture bool? vuMeterShowPeak = null, int? vuMeterPeakHoldDurationInMilliseconds = null, double? vuMeterReleasePerSecond = null, - double? vuMeterPeakReleasePerSecond = null) + double? vuMeterPeakReleasePerSecond = null, + bool includeVuMeterOrientation = true, + bool includeVuMeterSegmentCount = true, + bool includeVuMeterSegmentGap = true, + bool includeVuMeterMediumThreshold = true, + bool includeVuMeterHighThreshold = true, + bool includeVuMeterShowPeak = true, + bool includeVuMeterPeakHoldDurationInMilliseconds = true, + bool includeVuMeterReleasePerSecond = true, + bool includeVuMeterPeakReleasePerSecond = true) { // The high threshold is generated from the medium one, so a randomized command always describes a valid meter. - double mediumThreshold = vuMeterMediumThreshold ?? Random.Shared.NextDouble(); - double highThreshold = vuMeterHighThreshold ?? (mediumThreshold + Random.Shared.NextDouble() * (1 - mediumThreshold)); + double? mediumThreshold = includeVuMeterMediumThreshold + ? vuMeterMediumThreshold ?? Random.Shared.NextDouble() + : null; + double? highThreshold = includeVuMeterHighThreshold + ? vuMeterHighThreshold ?? (mediumThreshold is null ? Random.Shared.NextDouble() : mediumThreshold.Value + Random.Shared.NextDouble() * (1 - mediumThreshold.Value)) + : null; return new Faker() .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default, default, default, default, default, default, default, default, default, default, default, default, default, default, default, default, default, default, default)) .RuleFor(x => x.IsPaginationEnabled, f => isPaginationEnabled ?? f.Random.Bool()) @@ -84,15 +106,15 @@ public class UpdateUserSettingsCommandFixture .RuleFor(x => x.IsGaplessPlaybackEnabled, f => isGaplessPlaybackEnabled ?? f.Random.Bool()) .RuleFor(x => x.ReplayGainMode, f => replayGainMode ?? f.PickRandom()) .RuleFor(x => x.StreamingQuality, f => streamingQuality ?? f.PickRandom()) - .RuleFor(x => x.VuMeterOrientation, f => vuMeterOrientation ?? f.PickRandom()) - .RuleFor(x => x.VuMeterSegmentCount, f => vuMeterSegmentCount ?? f.Random.Int(1, 128)) - .RuleFor(x => x.VuMeterSegmentGap, f => vuMeterSegmentGap ?? f.Random.Int(0, 32)) + .RuleFor(x => x.VuMeterOrientation, f => includeVuMeterOrientation ? vuMeterOrientation ?? f.PickRandom() : null) + .RuleFor(x => x.VuMeterSegmentCount, f => includeVuMeterSegmentCount ? vuMeterSegmentCount ?? f.Random.Int(1, 128) : null) + .RuleFor(x => x.VuMeterSegmentGap, f => includeVuMeterSegmentGap ? vuMeterSegmentGap ?? f.Random.Int(0, 32) : null) .RuleFor(x => x.VuMeterMediumThreshold, f => mediumThreshold) .RuleFor(x => x.VuMeterHighThreshold, f => highThreshold) - .RuleFor(x => x.VuMeterShowPeak, f => vuMeterShowPeak ?? f.Random.Bool()) - .RuleFor(x => x.VuMeterPeakHoldDurationInMilliseconds, f => vuMeterPeakHoldDurationInMilliseconds ?? f.Random.Int(0, 10000)) - .RuleFor(x => x.VuMeterReleasePerSecond, f => vuMeterReleasePerSecond ?? f.Random.Double(0, 100)) - .RuleFor(x => x.VuMeterPeakReleasePerSecond, f => vuMeterPeakReleasePerSecond ?? f.Random.Double(0, 100)) + .RuleFor(x => x.VuMeterShowPeak, f => includeVuMeterShowPeak ? vuMeterShowPeak ?? f.Random.Bool() : null) + .RuleFor(x => x.VuMeterPeakHoldDurationInMilliseconds, f => includeVuMeterPeakHoldDurationInMilliseconds ? vuMeterPeakHoldDurationInMilliseconds ?? f.Random.Int(0, 10000) : null) + .RuleFor(x => x.VuMeterReleasePerSecond, f => includeVuMeterReleasePerSecond ? vuMeterReleasePerSecond ?? f.Random.Double(0, 100) : null) + .RuleFor(x => x.VuMeterPeakReleasePerSecond, f => includeVuMeterPeakReleasePerSecond ? vuMeterPeakReleasePerSecond ?? f.Random.Double(0, 100) : null) .Generate(); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs index 09c0a626..fb04bdae 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs @@ -42,6 +42,15 @@ public class UpdateUserSettingsRequestFixture /// The time a peak of the VU meter is held before it starts falling. /// The number of level units the display of the VU meter falls per second when the input level drops. /// The number of level units the peak of the VU meter falls per second after its hold time elapsed. + /// Whether to generate the VU meter orientation, or leave it . + /// Whether to generate the VU meter segment count, or leave it . + /// Whether to generate the VU meter segment gap, or leave it . + /// Whether to generate the VU meter medium threshold, or leave it . + /// Whether to generate the VU meter high threshold, or leave it . + /// Whether to generate the VU meter peak marker setting, or leave it . + /// Whether to generate the VU meter peak hold duration, or leave it . + /// Whether to generate the VU meter release rate, or leave it . + /// Whether to generate the VU meter peak release rate, or leave it . /// The created . public UpdateUserSettingsRequest Create( bool? isPaginationEnabled = null, @@ -65,11 +74,24 @@ public class UpdateUserSettingsRequestFixture bool? vuMeterShowPeak = null, int? vuMeterPeakHoldDurationInMilliseconds = null, double? vuMeterReleasePerSecond = null, - double? vuMeterPeakReleasePerSecond = null) + double? vuMeterPeakReleasePerSecond = null, + bool includeVuMeterOrientation = true, + bool includeVuMeterSegmentCount = true, + bool includeVuMeterSegmentGap = true, + bool includeVuMeterMediumThreshold = true, + bool includeVuMeterHighThreshold = true, + bool includeVuMeterShowPeak = true, + bool includeVuMeterPeakHoldDurationInMilliseconds = true, + bool includeVuMeterReleasePerSecond = true, + bool includeVuMeterPeakReleasePerSecond = true) { // The high threshold is generated from the medium one, so a randomized request always describes a valid meter. - double mediumThreshold = vuMeterMediumThreshold ?? _faker.Random.Double(0, 1); - double highThreshold = vuMeterHighThreshold ?? _faker.Random.Double(mediumThreshold, 1); + double? mediumThreshold = includeVuMeterMediumThreshold + ? vuMeterMediumThreshold ?? _faker.Random.Double(0, 1) + : null; + double? highThreshold = includeVuMeterHighThreshold + ? vuMeterHighThreshold ?? (mediumThreshold is null ? _faker.Random.Double(0, 1) : _faker.Random.Double(mediumThreshold.Value, 1)) + : null; return new UpdateUserSettingsRequest( isPaginationEnabled ?? _faker.Random.Bool(), itemsPerPage ?? _faker.Random.Int(1, 100), @@ -84,15 +106,15 @@ public class UpdateUserSettingsRequestFixture isGaplessPlaybackEnabled ?? _faker.Random.Bool(), replayGainMode ?? _faker.PickRandom(), streamingQuality ?? _faker.PickRandom(), - vuMeterOrientation ?? _faker.PickRandom(), - vuMeterSegmentCount ?? _faker.Random.Int(1, 128), - vuMeterSegmentGap ?? _faker.Random.Int(0, 32), + includeVuMeterOrientation ? vuMeterOrientation ?? _faker.PickRandom() : null, + includeVuMeterSegmentCount ? vuMeterSegmentCount ?? _faker.Random.Int(1, 128) : null, + includeVuMeterSegmentGap ? vuMeterSegmentGap ?? _faker.Random.Int(0, 32) : null, mediumThreshold, highThreshold, - vuMeterShowPeak ?? _faker.Random.Bool(), - vuMeterPeakHoldDurationInMilliseconds ?? _faker.Random.Int(0, 10000), - vuMeterReleasePerSecond ?? _faker.Random.Double(0, 100), - vuMeterPeakReleasePerSecond ?? _faker.Random.Double(0, 100)); + includeVuMeterShowPeak ? vuMeterShowPeak ?? _faker.Random.Bool() : null, + includeVuMeterPeakHoldDurationInMilliseconds ? vuMeterPeakHoldDurationInMilliseconds ?? _faker.Random.Int(0, 10000) : null, + includeVuMeterReleasePerSecond ? vuMeterReleasePerSecond ?? _faker.Random.Double(0, 100) : null, + includeVuMeterPeakReleasePerSecond ? vuMeterPeakReleasePerSecond ?? _faker.Random.Double(0, 100) : null); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs index 90317ec5..0bb777e9 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs @@ -34,6 +34,24 @@ public class UserSettingsDtoFixture /// Whether the player transitions between consecutive tracks without a gap. /// The way ReplayGain normalization is applied to the tracks the user plays. /// The quality cap applied to the audio the server normalizes for the user. + /// The direction in which each channel of the VU meter of the audio player grows. + /// The number of segments each channel of the VU meter is divided into. + /// The gap, in pixels, between the segments and the channels of the VU meter. + /// The level above which a segment of the VU meter is drawn with its medium state. + /// The level above which a segment of the VU meter is drawn with its high state. + /// Whether the VU meter holds the peak level of each channel after it falls. + /// The time a peak of the VU meter is held before it starts falling. + /// The number of level units the display of the VU meter falls per second when the input level drops. + /// The number of level units the peak of the VU meter falls per second after its hold time elapsed. + /// Whether to generate the VU meter orientation, or leave it . + /// Whether to generate the VU meter segment count, or leave it . + /// Whether to generate the VU meter segment gap, or leave it . + /// Whether to generate the VU meter medium threshold, or leave it . + /// Whether to generate the VU meter high threshold, or leave it . + /// Whether to generate the VU meter peak marker setting, or leave it . + /// Whether to generate the VU meter peak hold duration, or leave it . + /// Whether to generate the VU meter release rate, or leave it . + /// Whether to generate the VU meter peak release rate, or leave it . /// A configured instance. public UserSettingsDto Create( Guid? userId = null, @@ -48,8 +66,33 @@ public class UserSettingsDtoFixture bool? shouldAutoplay = null, bool? isGaplessPlaybackEnabled = null, ReplayGainMode? replayGainMode = null, - PlaybackStreamingQuality? streamingQuality = null) + PlaybackStreamingQuality? streamingQuality = null, + VuMeterOrientation? vuMeterOrientation = null, + int? vuMeterSegmentCount = null, + int? vuMeterSegmentGap = null, + double? vuMeterMediumThreshold = null, + double? vuMeterHighThreshold = null, + bool? vuMeterShowPeak = null, + int? vuMeterPeakHoldDurationInMilliseconds = null, + double? vuMeterReleasePerSecond = null, + double? vuMeterPeakReleasePerSecond = null, + bool includeVuMeterOrientation = true, + bool includeVuMeterSegmentCount = true, + bool includeVuMeterSegmentGap = true, + bool includeVuMeterMediumThreshold = true, + bool includeVuMeterHighThreshold = true, + bool includeVuMeterShowPeak = true, + bool includeVuMeterPeakHoldDurationInMilliseconds = true, + bool includeVuMeterReleasePerSecond = true, + bool includeVuMeterPeakReleasePerSecond = true) { + // The high threshold is generated from the medium one, so a randomized meter always describes a valid meter. + double? mediumThreshold = includeVuMeterMediumThreshold + ? vuMeterMediumThreshold ?? _faker.Random.Double(0, 1) + : null; + double? highThreshold = includeVuMeterHighThreshold + ? vuMeterHighThreshold ?? (mediumThreshold is null ? _faker.Random.Double(0, 1) : _faker.Random.Double(mediumThreshold.Value, 1)) + : null; return new UserSettingsDto { UserId = userId ?? Guid.NewGuid(), @@ -64,7 +107,16 @@ public class UserSettingsDtoFixture ShouldAutoplay = shouldAutoplay ?? _faker.Random.Bool(), IsGaplessPlaybackEnabled = isGaplessPlaybackEnabled ?? _faker.Random.Bool(), ReplayGainMode = replayGainMode ?? _faker.PickRandom(), - StreamingQuality = streamingQuality ?? _faker.PickRandom() + StreamingQuality = streamingQuality ?? _faker.PickRandom(), + VuMeterOrientation = includeVuMeterOrientation ? vuMeterOrientation ?? _faker.PickRandom() : null, + VuMeterSegmentCount = includeVuMeterSegmentCount ? vuMeterSegmentCount ?? _faker.Random.Int(1, 128) : null, + VuMeterSegmentGap = includeVuMeterSegmentGap ? vuMeterSegmentGap ?? _faker.Random.Int(0, 32) : null, + VuMeterMediumThreshold = mediumThreshold, + VuMeterHighThreshold = highThreshold, + VuMeterShowPeak = includeVuMeterShowPeak ? vuMeterShowPeak ?? _faker.Random.Bool() : null, + VuMeterPeakHoldDurationInMilliseconds = includeVuMeterPeakHoldDurationInMilliseconds ? vuMeterPeakHoldDurationInMilliseconds ?? _faker.Random.Int(0, 10000) : null, + VuMeterReleasePerSecond = includeVuMeterReleasePerSecond ? vuMeterReleasePerSecond ?? _faker.Random.Double(0, 100) : null, + VuMeterPeakReleasePerSecond = includeVuMeterPeakReleasePerSecond ? vuMeterPeakReleasePerSecond ?? _faker.Random.Double(0, 100) : null }; } diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs index 4ed35bfa..5c3d1aab 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.Repositories.Users; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using System; @@ -67,4 +68,53 @@ public class UserSettingsRepositoryTests Assert.Null(reloadedSettings.UpdatedOnUtc); Assert.Null(reloadedSettings.UpdatedBy); } + + [Fact] + public async Task InsertAsync_WhenVuMeterSettingsAreProvided_ShouldPersistEveryValue() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-usersettingsvu-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + UserSettingsRepository sut = new(context); + + UserEntity storedUser = _userEntityFixture.Create(username: "vu-meter-settings-user", password: "Password123"); + context.Users.Add(storedUser); + await context.SaveChangesAsync(); + + UserSettingsEntity settingsToStore = _userSettingsEntityFixture.Create( + userId: storedUser.Id, + vuMeterOrientation: VuMeterOrientation.Horizontal, + vuMeterSegmentCount: 20, + vuMeterSegmentGap: 4, + vuMeterMediumThreshold: 0.35, + vuMeterHighThreshold: 0.9, + vuMeterShowPeak: false, + vuMeterPeakHoldDurationInMilliseconds: 1200, + vuMeterReleasePerSecond: 7.5, + vuMeterPeakReleasePerSecond: 0.25); + settingsToStore.CreatedOnUtc = DateTime.UtcNow; + settingsToStore.CreatedBy = storedUser.Id; + + // Act + Result insertResult = await sut.InsertAsync(settingsToStore, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(insertResult.IsFailure); + Assert.Equal(Result.Created, insertResult.Value); + + context.ChangeTracker.Clear(); + UserSettingsEntity reloadedSettings = await context.UserSettings.AsNoTracking().FirstAsync(settings => settings.Id == settingsToStore.Id); + Assert.Equal(VuMeterOrientation.Horizontal, reloadedSettings.VuMeterOrientation); + Assert.Equal(20, reloadedSettings.VuMeterSegmentCount); + Assert.Equal(4, reloadedSettings.VuMeterSegmentGap); + Assert.Equal(0.35, reloadedSettings.VuMeterMediumThreshold); + Assert.Equal(0.9, reloadedSettings.VuMeterHighThreshold); + Assert.False(reloadedSettings.VuMeterShowPeak); + Assert.Equal(1200, reloadedSettings.VuMeterPeakHoldDurationInMilliseconds); + Assert.Equal(7.5, reloadedSettings.VuMeterReleasePerSecond); + Assert.Equal(0.25, reloadedSettings.VuMeterPeakReleasePerSecond); + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 1735ed4b..1908060a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.UsersManagement.Settings; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; @@ -72,6 +73,15 @@ public class GetUserSettingsEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - Assert.NotNull(problemDetails); - Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); - Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); - Assert.Equal("General.Validation", problemDetails["title"].GetString()); - Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); - Assert.Equal("/api/v1/users/me/settings", problemDetails["instance"].GetString()); - - Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); - Assert.NotNull(errors); - Assert.Contains("General.Validation", errors.Keys); - Assert.Contains("ItemsPerPageMustBeGreaterThanZero", errors["General.Validation"]); + await AssertValidationErrorAsync(response, "ItemsPerPageMustBeGreaterThanZero"); } [Fact] @@ -137,6 +142,352 @@ public class UpdateUserSettingsEndpointTests : IClassFixture + /// Asserts that is a validation problem response carrying the specified error. + /// + /// The response to assert. + /// The exact error description expected in the validation errors. + /// A task representing the asynchronous operation. + private async Task AssertValidationErrorAsync(HttpResponseMessage response, string expectedError) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/users/me/settings", problemDetails["instance"].GetString()); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains(expectedError, errors["General.Validation"]); + } + /// /// Disposes API factory resources. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 436fd2c1..d3d8e556 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Enums.AudioLibrary; using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; @@ -55,4 +56,45 @@ public class GetUserSettingsEndpointTests : IClassFixture Assert.Equal(24, json.RootElement.GetProperty("data").GetProperty("itemsPerPage").GetInt32()); Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings"); } + + [Fact] + public async Task GetUserSettings_WhenCalledByAuthenticatedUser_ShouldReturnVuMeterSettingsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + UserSettingsDto expectedSettings = _userSettingsDtoFixture.Create( + vuMeterOrientation: VuMeterOrientation.Horizontal, + vuMeterSegmentCount: 20, + vuMeterSegmentGap: 4, + vuMeterMediumThreshold: 0.35, + vuMeterHighThreshold: 0.9, + vuMeterShowPeak: false, + vuMeterPeakHoldDurationInMilliseconds: 1200, + vuMeterReleasePerSecond: 7.5, + vuMeterPeakReleasePerSecond: 0.25); + _apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings", expectedSettings); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-user-settings"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal("Horizontal", data.GetProperty("vuMeterOrientation").GetString()); + Assert.Equal(20, data.GetProperty("vuMeterSegmentCount").GetInt32()); + Assert.Equal(4, data.GetProperty("vuMeterSegmentGap").GetInt32()); + Assert.Equal(0.35, data.GetProperty("vuMeterMediumThreshold").GetDouble()); + Assert.Equal(0.9, data.GetProperty("vuMeterHighThreshold").GetDouble()); + Assert.False(data.GetProperty("vuMeterShowPeak").GetBoolean()); + Assert.Equal(1200, data.GetProperty("vuMeterPeakHoldDurationInMilliseconds").GetInt32()); + Assert.Equal(7.5, data.GetProperty("vuMeterReleasePerSecond").GetDouble()); + Assert.Equal(0.25, data.GetProperty("vuMeterPeakReleasePerSecond").GetDouble()); + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 4e362f78..a94dd321 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Enums.AudioLibrary; using Lumina.Presentation.Web.Common.Requests.Common; using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; @@ -56,6 +57,44 @@ public class UpdateUserSettingsEndpointTests : IClassFixture Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings"); } + [Fact] + public async Task UpdateUserSettings_WhenCalledByAuthenticatedUser_ShouldForwardVuMeterSettingsToApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings", _ => new EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + UserSettingsDto settings = _userSettingsDtoFixture.Create( + vuMeterOrientation: VuMeterOrientation.Horizontal, + vuMeterSegmentCount: 20, + vuMeterSegmentGap: 4, + vuMeterMediumThreshold: 0.35, + vuMeterHighThreshold: 0.9, + vuMeterShowPeak: false, + vuMeterPeakHoldDurationInMilliseconds: 1200, + vuMeterReleasePerSecond: 7.5, + vuMeterPeakReleasePerSecond: 0.25); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateUpdateSettingsRequest(settings, webClient.AntiforgeryToken)); + + // Assert + response.EnsureSuccessStatusCode(); + (string Endpoint, object? Data) putRequest = Assert.Single( + _apiFactory.ApiClientStub.PutRequests, + request => request.Endpoint == "users/me/settings"); + UserSettingsDto forwardedSettings = Assert.IsType(putRequest.Data); + Assert.Equal(VuMeterOrientation.Horizontal, forwardedSettings.VuMeterOrientation); + Assert.Equal(20, forwardedSettings.VuMeterSegmentCount); + Assert.Equal(4, forwardedSettings.VuMeterSegmentGap); + Assert.Equal(0.35, forwardedSettings.VuMeterMediumThreshold); + Assert.Equal(0.9, forwardedSettings.VuMeterHighThreshold); + Assert.False(forwardedSettings.VuMeterShowPeak); + Assert.Equal(1200, forwardedSettings.VuMeterPeakHoldDurationInMilliseconds); + Assert.Equal(7.5, forwardedSettings.VuMeterReleasePerSecond); + Assert.Equal(0.25, forwardedSettings.VuMeterPeakReleasePerSecond); + } + /// /// Builds the update request that sends the given to the user settings endpoint. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 1edfd338..1873b3cb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; @@ -14,7 +15,9 @@ using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; +using System.Text; using System.Text.Json; +using System.Text.Json.Nodes; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings; @@ -122,6 +125,223 @@ public class UpdateUserSettingsEndpointTests : IClassFixture Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); } + [Theory] + [InlineData(int.MaxValue)] // far above the maximum + [InlineData(int.MinValue)] // far below the minimum + public async Task UpdateUserSettings_WhenVuMeterSegmentCountIsAtAnIntExtreme_ShouldReturnValidationErrorWithoutCrashing(int vuMeterSegmentCount) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterSegmentCount: vuMeterSegmentCount); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + AssertResponseDoesNotLeakInternalDetails(content); + } + + [Theory] + [InlineData(int.MaxValue)] // far above the maximum + [InlineData(int.MinValue)] // far below the minimum + public async Task UpdateUserSettings_WhenVuMeterSegmentGapIsAtAnIntExtreme_ShouldReturnValidationErrorWithoutCrashing(int vuMeterSegmentGap) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterSegmentGap: vuMeterSegmentGap); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + AssertResponseDoesNotLeakInternalDetails(content); + } + + [Theory] + [InlineData(double.MaxValue)] // far above the maximum + [InlineData(double.MinValue)] // far below the minimum + public async Task UpdateUserSettings_WhenVuMeterMediumThresholdIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutCrashing(double vuMeterMediumThreshold) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( + vuMeterMediumThreshold: vuMeterMediumThreshold, + vuMeterHighThreshold: 1.0); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + AssertResponseDoesNotLeakInternalDetails(content); + } + + [Theory] + [InlineData(double.MaxValue)] // far above the maximum + [InlineData(double.MinValue)] // far below the minimum + public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutCrashing(double vuMeterHighThreshold) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( + vuMeterMediumThreshold: 0.0, + vuMeterHighThreshold: vuMeterHighThreshold); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + AssertResponseDoesNotLeakInternalDetails(content); + } + + [Theory] + [InlineData(int.MaxValue)] // far above the maximum + [InlineData(int.MinValue)] // far below the minimum + public async Task UpdateUserSettings_WhenVuMeterPeakHoldDurationIsAtAnIntExtreme_ShouldReturnValidationErrorWithoutCrashing(int vuMeterPeakHoldDurationInMilliseconds) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( + vuMeterPeakHoldDurationInMilliseconds: vuMeterPeakHoldDurationInMilliseconds); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + AssertResponseDoesNotLeakInternalDetails(content); + } + + [Theory] + [InlineData(double.MaxValue)] // far above the maximum + [InlineData(double.MinValue)] // far below the minimum + public async Task UpdateUserSettings_WhenVuMeterReleasePerSecondIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutCrashing(double vuMeterReleasePerSecond) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterReleasePerSecond: vuMeterReleasePerSecond); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + AssertResponseDoesNotLeakInternalDetails(content); + } + + [Theory] + [InlineData(double.MaxValue)] // far above the maximum + [InlineData(double.MinValue)] // far below the minimum + public async Task UpdateUserSettings_WhenVuMeterPeakReleasePerSecondIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutCrashing(double vuMeterPeakReleasePerSecond) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterPeakReleasePerSecond: vuMeterPeakReleasePerSecond); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + AssertResponseDoesNotLeakInternalDetails(content); + } + + [Fact] + public async Task UpdateUserSettings_WhenVuMeterOrientationIsAnUndefinedValue_ShouldReturnValidationErrorWithoutCrashing() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterOrientation: (VuMeterOrientation)999); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + AssertResponseDoesNotLeakInternalDetails(content); + } + + [Theory(Skip = "Production bug: a JSON payload whose VuMeterOrientation is not a valid enumeration value makes the FastEndpoints binder throw a System.Text.Json.JsonException, which escapes because UpdateUserSettingsEndpoint calls DontCatchExceptions(), so the API responds with 500 instead of 400 or 422. The body is the generic ProblemDetails and leaks no internals. The test stays skipped until the endpoint maps binding failures to a client error.")] + [InlineData("'; DROP TABLE UserSettings; --")] // SQL injection + [InlineData("$(rm -rf /)")] // command injection + [InlineData("{{7*7}}")] // template injection + public async Task UpdateUserSettings_WhenVuMeterOrientationIsAMaliciousString_ShouldReturnClientErrorWithoutLeakingInternals(string maliciousOrientation) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest validRequest = _updateUserSettingsRequestFixture.Create(); + JsonObject payload = JsonSerializer.SerializeToNode( + validRequest, + new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject(); + payload["vuMeterOrientation"] = maliciousOrientation; + StringContent requestContent = new(payload.ToJsonString(), Encoding.UTF8, "application/json"); + + // Act + HttpResponseMessage response = await client.PutAsync("/api/v1/users/me/settings", requestContent); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.True( + response.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.UnprocessableEntity, + $"Expected a 400 or 422 response, but got {(int)response.StatusCode}."); + AssertResponseDoesNotLeakInternalDetails(content); + Assert.DoesNotContain("DROP TABLE", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("rm -rf", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task UpdateUserSettings_WhenTheRawJsonPayloadIsValid_ShouldUpdateSettings() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + UpdateUserSettingsRequest validRequest = _updateUserSettingsRequestFixture.Create(); + JsonObject payload = JsonSerializer.SerializeToNode( + validRequest, + new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject(); + StringContent requestContent = new(payload.ToJsonString(), Encoding.UTF8, "application/json"); + + // Act + HttpResponseMessage response = await client.PutAsync("/api/v1/users/me/settings", requestContent); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Asserts that the response body does not expose exception details, stack frames, or database internals. + /// + /// The response body to inspect. + private static void AssertResponseDoesNotLeakInternalDetails(string content) + { + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Microsoft.Data.Sqlite", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Microsoft.EntityFrameworkCore", content, StringComparison.OrdinalIgnoreCase); + } + /// /// Creates a test user and authenticates it on . /// diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs index 2ae1fa52..beb811ef 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.UsersManagement.Users; using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Diagnostics.CodeAnalysis; #endregion @@ -27,7 +28,19 @@ public class UpdateUserSettingsRequestMappingTests isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldRenderPdfAsImages: true, - shouldPreserveBookStyles: true + shouldPreserveBookStyles: true, + shouldKeepDownloadingWhilePaused: false, + shouldAutoplay: false, + isGaplessPlaybackEnabled: false, + vuMeterOrientation: VuMeterOrientation.Horizontal, + vuMeterSegmentCount: 20, + vuMeterSegmentGap: 4, + vuMeterMediumThreshold: 0.35, + vuMeterHighThreshold: 0.9, + vuMeterShowPeak: false, + vuMeterPeakHoldDurationInMilliseconds: 1200, + vuMeterReleasePerSecond: 7.5, + vuMeterPeakReleasePerSecond: 0.25 ); // Act @@ -41,5 +54,20 @@ public class UpdateUserSettingsRequestMappingTests Assert.Equal(request.IsThemeCachingEnabled, result.IsThemeCachingEnabled); Assert.Equal(request.ShouldRenderPdfAsImages, result.ShouldRenderPdfAsImages); Assert.Equal(request.ShouldPreserveBookStyles, result.ShouldPreserveBookStyles); + Assert.Equal(request.ShouldKeepDownloadingWhilePaused, result.ShouldKeepDownloadingWhilePaused); + Assert.False(result.ShouldKeepDownloadingWhilePaused); + Assert.Equal(request.ShouldAutoplay, result.ShouldAutoplay); + Assert.False(result.ShouldAutoplay); + Assert.Equal(request.IsGaplessPlaybackEnabled, result.IsGaplessPlaybackEnabled); + Assert.False(result.IsGaplessPlaybackEnabled); + Assert.Equal(VuMeterOrientation.Horizontal, result.VuMeterOrientation); + Assert.Equal(20, result.VuMeterSegmentCount); + Assert.Equal(4, result.VuMeterSegmentGap); + Assert.Equal(0.35, result.VuMeterMediumThreshold); + Assert.Equal(0.9, result.VuMeterHighThreshold); + Assert.False(result.VuMeterShowPeak); + Assert.Equal(1200, result.VuMeterPeakHoldDurationInMilliseconds); + Assert.Equal(7.5, result.VuMeterReleasePerSecond); + Assert.Equal(0.25, result.VuMeterPeakReleasePerSecond); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs index b9200372..aa7c8ca1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs @@ -801,6 +801,123 @@ public class ValidatorUtilitiesTests result.ShouldNotHaveValidationError(s_equalValueError); } + [Fact] + public void Validate_WhenNullableDoubleValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(includeNullableDoubleValue: false); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_nullableDoubleValueError); + } + + [Fact] + public void Validate_WhenNullableDoubleComparisonValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(includeNullableDoubleComparisonValue: false); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_nullableDoubleValueError); + } + + [Fact] + public void Validate_WhenNullableDoubleValueIsGreaterThanComparison_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create( + nullableDoubleValue: 6.0, + nullableDoubleComparisonValue: 5.0); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_nullableDoubleValueError); + } + + [Fact] + public void Validate_WhenNullableDoubleValueEqualsComparison_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create( + nullableDoubleValue: 5.0, + nullableDoubleComparisonValue: 5.0); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_nullableDoubleValueError); + } + + [Fact] + public void Validate_WhenNullableDoubleValueIsSmallerThanComparison_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create( + nullableDoubleValue: 4.0, + nullableDoubleComparisonValue: 5.0); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_nullableDoubleValueError); + } + + [Fact] + public void Validate_WhenInclusiveNullableDoubleValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(includeInclusiveNullableDoubleValue: false); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_inclusiveNullableDoubleValueError); + } + + [Theory] + [InlineData(0.99)] // just below the minimum + [InlineData(10.01)] // just above the maximum + public void Validate_WhenInclusiveNullableDoubleValueIsOutsideRange_ShouldHaveValidationError(double inclusiveNullableDoubleValue) + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create( + inclusiveNullableDoubleValue: inclusiveNullableDoubleValue); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_inclusiveNullableDoubleValueError); + } + + [Theory] + [InlineData(1.0)] // the minimum + [InlineData(5.0)] // a middle value + [InlineData(10.0)] // the maximum + public void Validate_WhenInclusiveNullableDoubleValueIsWithinRange_ShouldNotHaveValidationError(double inclusiveNullableDoubleValue) + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create( + inclusiveNullableDoubleValue: inclusiveNullableDoubleValue); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_inclusiveNullableDoubleValueError); + } + [ExcludeFromCodeCoverage] private sealed class ValidatorUtilitiesTestValidator : AbstractValidator { @@ -829,6 +946,8 @@ public class ValidatorUtilitiesTests RuleFor(request => request.SelectorMatchValue).Matches(instance => instance.PatternValue).WithError(s_selectorMatchValueError); RuleFor(request => request.InclusiveIntValue).InclusiveBetween(1, 10).WithError(s_inclusiveIntValueError); RuleFor(request => request.InclusiveNullableIntValue).InclusiveBetween(1, 10).WithError(s_inclusiveNullableIntValueError); + RuleFor(request => request.NullableDoubleValue).GreaterThanOrEqualTo(instance => instance.NullableDoubleComparisonValue).WithError(s_nullableDoubleValueError); + RuleFor(request => request.InclusiveNullableDoubleValue).InclusiveBetween(1d, 10d).WithError(s_inclusiveNullableDoubleValueError); RuleFor(request => request.EqualValue).Equal(instance => instance.EqualComparisonValue).WithError(s_equalValueError); } } @@ -856,5 +975,7 @@ public class ValidatorUtilitiesTests private static readonly Error s_selectorMatchValueError = Error.Validation(description: "SelectorMatchValueError"); private static readonly Error s_inclusiveIntValueError = Error.Validation(description: "InclusiveIntValueError"); private static readonly Error s_inclusiveNullableIntValueError = Error.Validation(description: "InclusiveNullableIntValueError"); + private static readonly Error s_nullableDoubleValueError = Error.Validation(description: "NullableDoubleValueError"); + private static readonly Error s_inclusiveNullableDoubleValueError = Error.Validation(description: "InclusiveNullableDoubleValueError"); private static readonly Error s_equalValueError = Error.Validation(description: "EqualValueError"); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs index 08c37f4d..5994d7c0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs @@ -77,7 +77,16 @@ public class UpdateUserSettingsCommandHandlerTests settings.ItemsPerPage == command.ItemsPerPage && settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker && settings.ShouldRenderPdfAsImages == command.ShouldRenderPdfAsImages && - settings.ShouldPreserveBookStyles == command.ShouldPreserveBookStyles), + settings.ShouldPreserveBookStyles == command.ShouldPreserveBookStyles && + settings.VuMeterOrientation == command.VuMeterOrientation && + settings.VuMeterSegmentCount == command.VuMeterSegmentCount && + settings.VuMeterSegmentGap == command.VuMeterSegmentGap && + settings.VuMeterMediumThreshold == command.VuMeterMediumThreshold && + settings.VuMeterHighThreshold == command.VuMeterHighThreshold && + settings.VuMeterShowPeak == command.VuMeterShowPeak && + settings.VuMeterPeakHoldDurationInMilliseconds == command.VuMeterPeakHoldDurationInMilliseconds && + settings.VuMeterReleasePerSecond == command.VuMeterReleasePerSecond && + settings.VuMeterPeakReleasePerSecond == command.VuMeterPeakReleasePerSecond), Arg.Any()); await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); @@ -107,7 +116,16 @@ public class UpdateUserSettingsCommandHandlerTests settings.ItemsPerPage == command.ItemsPerPage && settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker && settings.ShouldRenderPdfAsImages == command.ShouldRenderPdfAsImages && - settings.ShouldPreserveBookStyles == command.ShouldPreserveBookStyles), + settings.ShouldPreserveBookStyles == command.ShouldPreserveBookStyles && + settings.VuMeterOrientation == command.VuMeterOrientation && + settings.VuMeterSegmentCount == command.VuMeterSegmentCount && + settings.VuMeterSegmentGap == command.VuMeterSegmentGap && + settings.VuMeterMediumThreshold == command.VuMeterMediumThreshold && + settings.VuMeterHighThreshold == command.VuMeterHighThreshold && + settings.VuMeterShowPeak == command.VuMeterShowPeak && + settings.VuMeterPeakHoldDurationInMilliseconds == command.VuMeterPeakHoldDurationInMilliseconds && + settings.VuMeterReleasePerSecond == command.VuMeterReleasePerSecond && + settings.VuMeterPeakReleasePerSecond == command.VuMeterPeakReleasePerSecond), Arg.Any()); await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidatorTests.cs index 4466be33..bb45fa81 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandValidatorTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdateU using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -51,6 +52,454 @@ public class UpdateUserSettingsCommandValidatorTests result.ShouldNotHaveValidationError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero); } + [Fact] + public void Validate_WhenVuMeterOrientationIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterOrientation: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterOrientationCannotBeNull); + } + + [Fact] + public void Validate_WhenVuMeterSegmentCountIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterSegmentCount: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterSegmentCountCannotBeNull); + } + + [Fact] + public void Validate_WhenVuMeterSegmentGapIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterSegmentGap: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterSegmentGapCannotBeNull); + } + + [Fact] + public void Validate_WhenVuMeterMediumThresholdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterMediumThreshold: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterMediumThresholdCannotBeNull); + } + + [Fact] + public void Validate_WhenVuMeterHighThresholdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterHighThreshold: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterHighThresholdCannotBeNull); + } + + [Fact] + public void Validate_WhenVuMeterShowPeakIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterShowPeak: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterShowPeakCannotBeNull); + } + + [Fact] + public void Validate_WhenVuMeterPeakHoldDurationIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterPeakHoldDurationInMilliseconds: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterPeakHoldDurationCannotBeNull); + } + + [Fact] + public void Validate_WhenVuMeterReleasePerSecondIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterReleasePerSecond: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterReleasePerSecondCannotBeNull); + } + + [Fact] + public void Validate_WhenVuMeterPeakReleasePerSecondIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterPeakReleasePerSecond: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterPeakReleasePerSecondCannotBeNull); + } + + [Theory] + [InlineData(999)] // a value that is not a defined member of the enumeration + [InlineData(-1)] // a negative value that is not a defined member of the enumeration + public void Validate_WhenVuMeterOrientationIsNotDefined_ShouldHaveValidationError(int vuMeterOrientationValue) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterOrientation: (VuMeterOrientation)vuMeterOrientationValue); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.InvalidVuMeterOrientation); + } + + [Theory] + [InlineData(VuMeterOrientation.Vertical)] + [InlineData(VuMeterOrientation.Horizontal)] + public void Validate_WhenVuMeterOrientationIsDefined_ShouldNotHaveValidationError(VuMeterOrientation vuMeterOrientation) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterOrientation: vuMeterOrientation); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.InvalidVuMeterOrientation); + } + + [Theory] + [InlineData(0)] // below the minimum + [InlineData(-1)] // negative + [InlineData(129)] // above the maximum + [InlineData(int.MaxValue)] // far above the maximum + public void Validate_WhenVuMeterSegmentCountIsOutOfRange_ShouldHaveValidationError(int vuMeterSegmentCount) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterSegmentCount: vuMeterSegmentCount); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterSegmentCountMustBeBetweenOneAndOneHundredTwentyEight); + } + + [Theory] + [InlineData(1)] // the minimum + [InlineData(64)] // a middle value + [InlineData(128)] // the maximum + public void Validate_WhenVuMeterSegmentCountIsInRange_ShouldNotHaveValidationError(int vuMeterSegmentCount) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterSegmentCount: vuMeterSegmentCount); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterSegmentCountMustBeBetweenOneAndOneHundredTwentyEight); + } + + [Theory] + [InlineData(-1)] // below the minimum + [InlineData(33)] // above the maximum + [InlineData(int.MinValue)] // far below the minimum + public void Validate_WhenVuMeterSegmentGapIsOutOfRange_ShouldHaveValidationError(int vuMeterSegmentGap) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterSegmentGap: vuMeterSegmentGap); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterSegmentGapMustBeBetweenZeroAndThirtyTwo); + } + + [Theory] + [InlineData(0)] // the minimum + [InlineData(16)] // a middle value + [InlineData(32)] // the maximum + public void Validate_WhenVuMeterSegmentGapIsInRange_ShouldNotHaveValidationError(int vuMeterSegmentGap) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterSegmentGap: vuMeterSegmentGap); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterSegmentGapMustBeBetweenZeroAndThirtyTwo); + } + + [Theory] + [InlineData(-0.01)] // just below the minimum + [InlineData(1.01)] // just above the maximum + [InlineData(double.MinValue)] // far below the minimum + public void Validate_WhenVuMeterMediumThresholdIsOutOfRange_ShouldHaveValidationError(double vuMeterMediumThreshold) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterMediumThreshold: vuMeterMediumThreshold, + vuMeterHighThreshold: 1.0); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterMediumThresholdMustBeBetweenZeroAndOne); + } + + [Theory] + [InlineData(0.0)] // the minimum + [InlineData(0.5)] // a middle value + [InlineData(1.0)] // the maximum + public void Validate_WhenVuMeterMediumThresholdIsInRange_ShouldNotHaveValidationError(double vuMeterMediumThreshold) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterMediumThreshold: vuMeterMediumThreshold, + vuMeterHighThreshold: 1.0); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterMediumThresholdMustBeBetweenZeroAndOne); + } + + [Theory] + [InlineData(-0.01)] // just below the minimum + [InlineData(1.01)] // just above the maximum + [InlineData(double.MaxValue)] // far above the maximum + public void Validate_WhenVuMeterHighThresholdIsOutOfRange_ShouldHaveValidationError(double vuMeterHighThreshold) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterMediumThreshold: 0.0, + vuMeterHighThreshold: vuMeterHighThreshold); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterHighThresholdMustBeBetweenZeroAndOne); + } + + [Fact] + public void Validate_WhenVuMeterHighThresholdIsAtTheMinimum_ShouldNotHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterMediumThreshold: 0.0, + vuMeterHighThreshold: 0.0); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterHighThresholdMustBeBetweenZeroAndOne); + } + + [Fact] + public void Validate_WhenVuMeterHighThresholdIsAtTheMaximum_ShouldNotHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterMediumThreshold: 0.5, + vuMeterHighThreshold: 1.0); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterHighThresholdMustBeBetweenZeroAndOne); + } + + [Fact] + public void Validate_WhenVuMeterHighThresholdIsLowerThanMediumThreshold_ShouldHaveValidationError() + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterMediumThreshold: 0.9, + vuMeterHighThreshold: 0.1); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterHighThresholdMustBeGreaterThanOrEqualToMediumThreshold); + } + + [Theory] + [InlineData(0.5, 0.5)] // the thresholds are equal + [InlineData(0.4, 0.9)] // the high threshold is greater than the medium one + public void Validate_WhenVuMeterHighThresholdIsGreaterThanOrEqualToMediumThreshold_ShouldNotHaveValidationError( + double vuMeterMediumThreshold, + double vuMeterHighThreshold) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterMediumThreshold: vuMeterMediumThreshold, + vuMeterHighThreshold: vuMeterHighThreshold); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterHighThresholdMustBeGreaterThanOrEqualToMediumThreshold); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Validate_WhenVuMeterShowPeakIsSpecified_ShouldNotHaveValidationError(bool vuMeterShowPeak) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterShowPeak: vuMeterShowPeak); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterShowPeakCannotBeNull); + } + + [Theory] + [InlineData(-1)] // below the minimum + [InlineData(10001)] // above the maximum + [InlineData(int.MinValue)] // far below the minimum + public void Validate_WhenVuMeterPeakHoldDurationIsOutOfRange_ShouldHaveValidationError(int vuMeterPeakHoldDurationInMilliseconds) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterPeakHoldDurationInMilliseconds: vuMeterPeakHoldDurationInMilliseconds); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterPeakHoldDurationMustBeBetweenZeroAndTenThousandMilliseconds); + } + + [Theory] + [InlineData(0)] // the minimum + [InlineData(650)] // a middle value + [InlineData(10000)] // the maximum + public void Validate_WhenVuMeterPeakHoldDurationIsInRange_ShouldNotHaveValidationError(int vuMeterPeakHoldDurationInMilliseconds) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterPeakHoldDurationInMilliseconds: vuMeterPeakHoldDurationInMilliseconds); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterPeakHoldDurationMustBeBetweenZeroAndTenThousandMilliseconds); + } + + [Theory] + [InlineData(-0.01)] // just below the minimum + [InlineData(100.01)] // just above the maximum + [InlineData(double.MinValue)] // far below the minimum + public void Validate_WhenVuMeterReleasePerSecondIsOutOfRange_ShouldHaveValidationError(double vuMeterReleasePerSecond) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterReleasePerSecond: vuMeterReleasePerSecond); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterReleasePerSecondMustBeBetweenZeroAndOneHundred); + } + + [Theory] + [InlineData(0.0)] // the minimum + [InlineData(3.0)] // a middle value + [InlineData(100.0)] // the maximum + public void Validate_WhenVuMeterReleasePerSecondIsInRange_ShouldNotHaveValidationError(double vuMeterReleasePerSecond) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterReleasePerSecond: vuMeterReleasePerSecond); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterReleasePerSecondMustBeBetweenZeroAndOneHundred); + } + + [Theory] + [InlineData(-0.01)] // just below the minimum + [InlineData(100.01)] // just above the maximum + [InlineData(double.MaxValue)] // far above the maximum + public void Validate_WhenVuMeterPeakReleasePerSecondIsOutOfRange_ShouldHaveValidationError(double vuMeterPeakReleasePerSecond) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterPeakReleasePerSecond: vuMeterPeakReleasePerSecond); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred); + } + + [Theory] + [InlineData(0.0)] // the minimum + [InlineData(0.65)] // a middle value + [InlineData(100.0)] // the maximum + public void Validate_WhenVuMeterPeakReleasePerSecondIsInRange_ShouldNotHaveValidationError(double vuMeterPeakReleasePerSecond) + { + // Arrange + UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create( + vuMeterPeakReleasePerSecond: vuMeterPeakReleasePerSecond); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred); + } + [Fact] public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() { diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs index d55f386f..44c32db9 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.UoW; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using System; using System.Collections.Generic; @@ -27,6 +28,11 @@ public class UserSettingsConfigurationTests _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); } + /// + /// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits. + /// + private IModel DesignTimeModel => _context.GetService().Model; + [Fact] public void Configure_WhenApplied_ShouldSetTableNameAndKey() { @@ -122,4 +128,37 @@ public class UserSettingsConfigurationTests Assert.False(createdOnUtcProperty.IsNullable); Assert.Null(updatedOnUtcProperty.GetDefaultValue()); } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureVuMeterAndPlaybackStateColumnOrders() + { + // Arrange + IEntityType entityType = DesignTimeModel.FindEntityType(typeof(UserSettingsEntity))!; + + // Act + IProperty vuMeterOrientationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterOrientation)); + IProperty vuMeterSegmentCountProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentCount)); + IProperty vuMeterSegmentGapProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterSegmentGap)); + IProperty vuMeterMediumThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterMediumThreshold)); + IProperty vuMeterHighThresholdProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterHighThreshold)); + IProperty vuMeterShowPeakProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterShowPeak)); + IProperty vuMeterPeakHoldDurationProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakHoldDurationInMilliseconds)); + IProperty vuMeterReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterReleasePerSecond)); + IProperty vuMeterPeakReleasePerSecondProperty = entityType.GetProperty(nameof(UserSettingsEntity.VuMeterPeakReleasePerSecond)); + IProperty volumeProperty = entityType.GetProperty(nameof(UserSettingsEntity.Volume)); + IProperty isMutedProperty = entityType.GetProperty(nameof(UserSettingsEntity.IsMuted)); + + // Assert + Assert.Equal(19, vuMeterOrientationProperty.GetColumnOrder()); + Assert.Equal(20, vuMeterSegmentCountProperty.GetColumnOrder()); + Assert.Equal(21, vuMeterSegmentGapProperty.GetColumnOrder()); + Assert.Equal(22, vuMeterMediumThresholdProperty.GetColumnOrder()); + Assert.Equal(23, vuMeterHighThresholdProperty.GetColumnOrder()); + Assert.Equal(24, vuMeterShowPeakProperty.GetColumnOrder()); + Assert.Equal(25, vuMeterPeakHoldDurationProperty.GetColumnOrder()); + Assert.Equal(26, vuMeterReleasePerSecondProperty.GetColumnOrder()); + Assert.Equal(27, vuMeterPeakReleasePerSecondProperty.GetColumnOrder()); + Assert.Equal(28, volumeProperty.GetColumnOrder()); + Assert.Equal(29, isMutedProperty.GetColumnOrder()); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs index 82421cc1..1ae67c19 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs @@ -40,6 +40,15 @@ public class UserSettingsTests Assert.False(result.Value.ShouldAggregateMetadataWhenMissing); Assert.False(result.Value.ShouldRenderPdfAsImages); Assert.True(result.Value.ShouldPreserveBookStyles); + Assert.Equal(VuMeterOrientation.Vertical, result.Value.VuMeterOrientation); + Assert.Equal(12, result.Value.VuMeterSegmentCount); + Assert.Equal(1, result.Value.VuMeterSegmentGap); + Assert.Equal(0.6, result.Value.VuMeterMediumThreshold); + Assert.Equal(0.8, result.Value.VuMeterHighThreshold); + Assert.True(result.Value.VuMeterShowPeak); + Assert.Equal(650, result.Value.VuMeterPeakHoldDurationInMilliseconds); + Assert.Equal(3.0, result.Value.VuMeterReleasePerSecond); + Assert.Equal(0.65, result.Value.VuMeterPeakReleasePerSecond); } [Fact] @@ -57,6 +66,15 @@ public class UserSettingsTests Assert.False(result.Value.ShouldAggregateMetadataWhenMissing); Assert.False(result.Value.ShouldRenderPdfAsImages); Assert.True(result.Value.ShouldPreserveBookStyles); + Assert.Equal(VuMeterOrientation.Vertical, result.Value.VuMeterOrientation); + Assert.Equal(12, result.Value.VuMeterSegmentCount); + Assert.Equal(1, result.Value.VuMeterSegmentGap); + Assert.Equal(0.6, result.Value.VuMeterMediumThreshold); + Assert.Equal(0.8, result.Value.VuMeterHighThreshold); + Assert.True(result.Value.VuMeterShowPeak); + Assert.Equal(650, result.Value.VuMeterPeakHoldDurationInMilliseconds); + Assert.Equal(3.0, result.Value.VuMeterReleasePerSecond); + Assert.Equal(0.65, result.Value.VuMeterPeakReleasePerSecond); } [Fact] @@ -80,7 +98,32 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true, shouldAggregateArtworkWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true, shouldKeepDownloadingWhilePaused: true, shouldAutoplay: true, isGaplessPlaybackEnabled: true, replayGainMode: ReplayGainMode.Off, streamingQuality: PlaybackStreamingQuality.Auto, vuMeterOrientation: VuMeterOrientation.Vertical, vuMeterSegmentCount: 12, vuMeterSegmentGap: 1, vuMeterMediumThreshold: 0.6, vuMeterHighThreshold: 0.8, vuMeterShowPeak: true, vuMeterPeakHoldDurationInMilliseconds: 650, vuMeterReleasePerSecond: 1.5, vuMeterPeakReleasePerSecond: 0.65, volume: 1.0, isMuted: false); + Result result = UserSettings.Create( + userId, + isPaginationEnabled: false, + itemsPerPage: 24, + shouldIgnoreThePrefixForAlphaPicker: true, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: true, + shouldAggregateArtworkWhenMissing: true, + shouldRenderPdfAsImages: true, + shouldPreserveBookStyles: true, + shouldKeepDownloadingWhilePaused: true, + shouldAutoplay: true, + isGaplessPlaybackEnabled: true, + replayGainMode: ReplayGainMode.Off, + streamingQuality: PlaybackStreamingQuality.Auto, + vuMeterOrientation: VuMeterOrientation.Horizontal, + vuMeterSegmentCount: 20, + vuMeterSegmentGap: 4, + vuMeterMediumThreshold: 0.35, + vuMeterHighThreshold: 0.9, + vuMeterShowPeak: false, + vuMeterPeakHoldDurationInMilliseconds: 1200, + vuMeterReleasePerSecond: 7.5, + vuMeterPeakReleasePerSecond: 0.25, + volume: 1.0, + isMuted: false); // Assert Assert.False(result.IsFailure); @@ -92,6 +135,15 @@ public class UserSettingsTests Assert.True(result.Value.ShouldAggregateMetadataWhenMissing); Assert.True(result.Value.ShouldRenderPdfAsImages); Assert.True(result.Value.ShouldPreserveBookStyles); + Assert.Equal(VuMeterOrientation.Horizontal, result.Value.VuMeterOrientation); + Assert.Equal(20, result.Value.VuMeterSegmentCount); + Assert.Equal(4, result.Value.VuMeterSegmentGap); + Assert.Equal(0.35, result.Value.VuMeterMediumThreshold); + Assert.Equal(0.9, result.Value.VuMeterHighThreshold); + Assert.False(result.Value.VuMeterShowPeak); + Assert.Equal(1200, result.Value.VuMeterPeakHoldDurationInMilliseconds); + Assert.Equal(7.5, result.Value.VuMeterReleasePerSecond); + Assert.Equal(0.25, result.Value.VuMeterPeakReleasePerSecond); } [Fact] @@ -116,13 +168,48 @@ public class UserSettingsTests UserSettingsId id = _userSettingsIdFixture.Create(); // Act - Result result = UserSettings.Create(id, userId, isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false, shouldAggregateArtworkWhenMissing: false, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: true, shouldKeepDownloadingWhilePaused: true, shouldAutoplay: true, isGaplessPlaybackEnabled: true, replayGainMode: ReplayGainMode.Off, streamingQuality: PlaybackStreamingQuality.Auto, vuMeterOrientation: VuMeterOrientation.Vertical, vuMeterSegmentCount: 12, vuMeterSegmentGap: 1, vuMeterMediumThreshold: 0.6, vuMeterHighThreshold: 0.8, vuMeterShowPeak: true, vuMeterPeakHoldDurationInMilliseconds: 650, vuMeterReleasePerSecond: 1.5, vuMeterPeakReleasePerSecond: 0.65, volume: 1.0, isMuted: false); + Result result = UserSettings.Create( + id, + userId, + isPaginationEnabled: true, + itemsPerPage: 24, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false, + shouldAggregateArtworkWhenMissing: false, + shouldRenderPdfAsImages: false, + shouldPreserveBookStyles: true, + shouldKeepDownloadingWhilePaused: true, + shouldAutoplay: true, + isGaplessPlaybackEnabled: true, + replayGainMode: ReplayGainMode.Off, + streamingQuality: PlaybackStreamingQuality.Auto, + vuMeterOrientation: VuMeterOrientation.Horizontal, + vuMeterSegmentCount: 24, + vuMeterSegmentGap: 3, + vuMeterMediumThreshold: 0.4, + vuMeterHighThreshold: 0.95, + vuMeterShowPeak: false, + vuMeterPeakHoldDurationInMilliseconds: 800, + vuMeterReleasePerSecond: 9.5, + vuMeterPeakReleasePerSecond: 0.5, + volume: 1.0, + isMuted: false); // Assert Assert.False(result.IsFailure); Assert.Equal(id, result.Value.Id); Assert.Equal(userId, result.Value.UserId); Assert.Equal(24, result.Value.ItemsPerPage); + Assert.Equal(VuMeterOrientation.Horizontal, result.Value.VuMeterOrientation); + Assert.Equal(24, result.Value.VuMeterSegmentCount); + Assert.Equal(3, result.Value.VuMeterSegmentGap); + Assert.Equal(0.4, result.Value.VuMeterMediumThreshold); + Assert.Equal(0.95, result.Value.VuMeterHighThreshold); + Assert.False(result.Value.VuMeterShowPeak); + Assert.Equal(800, result.Value.VuMeterPeakHoldDurationInMilliseconds); + Assert.Equal(9.5, result.Value.VuMeterReleasePerSecond); + Assert.Equal(0.5, result.Value.VuMeterPeakReleasePerSecond); } [Fact] @@ -130,9 +217,33 @@ public class UserSettingsTests { // Arrange UserSettings userSettings = _userSettingsFixture.Create(); + double previousVolume = userSettings.Volume; + bool previousIsMuted = userSettings.IsMuted; // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true, shouldAggregateArtworkWhenMissing: true, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true, shouldKeepDownloadingWhilePaused: true, shouldAutoplay: true, isGaplessPlaybackEnabled: true, replayGainMode: ReplayGainMode.Off, streamingQuality: PlaybackStreamingQuality.Auto, vuMeterOrientation: VuMeterOrientation.Vertical, vuMeterSegmentCount: 12, vuMeterSegmentGap: 1, vuMeterMediumThreshold: 0.6, vuMeterHighThreshold: 0.8, vuMeterShowPeak: true, vuMeterPeakHoldDurationInMilliseconds: 650, vuMeterReleasePerSecond: 1.5, vuMeterPeakReleasePerSecond: 0.65); + Result result = userSettings.UpdateSettings( + isPaginationEnabled: false, + itemsPerPage: 12, + shouldIgnoreThePrefixForAlphaPicker: true, + isThemeCachingEnabled: false, + shouldAggregateMetadataWhenMissing: true, + shouldAggregateArtworkWhenMissing: true, + shouldRenderPdfAsImages: true, + shouldPreserveBookStyles: true, + shouldKeepDownloadingWhilePaused: true, + shouldAutoplay: true, + isGaplessPlaybackEnabled: true, + replayGainMode: ReplayGainMode.Off, + streamingQuality: PlaybackStreamingQuality.Auto, + vuMeterOrientation: VuMeterOrientation.Horizontal, + vuMeterSegmentCount: 30, + vuMeterSegmentGap: 5, + vuMeterMediumThreshold: 0.3, + vuMeterHighThreshold: 0.95, + vuMeterShowPeak: false, + vuMeterPeakHoldDurationInMilliseconds: 1500, + vuMeterReleasePerSecond: 8.0, + vuMeterPeakReleasePerSecond: 0.4); // Assert Assert.False(result.IsFailure); @@ -143,5 +254,17 @@ public class UserSettingsTests Assert.True(userSettings.ShouldAggregateMetadataWhenMissing); Assert.True(userSettings.ShouldRenderPdfAsImages); Assert.True(userSettings.ShouldPreserveBookStyles); + Assert.Equal(VuMeterOrientation.Horizontal, userSettings.VuMeterOrientation); + Assert.Equal(30, userSettings.VuMeterSegmentCount); + Assert.Equal(5, userSettings.VuMeterSegmentGap); + Assert.Equal(0.3, userSettings.VuMeterMediumThreshold); + Assert.Equal(0.95, userSettings.VuMeterHighThreshold); + Assert.False(userSettings.VuMeterShowPeak); + Assert.Equal(1500, userSettings.VuMeterPeakHoldDurationInMilliseconds); + Assert.Equal(8.0, userSettings.VuMeterReleasePerSecond); + Assert.Equal(0.4, userSettings.VuMeterPeakReleasePerSecond); + // The playback state the player reports automatically is not part of the settings the user edits. + Assert.Equal(previousVolume, userSettings.Volume); + Assert.Equal(previousIsMuted, userSettings.IsMuted); } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index e734623c..0ca6d9e8 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Enums.AudioLibrary; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; @@ -70,4 +71,41 @@ public class UpdateUserSettingsEndpointTests Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean()); } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardVuMeterSettingsToApi() + { + // Arrange + UserSettingsDto request = _userSettingsDtoFixture.Create( + vuMeterOrientation: VuMeterOrientation.Horizontal, + vuMeterSegmentCount: 20, + vuMeterSegmentGap: 4, + vuMeterMediumThreshold: 0.35, + vuMeterHighThreshold: 0.9, + vuMeterShowPeak: false, + vuMeterPeakHoldDurationInMilliseconds: 1200, + vuMeterReleasePerSecond: 7.5, + vuMeterPeakReleasePerSecond: 0.25); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Web.Common.Requests.Common.EmptyRequest()); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + Assert.NotNull(result); + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.Users.UPDATE_USER_SETTINGS, + Arg.Is(settings => + settings.VuMeterOrientation == VuMeterOrientation.Horizontal && + settings.VuMeterSegmentCount == 20 && + settings.VuMeterSegmentGap == 4 && + settings.VuMeterMediumThreshold == 0.35 && + settings.VuMeterHighThreshold == 0.9 && + settings.VuMeterShowPeak == false && + settings.VuMeterPeakHoldDurationInMilliseconds == 1200 && + settings.VuMeterReleasePerSecond == 7.5 && + settings.VuMeterPeakReleasePerSecond == 0.25), + Arg.Any()); + } }