mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 21:11:10 +00:00
Adds authorization module tests
This commit is contained in:
1 parent
718e1c49cf
commit
0114ff13e8
125 files changed
+10411
-203
No files matched your search
+2
-2
@@ -36,7 +36,7 @@ public class BookJsonConverter : JsonConverter<Book>
|
||||
JsonElement root = doc.RootElement;
|
||||
|
||||
Guid id = root.GetProperty("id").GetGuid();
|
||||
DateTime created = root.GetProperty("created").GetDateTime();
|
||||
DateTime createdOnUtc = root.GetProperty("createdOnUtc").GetDateTime();
|
||||
WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata"));
|
||||
BookFormat? format = null;
|
||||
if (root.TryGetProperty("format", out JsonElement formatElement))
|
||||
@@ -80,7 +80,7 @@ public class BookJsonConverter : JsonConverter<Book>
|
||||
Optional<string>.FromNullable(googleBooksId),
|
||||
Optional<string>.FromNullable(barnesAndNobleId),
|
||||
Optional<string>.FromNullable(appleBooksId),
|
||||
created,
|
||||
createdOnUtc,
|
||||
default,
|
||||
isbns,
|
||||
contributorIds,
|
||||
|
||||
+70
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -12,6 +13,7 @@ using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -102,6 +104,74 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an HTTP client with authentication headers and an admin test user with all permissions
|
||||
/// </summary>
|
||||
/// <returns>An HTTP client configured with admin auth headers</returns>
|
||||
public async Task<HttpClient> CreateAuthenticatedAdminClientAsync()
|
||||
{
|
||||
HttpClient client = CreateClient();
|
||||
TestUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
// add the X-Forwarded-For header
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For",
|
||||
$"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
|
||||
|
||||
// create and authenticate admin user
|
||||
await CreateAndAuthenticateAdminUser(client);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates and authenticates an admin test user with all permissions.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to configure with auth.</param>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateAndAuthenticateAdminUser(HttpClient client)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
|
||||
|
||||
// create test user
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = TestUsername!,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// set up admin permissions and roles
|
||||
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(user.Id, CancellationToken.None);
|
||||
await dataSeedService.SetDefaultAuthorizationRolesAsync(user.Id, CancellationToken.None);
|
||||
await dataSeedService.SetAdminRolePermissionsAsync(user.Id, CancellationToken.None);
|
||||
await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None);
|
||||
|
||||
// authenticate user
|
||||
LoginRequest loginRequest = new(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!"
|
||||
);
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// set auth header for subsequent requests
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Enums.Authorization;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Admin.Authorization.Permissions;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPermissionsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldReturnPermissions()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/permissions");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<PermissionResponse>? result = JsonSerializer.Deserialize<IEnumerable<PermissionResponse>>(content, _jsonOptions);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result.Should().NotBeEmpty();
|
||||
result!.Should().AllSatisfy(permission =>
|
||||
{
|
||||
permission.Id.Should().NotBe(Guid.Empty);
|
||||
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Act
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync(); // authenticated user, but not admin
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/permissions");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be("/api/v1/permissions");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync("/api/v1/permissions", cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
_apiFactory.Dispose();
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Enums.Authorization;
|
||||
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.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="AddRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddRoleEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldCreateRole()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)];
|
||||
|
||||
AddRoleRequest request = new(
|
||||
RoleName: "Editor",
|
||||
Permissions: permissions.Select(p => p.Id).ToList()
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/roles", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RolePermissionsResponse? result = JsonSerializer.Deserialize<RolePermissionsResponse>(content, _jsonOptions);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.Role.RoleName.Should().Be("Editor");
|
||||
result.Permissions.Should().HaveCount(2);
|
||||
result.Permissions.Should().AllSatisfy(permission =>
|
||||
{
|
||||
permission.Id.Should().NotBe(Guid.Empty);
|
||||
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
AddRoleRequest request = new(
|
||||
RoleName: "Editor",
|
||||
Permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/roles", request);
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be("/api/v1/roles");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRoleAlreadyExists_ShouldReturnConflict()
|
||||
{
|
||||
// Arrange
|
||||
AddRoleRequest request = new(
|
||||
RoleName: "Admin",
|
||||
Permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/roles", request);
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Conflict);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status409Conflict);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.10");
|
||||
problemDetails["title"].GetString().Should().Be("General.Conflict");
|
||||
problemDetails["detail"].GetString().Should().Be("RoleAlreadyExists");
|
||||
problemDetails["instance"].GetString().Should().Be("/api/v1/roles");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
AddRoleRequest request = new(
|
||||
RoleName: "Editor",
|
||||
Permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PostAsJsonAsync("/api/v1/roles", request, cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
_apiFactory.Dispose();
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteRoleEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldDeleteRole()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Create a test role first
|
||||
RoleEntity role = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "TestRole",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
dbContext.Roles.Add(role);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/roles/{role.Id}");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NoContent);
|
||||
|
||||
// Verify role was deleted
|
||||
RoleEntity? deletedRole = await dbContext.Roles.FirstOrDefaultAsync(r => r.Id == role.Id);
|
||||
deletedRole.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
Guid roleId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/roles/{roleId}");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/roles/{roleId}");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTryingToDeleteAdminRole_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
RoleEntity? adminRole = dbContext.Roles.FirstOrDefault(r => r.RoleName == "Admin");
|
||||
adminRole.Should().NotBeNull("Admin role should exist");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/roles/{adminRole!.Id}");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Forbidden");
|
||||
problemDetails["detail"].GetString().Should().Be("AdminRoleCannotBeDeleted");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/roles/{adminRole!.Id}");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRoleDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentRoleId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/roles/{nonExistentRoleId}");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails["title"].GetString().Should().Be("General.NotFound");
|
||||
problemDetails["detail"].GetString().Should().Be("RoleNotFound");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/roles/{nonExistentRoleId}");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
Guid roleId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.DeleteAsync($"/api/v1/roles/{roleId}", cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
_apiFactory.Dispose();
|
||||
}
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Enums.Authorization;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRolePermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolePermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolePermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetRolePermissionsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldReturnRolePermissions()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
RoleEntity? role = dbContext.Roles.FirstOrDefault();
|
||||
role.Should().NotBeNull("Admin role should exist");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/roles/{role!.Id}/permissions");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RolePermissionsResponse? result = JsonSerializer.Deserialize<RolePermissionsResponse>(content, _jsonOptions);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.Role.Id.Should().Be(role.Id);
|
||||
result.Role.RoleName.Should().Be("Admin");
|
||||
result.Permissions.Should().NotBeEmpty();
|
||||
result.Permissions.Should().AllSatisfy(permission =>
|
||||
{
|
||||
permission.Id.Should().NotBe(Guid.Empty);
|
||||
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync(); // authenticated user, but not admin
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
RoleEntity? role = dbContext.Roles.FirstOrDefault();
|
||||
role.Should().NotBeNull("Admin role should exist");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/roles/{role!.Id}/permissions");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/roles/{role.Id}/permissions");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithInvalidRoleId_ShouldReturnNotFound()
|
||||
{
|
||||
// Act
|
||||
Guid invalidRoleId = Guid.NewGuid();
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/roles/{invalidRoleId}/permissions");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails["title"].GetString().Should().Be("General.NotFound");
|
||||
problemDetails["detail"].GetString().Should().Be("RoleNotFound");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/roles/{invalidRoleId}/permissions");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
RoleEntity? role = dbContext.Roles.FirstOrDefault();
|
||||
role.Should().NotBeNull("Admin role should exist");
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/roles/{role!.Id}/permissions", cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
_apiFactory.Dispose();
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
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.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRolesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRolesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetRolesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldReturnRoles()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/roles");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<RoleResponse>? result = JsonSerializer.Deserialize<IEnumerable<RoleResponse>>(content, _jsonOptions);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result.Should().NotBeEmpty();
|
||||
result!.Should().Contain(role =>
|
||||
role.Id != Guid.Empty &&
|
||||
role.RoleName == "Admin"
|
||||
);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/roles");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be("/api/v1/roles");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync("/api/v1/roles", cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
_apiFactory.Dispose();
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Enums.Authorization;
|
||||
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.Admin.Authorization.Roles;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateRoleEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldUpdateRole()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
RoleEntity role = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "TestRole",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
dbContext.Roles.Add(role);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)];
|
||||
UpdateRoleRequest request = new(
|
||||
RoleId: role.Id,
|
||||
RoleName: "UpdatedRole",
|
||||
Permissions: permissions.Select(p => p.Id).ToList()
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/roles", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RolePermissionsResponse? result = JsonSerializer.Deserialize<RolePermissionsResponse>(content, _jsonOptions);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.Role.Id.Should().Be(role.Id);
|
||||
result.Role.RoleName.Should().Be("UpdatedRole");
|
||||
result.Permissions.Should().HaveCount(2);
|
||||
result.Permissions.Should().AllSatisfy(permission =>
|
||||
{
|
||||
permission.Id.Should().NotBe(Guid.Empty);
|
||||
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
UpdateRoleRequest request = new(
|
||||
RoleId: Guid.NewGuid(),
|
||||
RoleName: "UpdatedRole",
|
||||
Permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/roles", request);
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be("/api/v1/roles");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRoleDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentRoleId = Guid.NewGuid();
|
||||
UpdateRoleRequest request = new(
|
||||
RoleId: nonExistentRoleId,
|
||||
RoleName: "UpdatedRole",
|
||||
Permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/roles", request);
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails["title"].GetString().Should().Be("General.NotFound");
|
||||
problemDetails["detail"].GetString().Should().Be("RoleNotFound");
|
||||
problemDetails["instance"].GetString().Should().Be("/api/v1/roles");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
UpdateRoleRequest request = new(
|
||||
RoleId: Guid.NewGuid(),
|
||||
RoleName: "UpdatedRole",
|
||||
Permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PutAsJsonAsync($"/api/v1/roles", request, cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
_apiFactory.Dispose();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -139,7 +139,7 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnForbidden()
|
||||
public async Task ExecuteAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Users;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
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.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUsersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUsersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUsersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldReturnUsers()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/users");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<UserResponse>? result = JsonSerializer.Deserialize<IEnumerable<UserResponse>>(content, _jsonOptions);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result.Should().NotBeEmpty();
|
||||
result!.Should().AllSatisfy(user =>
|
||||
{
|
||||
user.Id.Should().NotBe(Guid.Empty);
|
||||
user.Username.Should().NotBeNullOrEmpty();
|
||||
user.CreatedOnUtc.Should().NotBe(default);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/users");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/users");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync("/api/v1/auth/users", cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
_apiFactory.Dispose();
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -142,7 +142,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenInvalidTotpCode_ShouldReturnForbidden()
|
||||
public async Task ExecuteAsync_WhenInvalidTotpCode_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateUserWithTotp();
|
||||
@@ -198,7 +198,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecover_ShouldReturnForbidden()
|
||||
public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecover_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateUserWithoutTotp();
|
||||
@@ -229,7 +229,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecoverWithoutCode_ShouldReturnForbidden()
|
||||
public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecoverWithoutCode_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
// Setup user without TOTP
|
||||
@@ -327,6 +327,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("OldPass123!"),
|
||||
TotpSecret = null,
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnForbidden()
|
||||
public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
GetAuthorizationRequest request = new(Guid.NewGuid());
|
||||
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Enums.Authorization;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserPermissionsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldReturnUserPermissions()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
user.Should().NotBeNull("Test user should exist");
|
||||
|
||||
// Add a direct user permission
|
||||
PermissionEntity permission = dbContext.Permissions.First();
|
||||
UserPermissionEntity userPermission = new()
|
||||
{
|
||||
UserId = user!.Id,
|
||||
PermissionId = permission.Id,
|
||||
CreatedBy = user.Id,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
User = user,
|
||||
Permission = permission,
|
||||
};
|
||||
dbContext.UserPermissions.Add(userPermission);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user.Id}/permissions");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<PermissionResponse>? result = JsonSerializer.Deserialize<IEnumerable<PermissionResponse>>(content, _jsonOptions);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result.Should().NotBeEmpty();
|
||||
result!.Should().AllSatisfy(permission =>
|
||||
{
|
||||
permission.Id.Should().NotBe(Guid.Empty);
|
||||
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
user.Should().NotBeNull("Test user should exist");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/permissions");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/auth/users/{user.Id}/permissions");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentUserId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{nonExistentUserId}/permissions");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails["title"].GetString().Should().Be("General.NotFound");
|
||||
problemDetails["detail"].GetString().Should().Be("UsernameDoesNotExist");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/auth/users/{nonExistentUserId}/permissions");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
user.Should().NotBeNull("Test user should exist");
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/permissions", cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
_apiFactory.Dispose();
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Enums.Authorization;
|
||||
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.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserRoleEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldReturnUserRole()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
user.Should().NotBeNull("Test user should exist");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/role");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RoleResponse? result = JsonSerializer.Deserialize<RoleResponse>(content, _jsonOptions);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.Id.Should().NotBe(Guid.Empty);
|
||||
result.RoleName.Should().Be("Admin");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
user.Should().NotBeNull("Test user should exist");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/role");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/auth/users/{user.Id}/role");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentUserId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{nonExistentUserId}/role");
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails["title"].GetString().Should().Be("General.NotFound");
|
||||
problemDetails["detail"].GetString().Should().Be("UsernameDoesNotExist");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/auth/users/{nonExistentUserId}/role");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
user.Should().NotBeNull("Test user should exist");
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/role", cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
_apiFactory.Dispose();
|
||||
}
|
||||
}
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Enums.Authorization;
|
||||
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.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateUserRoleAndPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserRoleAndPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateUserRoleAndPermissionsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldUpdateUserRoleAndPermissions()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// create a non-admin role first
|
||||
RoleEntity editorRole = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "Editor",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
dbContext.Roles.Add(editorRole);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// create test user
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "TestUser",
|
||||
Password = "HashedPassword",
|
||||
UserRole = null,
|
||||
UserPermissions = [],
|
||||
Libraries = [],
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)];
|
||||
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: user.Id,
|
||||
RoleId: editorRole.Id,
|
||||
Permissions: permissions.Select(p => p.Id).ToList()
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{user.Id}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
JsonNode? jsonNode = JsonNode.Parse(content);
|
||||
|
||||
jsonNode.Should().NotBeNull();
|
||||
Guid.Parse(jsonNode!["userId"]!.ToString()).Should().Be(user.Id);
|
||||
jsonNode["role"]!.ToString().Should().Be("Editor");
|
||||
jsonNode["permissions"]!.AsArray().Count.Should().BeGreaterThan(0);
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: Guid.NewGuid(),
|
||||
RoleId: Guid.NewGuid(),
|
||||
Permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{request.UserId}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
|
||||
problemDetails["detail"].GetString().Should().Be("NotAuthorized");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/auth/users/{request.UserId}/role-and-permissions");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTryingToRemoveLastAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// create Editor role
|
||||
RoleEntity editorRole = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
RoleName = "Editor",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
dbContext.Roles.Add(editorRole);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// get the admin user that was created by CreateAuthenticatedAdminClientAsync
|
||||
UserEntity? adminUser = dbContext.Users.FirstOrDefault(u => u.UserRole!.Role.RoleName == "Admin");
|
||||
adminUser.Should().NotBeNull("Admin user should exist");
|
||||
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: adminUser!.Id,
|
||||
RoleId: editorRole.Id,
|
||||
Permissions: []
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{request.UserId}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
problemDetails["title"].GetString().Should().Be("General.Forbidden");
|
||||
problemDetails["detail"].GetString().Should().Be("CannotRemoveLastAdmin");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/auth/users/{request.UserId}/role-and-permissions");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentUserId = Guid.NewGuid();
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: nonExistentUserId,
|
||||
RoleId: Guid.NewGuid(),
|
||||
Permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{nonExistentUserId}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
problemDetails["title"].GetString().Should().Be("General.NotFound");
|
||||
problemDetails["detail"].GetString().Should().Be("UserDoesNotExist");
|
||||
problemDetails["instance"].GetString().Should().Be($"/api/v1/auth/users/{nonExistentUserId}/role-and-permissions");
|
||||
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
UpdateUserRoleAndPermissionsRequest request = new(
|
||||
UserId: Guid.NewGuid(),
|
||||
RoleId: Guid.NewGuid(),
|
||||
Permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
Func<Task> act = async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PutAsJsonAsync($"/api/v1/auth/users/{request.UserId}/role-and-permissions", request, cts.Token);
|
||||
};
|
||||
|
||||
// Assert
|
||||
await act.Should().ThrowAsync<TaskCanceledException>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// clear junction tables first
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// then clear main tables
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
_apiFactory.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user