Adds the scheduling module tests and centralizes domain event test fixtures

This commit is contained in:
BinaryAlley committed 2026-09-04 00:16:41 -07:00
1 parent 237be9e2c8
commit 99a6159f7f
135 files changed
+10203 -165

No files matched your search

@@ -0,0 +1,183 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.AddScheduledJob;
/// <summary>
/// Contains integration tests for the <see cref="AddScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddScheduledJobEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
private readonly List<Guid> _createdScheduledJobIds = [];
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddScheduledJobEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task AddScheduledJob_WhenCalledWithValidIntervalRequest_ShouldCreateScheduledJob()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(
name: $"Scan job {Guid.NewGuid()}",
taskType: ScheduledTaskType.ScanMediaLibraries,
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 60);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
ScheduledJobResponse? result = JsonSerializer.Deserialize<ScheduledJobResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(request.Name, result!.Name);
Assert.Equal(request.TaskType, result.TaskType);
Assert.Equal(ScheduleType.WithIntervalInMinutes, result.ScheduleType);
Assert.Equal(60, result.IntervalMinutes);
Assert.Equal(ScheduledJobStatus.Added, result.Status);
_createdScheduledJobIds.Add(result.Id);
}
[Fact]
public async Task AddScheduledJob_WhenCalledWithValidDailyRequest_ShouldCreateScheduledJob()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(
name: $"Daily job {Guid.NewGuid()}",
taskType: ScheduledTaskType.CleanTemporaryFiles,
scheduleType: ScheduleType.DailyAtHourAndMinute,
hour: 6,
minute: 30);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
ScheduledJobResponse? result = JsonSerializer.Deserialize<ScheduledJobResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(ScheduleType.DailyAtHourAndMinute, result!.ScheduleType);
Assert.Equal(6, result.Hour);
Assert.Equal(30, result.Minute);
Assert.Null(result.IntervalMinutes);
_createdScheduledJobIds.Add(result.Id);
}
[Fact]
public async Task AddScheduledJob_WhenCalledWithInvalidName_ShouldReturnValidationProblem()
{
// Arrange
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(
name: " ",
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 60);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", 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("General.Validation", problemDetails["title"].GetString());
}
[Fact]
public async Task AddScheduledJob_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.GetScheduledJobs;
/// <summary>
/// Contains integration tests for the <see cref="GetScheduledJobsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetScheduledJobsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
private readonly List<Guid> _createdScheduledJobIds = [];
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetScheduledJobsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task GetScheduledJobs_WhenScheduledJobsExist_ShouldReturnTheListOfScheduledJobs()
{
// Arrange
AddScheduledJobRequest addRequest = _addScheduledJobRequestFixture.Create(
name: $"Listed job {Guid.NewGuid()}",
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 30);
HttpResponseMessage addResponse = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", addRequest);
string addContent = await addResponse.Content.ReadAsStringAsync();
ScheduledJobResponse? createdJob = JsonSerializer.Deserialize<ScheduledJobResponse>(addContent, _jsonOptions);
Assert.NotNull(createdJob);
_createdScheduledJobIds.Add(createdJob!.Id);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/scheduled-jobs");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<ScheduledJobResponse>? result = JsonSerializer.Deserialize<List<ScheduledJobResponse>>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Contains(result!, scheduledJob => scheduledJob.Id == createdJob.Id && scheduledJob.Name == addRequest.Name);
}
[Fact]
public async Task GetScheduledJobs_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/scheduled-jobs");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.GetSchedulerDisplayPreferences;
/// <summary>
/// Contains integration tests for the <see cref="GetSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetSchedulerDisplayPreferencesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="GetSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetSchedulerDisplayPreferencesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task GetSchedulerDisplayPreferences_WhenNoPreferencesStored_ShouldReturnTheDefaultPreferences()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/scheduled-jobs/display-preferences");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
SchedulerDisplayPreferencesResponse? result = JsonSerializer.Deserialize<SchedulerDisplayPreferencesResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Null(result!.JobTypeFilter);
Assert.Equal(10, result.DisplayTimeSpan);
Assert.Equal(SchedulerDisplayTimeUnit.Minutes, result.DisplayTimeUnit);
}
[Fact]
public async Task GetSchedulerDisplayPreferences_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/scheduled-jobs/display-preferences");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,152 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.RemoveScheduledJob;
/// <summary>
/// Contains integration tests for the <see cref="RemoveScheduledJobEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveScheduledJobEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly AddScheduledJobRequestFixture _addScheduledJobRequestFixture = new();
private readonly List<Guid> _createdScheduledJobIds = [];
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RemoveScheduledJobEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task RemoveScheduledJob_WhenScheduledJobExists_ShouldRemoveIt()
{
// Arrange
ScheduledJobResponse createdJob = await CreateScheduledJobAsync();
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/scheduled-jobs/{createdJob.Id}");
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == createdJob.Id));
}
[Fact]
public async Task RemoveScheduledJob_WhenScheduledJobDoesNotExist_ShouldReturnNotFound()
{
// Arrange
Guid missingScheduledJobId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/scheduled-jobs/{missingScheduledJobId}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, 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.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("ScheduledJobNotFound", problemDetails["detail"].GetString());
}
[Fact]
public async Task RemoveScheduledJob_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
Guid scheduledJobId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/scheduled-jobs/{scheduledJobId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
/// <summary>
/// Creates a scheduled job through the API and returns its response.
/// </summary>
/// <returns>The created scheduled job response.</returns>
private async Task<ScheduledJobResponse> CreateScheduledJobAsync()
{
AddScheduledJobRequest addRequest = _addScheduledJobRequestFixture.Create(
name: $"Removable job {Guid.NewGuid()}",
scheduleType: ScheduleType.WithIntervalInMinutes,
intervalMinutes: 60);
HttpResponseMessage addResponse = await _client.PostAsJsonAsync("/api/v1/scheduled-jobs", addRequest);
string addContent = await addResponse.Content.ReadAsStringAsync();
ScheduledJobResponse? createdJob = JsonSerializer.Deserialize<ScheduledJobResponse>(addContent, _jsonOptions);
Assert.NotNull(createdJob);
_createdScheduledJobIds.Add(createdJob!.Id);
return createdJob;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,142 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Scheduling;
using Lumina.Contracts.Requests.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Scheduling.UpdateSchedulerDisplayPreferences;
/// <summary>
/// Contains integration tests for the <see cref="UpdateSchedulerDisplayPreferencesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateSchedulerDisplayPreferencesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly UpdateSchedulerDisplayPreferencesRequestFixture _updateSchedulerDisplayPreferencesRequestFixture = new();
private Guid? _createdPreferencesUserId;
private HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateSchedulerDisplayPreferencesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateSchedulerDisplayPreferencesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes an authenticated admin API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
}
[Fact]
public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithValidRequest_ShouldPersistThePreferences()
{
// Arrange
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(
jobTypeFilter: ScheduledTaskType.ScanMediaLibraries,
displayTimeSpan: 30,
displayTimeUnit: SchedulerDisplayTimeUnit.Minutes);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/scheduled-jobs/display-preferences", request);
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
HttpResponseMessage getResponse = await _client.GetAsync("/api/v1/scheduled-jobs/display-preferences");
string content = await getResponse.Content.ReadAsStringAsync();
SchedulerDisplayPreferencesResponse? result = JsonSerializer.Deserialize<SchedulerDisplayPreferencesResponse>(content, _jsonOptions);
Assert.NotNull(result);
Assert.Equal(ScheduledTaskType.ScanMediaLibraries, result!.JobTypeFilter);
Assert.Equal(30, result.DisplayTimeSpan);
Assert.Equal(SchedulerDisplayTimeUnit.Minutes, result.DisplayTimeUnit);
_createdPreferencesUserId = result.UserId;
}
[Fact]
public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithNonPositiveTimeSpan_ShouldReturnValidationProblem()
{
// Arrange
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(displayTimeSpan: 0);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/scheduled-jobs/display-preferences", 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("General.Validation", problemDetails["title"].GetString());
}
[Fact]
public async Task UpdateSchedulerDisplayPreferences_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
{
// Arrange
_client = await _apiFactory.CreateAuthenticatedClientAsync();
UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create();
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/scheduled-jobs/display-preferences", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Wipe the tables touched by the tests, because the in-memory database of the class factory is shared between the tests of the class.
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobExecutionEntity>().ExecuteDeleteAsync();
await dbContext.Set<ScheduledJobEntity>().ExecuteDeleteAsync();
await dbContext.Set<SchedulerDisplayPreferencesEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}