Implements tests for commit 2e9f7d8496

This commit is contained in:
BinaryAlley committed 2026-10-28 23:50:00 +02:00
1 parent a75447062f
commit 468f1846f1
18 files changed
+1711 -48

No files matched your search

@@ -36,4 +36,7 @@ public sealed record ValidatorUtilitiesTestRequest(
int? InclusiveNullableIntValue,
string? EqualValue,
string? EqualComparisonValue,
string? TextualEnumValue);
string? TextualEnumValue,
double? NullableDoubleValue,
double? NullableDoubleComparisonValue,
double? InclusiveNullableDoubleValue);
@@ -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;
/// <summary>
/// Creates a new <see cref="ValidatorUtilitiesTestRequest"/> instance with randomized test data that satisfies all validation rules.
@@ -45,6 +48,12 @@ public class ValidatorUtilitiesTestRequestFixture
/// <param name="equalValue">Optional. The value that must equal the comparison value.</param>
/// <param name="equalComparisonValue">Optional. The comparison value.</param>
/// <param name="textualEnumValue">Optional. The textual enum value that must be a member name of the test enumeration.</param>
/// <param name="nullableDoubleValue">Optional. The nullable double value that must be greater than or equal to the selected comparison value.</param>
/// <param name="nullableDoubleComparisonValue">Optional. The nullable double comparison value selected from the request.</param>
/// <param name="inclusiveNullableDoubleValue">Optional. The nullable double value that must be between 1 and 10.</param>
/// <param name="includeNullableDoubleValue">Whether to generate the nullable double value, or leave it <see langword="null"/>.</param>
/// <param name="includeNullableDoubleComparisonValue">Whether to generate the nullable double comparison value, or leave it <see langword="null"/>.</param>
/// <param name="includeInclusiveNullableDoubleValue">Whether to generate the inclusive nullable double value, or leave it <see langword="null"/>.</param>
/// <returns>A configured <see cref="ValidatorUtilitiesTestRequest"/> instance.</returns>
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<ValidatorUtilitiesTestRequest>()
@@ -102,7 +117,10 @@ public class ValidatorUtilitiesTestRequestFixture
InclusiveNullableIntValue: inclusiveNullableIntValue ?? f.Random.Int(1, 10),
EqualValue: equalValue ?? "same",
EqualComparisonValue: equalComparisonValue ?? "same",
TextualEnumValue: textualEnumValue ?? f.PickRandom<ValidatorUtilitiesTestEnum>().ToString()))
TextualEnumValue: textualEnumValue ?? f.PickRandom<ValidatorUtilitiesTestEnum>().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();
}
@@ -41,6 +41,15 @@ public class UpdateUserSettingsCommandFixture
/// <param name="vuMeterPeakHoldDurationInMilliseconds">Optional. The time a peak of the VU meter is held before it starts falling.</param>
/// <param name="vuMeterReleasePerSecond">Optional. The number of level units the display of the VU meter falls per second when the input level drops.</param>
/// <param name="vuMeterPeakReleasePerSecond">Optional. The number of level units the peak of the VU meter falls per second after its hold time elapsed.</param>
/// <param name="includeVuMeterOrientation">Whether to generate the VU meter orientation, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterSegmentCount">Whether to generate the VU meter segment count, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterSegmentGap">Whether to generate the VU meter segment gap, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterMediumThreshold">Whether to generate the VU meter medium threshold, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterHighThreshold">Whether to generate the VU meter high threshold, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterShowPeak">Whether to generate the VU meter peak marker setting, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterPeakHoldDurationInMilliseconds">Whether to generate the VU meter peak hold duration, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterReleasePerSecond">Whether to generate the VU meter release rate, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterPeakReleasePerSecond">Whether to generate the VU meter peak release rate, or leave it <see langword="null"/>.</param>
/// <returns>The created command.</returns>
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<UpdateUserSettingsCommand>()
.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<ReplayGainMode>())
.RuleFor(x => x.StreamingQuality, f => streamingQuality ?? f.PickRandom<PlaybackStreamingQuality>())
.RuleFor(x => x.VuMeterOrientation, f => vuMeterOrientation ?? f.PickRandom<VuMeterOrientation>())
.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<VuMeterOrientation>() : 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();
}
@@ -42,6 +42,15 @@ public class UpdateUserSettingsRequestFixture
/// <param name="vuMeterPeakHoldDurationInMilliseconds">The time a peak of the VU meter is held before it starts falling.</param>
/// <param name="vuMeterReleasePerSecond">The number of level units the display of the VU meter falls per second when the input level drops.</param>
/// <param name="vuMeterPeakReleasePerSecond">The number of level units the peak of the VU meter falls per second after its hold time elapsed.</param>
/// <param name="includeVuMeterOrientation">Whether to generate the VU meter orientation, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterSegmentCount">Whether to generate the VU meter segment count, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterSegmentGap">Whether to generate the VU meter segment gap, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterMediumThreshold">Whether to generate the VU meter medium threshold, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterHighThreshold">Whether to generate the VU meter high threshold, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterShowPeak">Whether to generate the VU meter peak marker setting, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterPeakHoldDurationInMilliseconds">Whether to generate the VU meter peak hold duration, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterReleasePerSecond">Whether to generate the VU meter release rate, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterPeakReleasePerSecond">Whether to generate the VU meter peak release rate, or leave it <see langword="null"/>.</param>
/// <returns>The created <see cref="UpdateUserSettingsRequest"/>.</returns>
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<ReplayGainMode>(),
streamingQuality ?? _faker.PickRandom<PlaybackStreamingQuality>(),
vuMeterOrientation ?? _faker.PickRandom<VuMeterOrientation>(),
vuMeterSegmentCount ?? _faker.Random.Int(1, 128),
vuMeterSegmentGap ?? _faker.Random.Int(0, 32),
includeVuMeterOrientation ? vuMeterOrientation ?? _faker.PickRandom<VuMeterOrientation>() : 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);
}
/// <summary>
@@ -34,6 +34,24 @@ public class UserSettingsDtoFixture
/// <param name="isGaplessPlaybackEnabled">Whether the player transitions between consecutive tracks without a gap.</param>
/// <param name="replayGainMode">The way ReplayGain normalization is applied to the tracks the user plays.</param>
/// <param name="streamingQuality">The quality cap applied to the audio the server normalizes for the user.</param>
/// <param name="vuMeterOrientation">The direction in which each channel of the VU meter of the audio player grows.</param>
/// <param name="vuMeterSegmentCount">The number of segments each channel of the VU meter is divided into.</param>
/// <param name="vuMeterSegmentGap">The gap, in pixels, between the segments and the channels of the VU meter.</param>
/// <param name="vuMeterMediumThreshold">The level above which a segment of the VU meter is drawn with its medium state.</param>
/// <param name="vuMeterHighThreshold">The level above which a segment of the VU meter is drawn with its high state.</param>
/// <param name="vuMeterShowPeak">Whether the VU meter holds the peak level of each channel after it falls.</param>
/// <param name="vuMeterPeakHoldDurationInMilliseconds">The time a peak of the VU meter is held before it starts falling.</param>
/// <param name="vuMeterReleasePerSecond">The number of level units the display of the VU meter falls per second when the input level drops.</param>
/// <param name="vuMeterPeakReleasePerSecond">The number of level units the peak of the VU meter falls per second after its hold time elapsed.</param>
/// <param name="includeVuMeterOrientation">Whether to generate the VU meter orientation, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterSegmentCount">Whether to generate the VU meter segment count, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterSegmentGap">Whether to generate the VU meter segment gap, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterMediumThreshold">Whether to generate the VU meter medium threshold, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterHighThreshold">Whether to generate the VU meter high threshold, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterShowPeak">Whether to generate the VU meter peak marker setting, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterPeakHoldDurationInMilliseconds">Whether to generate the VU meter peak hold duration, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterReleasePerSecond">Whether to generate the VU meter release rate, or leave it <see langword="null"/>.</param>
/// <param name="includeVuMeterPeakReleasePerSecond">Whether to generate the VU meter peak release rate, or leave it <see langword="null"/>.</param>
/// <returns>A configured <see cref="UserSettingsDto"/> instance.</returns>
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<ReplayGainMode>(),
StreamingQuality = streamingQuality ?? _faker.PickRandom<PlaybackStreamingQuality>()
StreamingQuality = streamingQuality ?? _faker.PickRandom<PlaybackStreamingQuality>(),
VuMeterOrientation = includeVuMeterOrientation ? vuMeterOrientation ?? _faker.PickRandom<VuMeterOrientation>() : 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
};
}
@@ -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<LuminaDbContext>().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<Created> 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);
}
}
@@ -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<AuthenticatedLuminaApi
Assert.Equal(storedSettings.IsPaginationEnabled, result.IsPaginationEnabled);
Assert.Equal(storedSettings.ItemsPerPage, result.ItemsPerPage);
Assert.Equal(storedSettings.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
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);
}
[Fact]
@@ -91,6 +101,15 @@ public class GetUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApi
Assert.True(result!.IsPaginationEnabled);
Assert.Equal(48, result.ItemsPerPage);
Assert.False(result.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(VuMeterOrientation.Vertical, result.VuMeterOrientation);
Assert.Equal(12, result.VuMeterSegmentCount);
Assert.Equal(1, result.VuMeterSegmentGap);
Assert.Equal(0.6, result.VuMeterMediumThreshold);
Assert.Equal(0.8, result.VuMeterHighThreshold);
Assert.True(result.VuMeterShowPeak);
Assert.Equal(650, result.VuMeterPeakHoldDurationInMilliseconds);
Assert.Equal(3.0, result.VuMeterReleasePerSecond);
Assert.Equal(0.65, result.VuMeterPeakReleasePerSecond);
}
[Fact]
@@ -116,7 +135,16 @@ public class GetUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApi
userId: userId,
isPaginationEnabled: false,
itemsPerPage: 24,
shouldIgnoreThePrefixForAlphaPicker: true);
shouldIgnoreThePrefixForAlphaPicker: true,
vuMeterOrientation: VuMeterOrientation.Horizontal,
vuMeterSegmentCount: 20,
vuMeterSegmentGap: 4,
vuMeterMediumThreshold: 0.35,
vuMeterHighThreshold: 0.9,
vuMeterShowPeak: false,
vuMeterPeakHoldDurationInMilliseconds: 1200,
vuMeterReleasePerSecond: 7.5,
vuMeterPeakReleasePerSecond: 0.25);
dbContext.UserSettings.Add(settings);
await dbContext.SaveChangesAsync();
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
using Lumina.Contracts.Requests.UsersManagement.Settings;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
@@ -63,7 +64,16 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
itemsPerPage: 24,
shouldIgnoreThePrefixForAlphaPicker: true,
isThemeCachingEnabled: false,
shouldAggregateMetadataWhenMissing: false
shouldAggregateMetadataWhenMissing: 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
@@ -82,6 +92,15 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
Assert.Equal(24, storedSettings.ItemsPerPage);
Assert.True(storedSettings.ShouldIgnoreThePrefixForAlphaPicker);
Assert.False(storedSettings.IsThemeCachingEnabled);
Assert.Equal(VuMeterOrientation.Horizontal, storedSettings.VuMeterOrientation);
Assert.Equal(20, storedSettings.VuMeterSegmentCount);
Assert.Equal(4, storedSettings.VuMeterSegmentGap);
Assert.Equal(0.35, storedSettings.VuMeterMediumThreshold);
Assert.Equal(0.9, storedSettings.VuMeterHighThreshold);
Assert.False(storedSettings.VuMeterShowPeak);
Assert.Equal(1200, storedSettings.VuMeterPeakHoldDurationInMilliseconds);
Assert.Equal(7.5, storedSettings.VuMeterReleasePerSecond);
Assert.Equal(0.25, storedSettings.VuMeterPeakReleasePerSecond);
}
[Fact]
@@ -100,21 +119,7 @@ public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLumina
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<AuthenticatedLumina
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterOrientationIsNull_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterOrientation: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterOrientationCannotBeNull");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterSegmentCountIsNull_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterSegmentCount: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterSegmentCountCannotBeNull");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterSegmentGapIsNull_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterSegmentGap: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterSegmentGapCannotBeNull");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterMediumThresholdIsNull_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterMediumThreshold: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterMediumThresholdCannotBeNull");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsNull_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterHighThreshold: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterHighThresholdCannotBeNull");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterShowPeakIsNull_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterShowPeak: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterShowPeakCannotBeNull");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterPeakHoldDurationIsNull_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterPeakHoldDurationInMilliseconds: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterPeakHoldDurationCannotBeNull");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterReleasePerSecondIsNull_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterReleasePerSecond: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterReleasePerSecondCannotBeNull");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterPeakReleasePerSecondIsNull_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterPeakReleasePerSecond: false);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterPeakReleasePerSecondCannotBeNull");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterOrientationIsNotDefined_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterOrientation: (VuMeterOrientation)999);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "InvalidVuMeterOrientation");
}
[Theory]
[InlineData(0)] // below the minimum
[InlineData(129)] // above the maximum
public async Task UpdateUserSettings_WhenVuMeterSegmentCountIsOutOfRange_ShouldReturnValidationError(int vuMeterSegmentCount)
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterSegmentCount: vuMeterSegmentCount);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterSegmentCountMustBeBetweenOneAndOneHundredTwentyEight");
}
[Theory]
[InlineData(-1)] // below the minimum
[InlineData(33)] // above the maximum
public async Task UpdateUserSettings_WhenVuMeterSegmentGapIsOutOfRange_ShouldReturnValidationError(int vuMeterSegmentGap)
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterSegmentGap: vuMeterSegmentGap);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterSegmentGapMustBeBetweenZeroAndThirtyTwo");
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(1.01)] // just above the maximum
public async Task UpdateUserSettings_WhenVuMeterMediumThresholdIsOutOfRange_ShouldReturnValidationError(double vuMeterMediumThreshold)
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
vuMeterMediumThreshold: vuMeterMediumThreshold,
vuMeterHighThreshold: 1.0);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterMediumThresholdMustBeBetweenZeroAndOne");
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(1.01)] // just above the maximum
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsOutOfRange_ShouldReturnValidationError(double vuMeterHighThreshold)
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
vuMeterMediumThreshold: 0.0,
vuMeterHighThreshold: vuMeterHighThreshold);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterHighThresholdMustBeBetweenZeroAndOne");
}
[Fact]
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsLowerThanMediumThreshold_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
vuMeterMediumThreshold: 0.9,
vuMeterHighThreshold: 0.1);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "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 async Task UpdateUserSettings_WhenVuMeterHighThresholdIsGreaterThanOrEqualToMediumThreshold_ShouldUpdateSettings(
double vuMeterMediumThreshold,
double vuMeterHighThreshold)
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
vuMeterMediumThreshold: vuMeterMediumThreshold,
vuMeterHighThreshold: vuMeterHighThreshold);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Theory]
[InlineData(-1)] // below the minimum
[InlineData(10001)] // above the maximum
public async Task UpdateUserSettings_WhenVuMeterPeakHoldDurationIsOutOfRange_ShouldReturnValidationError(int vuMeterPeakHoldDurationInMilliseconds)
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
vuMeterPeakHoldDurationInMilliseconds: vuMeterPeakHoldDurationInMilliseconds);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterPeakHoldDurationMustBeBetweenZeroAndTenThousandMilliseconds");
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(100.01)] // just above the maximum
public async Task UpdateUserSettings_WhenVuMeterReleasePerSecondIsOutOfRange_ShouldReturnValidationError(double vuMeterReleasePerSecond)
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterReleasePerSecond: vuMeterReleasePerSecond);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterReleasePerSecondMustBeBetweenZeroAndOneHundred");
}
[Theory]
[InlineData(-0.01)] // just below the minimum
[InlineData(100.01)] // just above the maximum
public async Task UpdateUserSettings_WhenVuMeterPeakReleasePerSecondIsOutOfRange_ShouldReturnValidationError(double vuMeterPeakReleasePerSecond)
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterPeakReleasePerSecond: vuMeterPeakReleasePerSecond);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
await AssertValidationErrorAsync(response, "VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred");
}
[Fact]
public async Task UpdateUserSettings_WhenAllVuMeterValuesAreAtTheirMinimums_ShouldUpdateSettings()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
vuMeterOrientation: VuMeterOrientation.Vertical,
vuMeterSegmentCount: 1,
vuMeterSegmentGap: 0,
vuMeterMediumThreshold: 0.0,
vuMeterHighThreshold: 0.0,
vuMeterShowPeak: false,
vuMeterPeakHoldDurationInMilliseconds: 0,
vuMeterReleasePerSecond: 0.0,
vuMeterPeakReleasePerSecond: 0.0);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task UpdateUserSettings_WhenAllVuMeterValuesAreAtTheirMaximums_ShouldUpdateSettings()
{
// Arrange
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
vuMeterOrientation: VuMeterOrientation.Horizontal,
vuMeterSegmentCount: 128,
vuMeterSegmentGap: 32,
vuMeterMediumThreshold: 1.0,
vuMeterHighThreshold: 1.0,
vuMeterShowPeak: true,
vuMeterPeakHoldDurationInMilliseconds: 10000,
vuMeterReleasePerSecond: 100.0,
vuMeterPeakReleasePerSecond: 100.0);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
/// <summary>
/// Asserts that <paramref name="response"/> is a validation problem response carrying the specified error.
/// </summary>
/// <param name="response">The response to assert.</param>
/// <param name="expectedError">The exact error description expected in the validation errors.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task AssertValidationErrorAsync(HttpResponseMessage response, string expectedError)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains(expectedError, errors["General.Validation"]);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
@@ -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<LuminaWebFactory>
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());
}
}
@@ -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<LuminaWebFactory>
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<UserSettingsDto>(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);
}
/// <summary>
/// Builds the update request that sends the given <paramref name="settings"/> to the user settings endpoint.
/// </summary>
@@ -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<LuminaApiFactory>
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);
}
/// <summary>
/// Asserts that the response body does not expose exception details, stack frames, or database internals.
/// </summary>
/// <param name="content">The response body to inspect.</param>
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);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
@@ -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);
}
}
@@ -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<Error> result = _validator.TestValidate(request);
// Assert
result.ShouldNotHaveValidationError(s_nullableDoubleValueError);
}
[Fact]
public void Validate_WhenNullableDoubleComparisonValueIsNull_ShouldNotHaveValidationError()
{
// Arrange
ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(includeNullableDoubleComparisonValue: false);
// Act
List<Error> 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<Error> 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<Error> 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<Error> result = _validator.TestValidate(request);
// Assert
result.ShouldHaveValidationError(s_nullableDoubleValueError);
}
[Fact]
public void Validate_WhenInclusiveNullableDoubleValueIsNull_ShouldNotHaveValidationError()
{
// Arrange
ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(includeInclusiveNullableDoubleValue: false);
// Act
List<Error> 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<Error> 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<Error> result = _validator.TestValidate(request);
// Assert
result.ShouldNotHaveValidationError(s_inclusiveNullableDoubleValueError);
}
[ExcludeFromCodeCoverage]
private sealed class ValidatorUtilitiesTestValidator : AbstractValidator<ValidatorUtilitiesTestRequest>
{
@@ -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");
}
@@ -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<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -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<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> 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<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.UserSettings.VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
@@ -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<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
/// <summary>
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
/// </summary>
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().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());
}
}
@@ -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<UserSettings> 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<UserSettings> 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<UserSettings> 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<UserSettings> 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<Updated> 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<Updated> 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);
}
}
@@ -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<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
.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<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(
ApiRoutes.Users.UPDATE_USER_SETTINGS,
Arg.Is<UserSettingsDto>(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<CancellationToken>());
}
}