Removes FluentAssertions library from test projects, due to licensing changes

This commit is contained in:
BinaryAlley committed 2025-02-03 00:31:15 +02:00
1 parent c1100e5398
commit d46bfae4fc
235 files changed
+4468 -4725

No files matched your search

@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Authorization;
@@ -12,7 +11,6 @@ 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;
@@ -63,18 +61,18 @@ public class GetPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiF
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
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 =>
Assert.NotNull(result);
Assert.NotEmpty(result);
foreach (PermissionResponse permission in result!)
{
permission.Id.Should().NotBe(Guid.Empty);
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
});
Assert.NotEqual(Guid.Empty, permission.Id);
Assert.NotEqual(AuthorizationPermission.None, permission.PermissionName);
}
}
[Fact]
@@ -85,18 +83,19 @@ public class GetPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiF
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/permissions");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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/permissions");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/permissions", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -105,15 +104,12 @@ public class GetPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiF
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
cts.Cancel();
await _client.GetAsync("/api/v1/auth/permissions", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
}
/// <summary>
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.DTO.Authentication;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.DataAccess.Core.UoW;
@@ -75,19 +75,19 @@ public class AddRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
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 =>
Assert.NotNull(result);
Assert.Equal("Editor", result!.Role.RoleName);
Assert.Equal(2, result.Permissions.Length);
foreach (PermissionDto permission in result.Permissions)
{
permission.Id.Should().NotBe(Guid.Empty);
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
});
Assert.NotEqual(Guid.Empty, permission.Id);
Assert.NotEqual(AuthorizationPermission.None, permission.PermissionName);
}
}
[Fact]
@@ -104,17 +104,18 @@ public class AddRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/roles", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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/roles");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -130,17 +131,18 @@ public class AddRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/roles", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Conflict);
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
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/auth/roles");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status409Conflict, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.10", problemDetails["type"].GetString());
Assert.Equal("General.Conflict", problemDetails["title"].GetString());
Assert.Equal("RoleAlreadyExists", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -153,15 +155,12 @@ public class AddRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
Permissions: [Guid.NewGuid()]
);
// Act
Func<Task> act = async () =>
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
cts.Cancel();
await _client.PostAsJsonAsync("/api/v1/auth/roles", request, cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
@@ -75,11 +74,11 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/auth/roles/{role.Id}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NoContent);
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
// Verify role was deleted
// verify role was deleted
RoleEntity? deletedRole = await dbContext.Roles.FirstOrDefaultAsync(r => r.Id == role.Id);
deletedRole.Should().BeNull();
Assert.Null(deletedRole);
}
[Fact]
@@ -93,17 +92,18 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/auth/roles/{roleId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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/roles/{roleId}");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/roles/{roleId}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -113,23 +113,24 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
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");
Assert.NotNull(adminRole);
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/auth/roles/{adminRole!.Id}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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/auth/roles/{adminRole!.Id}");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Forbidden", problemDetails["title"].GetString());
Assert.Equal("AdminRoleCannotBeDeleted", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/roles/{adminRole!.Id}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -142,17 +143,18 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/auth/roles/{nonExistentRoleId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
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/auth/roles/{nonExistentRoleId}");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("RoleNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/roles/{nonExistentRoleId}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -162,15 +164,13 @@ public class DeleteRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using CancellationTokenSource cts = new();
Guid roleId = Guid.NewGuid();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.DeleteAsync($"/api/v1/auth/roles/{roleId}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.DTO.Authentication;
using Lumina.Contracts.Responses.Authorization;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Enums.Authorization;
@@ -62,27 +62,27 @@ public class GetRolePermissionsEndpointTests : IClassFixture<AuthenticatedLumina
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
RoleEntity? role = dbContext.Roles.FirstOrDefault();
role.Should().NotBeNull("Admin role should exist");
Assert.NotNull(role);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/roles/{role!.Id}/permissions");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
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 =>
Assert.NotNull(result);
Assert.Equal(role.Id, result!.Role.Id);
Assert.Equal("Admin", result.Role.RoleName);
Assert.NotEmpty(result.Permissions);
foreach (PermissionDto permission in result.Permissions)
{
permission.Id.Should().NotBe(Guid.Empty);
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
});
Assert.NotEqual(Guid.Empty, permission.Id);
Assert.NotEqual(AuthorizationPermission.None, permission.PermissionName);
}
}
[Fact]
@@ -93,23 +93,24 @@ public class GetRolePermissionsEndpointTests : IClassFixture<AuthenticatedLumina
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
RoleEntity? role = dbContext.Roles.FirstOrDefault();
role.Should().NotBeNull("Admin role should exist");
Assert.NotNull(role);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/roles/{role!.Id}/permissions");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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/roles/{role.Id}/permissions");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/roles/{role.Id}/permissions", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -120,17 +121,18 @@ public class GetRolePermissionsEndpointTests : IClassFixture<AuthenticatedLumina
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/roles/{invalidRoleId}/permissions");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
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/auth/roles/{invalidRoleId}/permissions");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("RoleNotFound", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/roles/{invalidRoleId}/permissions", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -141,17 +143,14 @@ public class GetRolePermissionsEndpointTests : IClassFixture<AuthenticatedLumina
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
RoleEntity? role = dbContext.Roles.FirstOrDefault();
role.Should().NotBeNull("Admin role should exist");
Assert.NotNull(role);
// Act
Func<Task> act = async () =>
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/auth/roles/{role!.Id}/permissions", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Authorization;
@@ -61,14 +60,14 @@ public class GetRolesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
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 =>
Assert.NotNull(result);
Assert.NotEmpty(result);
Assert.Contains(result, role =>
role.Id != Guid.Empty &&
role.RoleName == "Admin"
);
@@ -84,17 +83,18 @@ public class GetRolesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/roles");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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/roles");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -103,15 +103,12 @@ public class GetRolesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
cts.Cancel();
await _client.GetAsync("/api/v1/auth/roles", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
}
/// <summary>
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.DTO.Authentication;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.DataAccess.Core.UoW;
@@ -86,20 +86,20 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
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 =>
Assert.NotNull(result);
Assert.Equal(role.Id, result!.Role.Id);
Assert.Equal("UpdatedRole", result.Role.RoleName);
Assert.Equal(2, result.Permissions.Length);
foreach (PermissionDto permission in result.Permissions)
{
permission.Id.Should().NotBe(Guid.Empty);
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
});
Assert.NotEqual(Guid.Empty, permission.Id);
Assert.NotEqual(AuthorizationPermission.None, permission.PermissionName);
}
}
[Fact]
@@ -117,17 +117,18 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/roles", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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/roles");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -145,17 +146,18 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/roles", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
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/auth/roles");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("RoleNotFound", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -169,15 +171,12 @@ public class UpdateRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
Permissions: [Guid.NewGuid()]
);
// Act
Func<Task> act = async () =>
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
cts.Cancel();
await _client.PutAsJsonAsync($"/api/v1/auth/roles", request, cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
@@ -71,12 +70,12 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
// Assert
string content = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<DirectoryResponse>? directories = JsonSerializer.Deserialize<List<DirectoryResponse>>(content, _jsonOptions);
directories.Should().NotBeNull();
directories!.Should().BeEmpty();
Assert.NotNull(directories);
Assert.Empty(directories);
}
finally
{
@@ -101,21 +100,21 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<DirectoryResponse>? directories = JsonSerializer.Deserialize<List<DirectoryResponse>>(content, _jsonOptions);
directories.Should().NotBeNull();
directories!.Should().NotBeEmpty();
Assert.NotNull(directories);
Assert.NotNull(directories);
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
DirectoryResponse firstDirectory = directories!.First();
firstDirectory.Name.Should().Be((s_isUnix ? "." : string.Empty) + "NestedDirectory_2");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "NestedDirectory_2" + System.IO.Path.DirectorySeparatorChar));
directories!.Count.Should().Be(1); // only directories
Assert.Equal((s_isUnix ? "." : string.Empty) + "NestedDirectory_2", directories!.First().Name);
Assert.Equal(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "NestedDirectory_2" + System.IO.Path.DirectorySeparatorChar), directories.First().Path);
Assert.Single(directories); // only directories
}
finally
{
@@ -135,17 +134,18 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directories");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("General.Failure", problemDetails["title"].GetString());
Assert.Equal("/api/v1/directories/get-directories", problemDetails["instance"].GetString());
Assert.Equal("UnauthorizedAccess", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -160,20 +160,23 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directories");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/directories/get-directories", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -185,11 +188,11 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
bool includeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token)
);
Assert.Null(exception);
}
[Fact]
@@ -201,15 +204,12 @@ public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiF
bool includeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -67,18 +66,18 @@ public class GetDrivesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactor
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? drives = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
drives.Should().NotBeNull();
drives.Should().NotBeEmpty();
Assert.NotNull(drives);
Assert.NotEmpty(drives);
FileSystemTreeNodeResponse firstDrive = drives!.First();
firstDrive.Name.Should().Be(s_isUnix ? "/" : "C:\\");
firstDrive.Path.Should().Be(s_isUnix ? "/" : "C:\\");
firstDrive.ItemType.Should().Be(FileSystemItemType.Root);
drives!.Count.Should().BeGreaterThanOrEqualTo(1);
Assert.Equal(s_isUnix ? "/" : "C:\\", firstDrive.Name);
Assert.Equal(s_isUnix ? "/" : "C:\\", firstDrive.Path);
Assert.Equal(FileSystemItemType.Root, firstDrive.ItemType);
Assert.True(drives.Count >= 1);
}
}
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -55,11 +54,11 @@ public class GetTypeEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
HttpResponseMessage response = await _client.GetAsync("/api/v1/file-system/get-type");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
FileSystemTypeResponse? result = JsonSerializer.Deserialize<FileSystemTypeResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.PlatformType.Should().BeOneOf(PlatformType.Unix, PlatformType.Windows);
Assert.NotNull(result);
Assert.True(result!.PlatformType == PlatformType.Unix || result.PlatformType == PlatformType.Windows);
}
[Fact]
@@ -70,8 +69,8 @@ public class GetTypeEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
HttpResponseMessage response2 = await _client.GetAsync("/api/v1/file-system/get-type");
// Assert
response1.StatusCode.Should().Be(HttpStatusCode.OK);
response2.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
string content1 = await response1.Content.ReadAsStringAsync();
string content2 = await response2.Content.ReadAsStringAsync();
@@ -79,9 +78,9 @@ public class GetTypeEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
FileSystemTypeResponse? result1 = JsonSerializer.Deserialize<FileSystemTypeResponse>(content1, _jsonOptions);
FileSystemTypeResponse? result2 = JsonSerializer.Deserialize<FileSystemTypeResponse>(content2, _jsonOptions);
result1.Should().NotBeNull();
result2.Should().NotBeNull();
result1.Should().BeEquivalentTo(result2);
Assert.NotNull(result1);
Assert.NotNull(result2);
Assert.Equal(result1.PlatformType, result2.PlatformType);
}
[Fact]
@@ -90,11 +89,11 @@ public class GetTypeEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// Arrange
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync("/api/v1/file-system/get-type", cts.Token);
// Assert
await act.Should().NotThrowAsync();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync("/api/v1/file-system/get-type", cts.Token)
);
Assert.Null(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
@@ -68,21 +67,21 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<FileResponse>? files = JsonSerializer.Deserialize<List<FileResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
files!.Should().NotBeEmpty();
Assert.NotNull(files);
Assert.NotEmpty(files);
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be("TestFile_2.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
files!.Count.Should().Be(1); // only files
Assert.Equal("TestFile_2.txt", firstDirectory.Name);
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), firstDirectory.Path);
Assert.Single(files); // only files
}
finally
{
@@ -106,15 +105,15 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<FileResponse>? files = JsonSerializer.Deserialize<List<FileResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
Assert.NotNull(files);
FileResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be("TestFile_2.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
Assert.Equal("TestFile_2.txt", firstDirectory.Name);
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), firstDirectory.Path);
}
finally
{
@@ -138,23 +137,24 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<FileResponse>? files = JsonSerializer.Deserialize<List<FileResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
files!.Should().NotBeEmpty();
Assert.NotNull(files);
Assert.NotEmpty(files);
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be((s_isUnix ? "." : string.Empty) + "TestFile_1.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "TestFile_1.txt"));
Assert.Equal((s_isUnix ? "." : string.Empty) + "TestFile_1.txt", firstDirectory.Name);
Assert.Equal(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "TestFile_1.txt"), firstDirectory.Path);
FileResponse secondDirectory = files!.Last();
secondDirectory.Name.Should().Be("TestFile_2.txt");
secondDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
files!.Count.Should().Be(2);
Assert.Equal("TestFile_2.txt", secondDirectory.Name);
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), secondDirectory.Path);
Assert.Equal(2, files.Count);
}
finally
{
@@ -174,17 +174,18 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-files");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("General.Failure", problemDetails["title"].GetString());
Assert.Equal("/api/v1/files/get-files", problemDetails["instance"].GetString());
Assert.Equal("UnauthorizedAccess", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -199,20 +200,23 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-files");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/files/get-files", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -224,11 +228,11 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
bool includeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token)
);
Assert.Null(exception);
}
[Fact]
@@ -240,15 +244,13 @@ public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
bool includeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
@@ -68,21 +67,21 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? files = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
files!.Should().NotBeEmpty();
Assert.NotNull(files);
Assert.NotEmpty(files);
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileSystemTreeNodeResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be("TestFile_2.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
files!.Count.Should().Be(1); // only files
Assert.Equal("TestFile_2.txt", firstDirectory.Name);
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), firstDirectory.Path);
Assert.Single(files); // only files
}
finally
{
@@ -106,16 +105,16 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? files = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
Assert.NotNull(files);
FileSystemTreeNodeResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be("TestFile_2.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
Assert.Equal("TestFile_2.txt", firstDirectory.Name);
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), firstDirectory.Path);
}
finally
{
@@ -139,23 +138,24 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? files = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
files!.Should().NotBeEmpty();
Assert.NotNull(files);
Assert.NotEmpty(files);
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileSystemTreeNodeResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be((s_isUnix ? "." : string.Empty) + "TestFile_1.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "TestFile_1.txt"));
Assert.Equal((s_isUnix ? "." : string.Empty) + "TestFile_1.txt", firstDirectory.Name);
Assert.Equal(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "TestFile_1.txt"), firstDirectory.Path);
FileSystemTreeNodeResponse secondDirectory = files!.Last();
secondDirectory.Name.Should().Be("TestFile_2.txt");
secondDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
files!.Count.Should().Be(2);
Assert.Equal("TestFile_2.txt", secondDirectory.Name);
Assert.Equal(System.IO.Path.Combine(testPath, "TestFile_2.txt"), secondDirectory.Path);
Assert.Equal(2, files.Count);
}
finally
{
@@ -174,17 +174,18 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-tree-files");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("General.Failure", problemDetails["title"].GetString());
Assert.Equal("/api/v1/files/get-tree-files", problemDetails["instance"].GetString());
Assert.Equal("UnauthorizedAccess", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -199,20 +200,23 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-tree-files");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/files/get-tree-files", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -224,11 +228,11 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
bool includeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token)
);
Assert.Null(exception);
}
[Fact]
@@ -240,15 +244,13 @@ public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
bool includeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -59,11 +58,11 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(tempPath)}&includeHiddenElements=false");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PathExistsResponse? result = JsonSerializer.Deserialize<PathExistsResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Exists.Should().BeTrue();
Assert.NotNull(result);
Assert.True(result!.Exists);
}
[Fact]
@@ -76,11 +75,11 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(nonExistingPath)}&includeHiddenElements=false");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PathExistsResponse? result = JsonSerializer.Deserialize<PathExistsResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Exists.Should().BeFalse();
Assert.NotNull(result);
Assert.False(result!.Exists);
}
[Fact]
@@ -93,20 +92,22 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=false");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/check-path-exists");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/path/check-path-exists", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -119,11 +120,11 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(invalidPath)}&includeHiddenElements=false");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PathExistsResponse? result = JsonSerializer.Deserialize<PathExistsResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Exists.Should().BeFalse();
Assert.NotNull(result);
Assert.False(result!.Exists);
}
[Fact]
@@ -134,15 +135,13 @@ public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApi
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/path/check-path-exists?path={encodedPath}&includeHiddenElements=false", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -63,11 +62,11 @@ public class CombinePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PathSegmentResponse? result = JsonSerializer.Deserialize<PathSegmentResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Path.Should().Be(expectedPath);
Assert.NotNull(result);
Assert.Equal(expectedPath, result!.Path);
}
[Fact]
@@ -81,20 +80,23 @@ public class CombinePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/combine");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/path/combine", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -105,11 +107,11 @@ public class CombinePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
string newPath = "documents";
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token)
);
Assert.Null(exception);
}
[Fact]
@@ -120,15 +122,13 @@ public class CombinePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
string newPath = "testFile.txt";
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -63,11 +62,11 @@ public class GetPathParentEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
IEnumerable<PathSegmentResponse>? result = JsonSerializer.Deserialize<IEnumerable<PathSegmentResponse>>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Should().NotBeEmpty();
Assert.NotNull(result);
Assert.NotEmpty(result);
List<string> hierarchy = [];
string path = System.IO.Path.GetDirectoryName(testPath)!;
@@ -84,7 +83,7 @@ public class GetPathParentEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
}
hierarchy.Reverse();
result!.Select(r => r.Path).Should().BeEquivalentTo(hierarchy, options => options.WithStrictOrdering());
Assert.Equal(hierarchy, result.Select(r => r.Path));
}
[Fact]
@@ -98,17 +97,18 @@ public class GetPathParentEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-parent");
problemDetails["detail"].GetString().Should().Be("CannotNavigateUp");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("General.Failure", problemDetails["title"].GetString());
Assert.Equal("/api/v1/path/get-path-parent", problemDetails["instance"].GetString());
Assert.Equal("CannotNavigateUp", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -122,20 +122,22 @@ public class GetPathParentEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-parent");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/path/get-path-parent", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("InvalidPath", errors["General.Validation"]);
}
[Fact]
@@ -149,20 +151,23 @@ public class GetPathParentEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-parent");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/path/get-path-parent", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -173,11 +178,11 @@ public class GetPathParentEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}", cts.Token)
);
Assert.Null(exception);
}
[Fact]
@@ -188,15 +193,13 @@ public class GetPathParentEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -8,7 +7,6 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
@@ -61,11 +59,12 @@ public class GetPathRootEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PathSegmentResponse? result = JsonSerializer.Deserialize<PathSegmentResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Path.Should().NotBeNullOrEmpty();
Assert.NotNull(result);
Assert.NotNull(result!.Path);
Assert.NotEmpty(result.Path);
}
[Fact]
@@ -79,20 +78,23 @@ public class GetPathRootEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-root");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/path/get-path-root", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("InvalidPath", errors["General.Validation"]);
}
[Fact]
@@ -106,20 +108,23 @@ public class GetPathRootEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-root");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/path/get-path-root", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -130,11 +135,11 @@ public class GetPathRootEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}", cts.Token)
);
Assert.Null(exception);
}
[Fact]
@@ -145,15 +150,13 @@ public class GetPathRootEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System;
@@ -54,11 +53,11 @@ public class GetPathSeparatorEndpointTests : IClassFixture<AuthenticatedLuminaAp
HttpResponseMessage response = await _client.GetAsync("/api/v1/path/get-path-separator");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PathSeparatorResponse? result = JsonSerializer.Deserialize<PathSeparatorResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Separator.Should().BeOneOf("/", "\\");
Assert.NotNull(result);
Assert.True(result!.Separator == "/" || result.Separator == "\\");
}
[Fact]
@@ -69,8 +68,8 @@ public class GetPathSeparatorEndpointTests : IClassFixture<AuthenticatedLuminaAp
HttpResponseMessage response2 = await _client.GetAsync("/api/v1/path/get-path-separator");
// Assert
response1.StatusCode.Should().Be(HttpStatusCode.OK);
response2.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
string content1 = await response1.Content.ReadAsStringAsync();
string content2 = await response2.Content.ReadAsStringAsync();
@@ -78,9 +77,9 @@ public class GetPathSeparatorEndpointTests : IClassFixture<AuthenticatedLuminaAp
PathSeparatorResponse? result1 = JsonSerializer.Deserialize<PathSeparatorResponse>(content1, _jsonOptions);
PathSeparatorResponse? result2 = JsonSerializer.Deserialize<PathSeparatorResponse>(content2, _jsonOptions);
result1.Should().NotBeNull();
result2.Should().NotBeNull();
result1.Should().BeEquivalentTo(result2);
Assert.NotNull(result1);
Assert.NotNull(result2);
Assert.Equal(result1, result2);
}
[Fact]
@@ -89,11 +88,11 @@ public class GetPathSeparatorEndpointTests : IClassFixture<AuthenticatedLuminaAp
// Arrange
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync("/api/v1/path/get-path-separator", cts.Token);
// Assert
await act.Should().NotThrowAsync();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync("/api/v1/path/get-path-separator", cts.Token)
);
Assert.Null(exception);
}
[Fact]
@@ -102,15 +101,13 @@ public class GetPathSeparatorEndpointTests : IClassFixture<AuthenticatedLuminaAp
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync("/api/v1/path/get-path-separator", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -61,12 +60,15 @@ public class SplitPathEndpointTests : IClassFixture<AuthenticatedLuminaApiFactor
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(testPath)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
IEnumerable<PathSegmentResponse>? result = JsonSerializer.Deserialize<IEnumerable<PathSegmentResponse>>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Should().HaveCountGreaterThanOrEqualTo(3);
result!.Select(r => r.Path).Should().Contain(["testFolder", "testFile.txt"]);
Assert.NotNull(result);
Assert.True(result!.Count() >= 3);
IEnumerable<string> paths = result.Select(r => r.Path);
Assert.Contains("testFolder", paths);
Assert.Contains("testFile.txt", paths);
}
[Fact]
@@ -79,20 +81,23 @@ public class SplitPathEndpointTests : IClassFixture<AuthenticatedLuminaApiFactor
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(path)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/split");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/path/split", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -105,20 +110,23 @@ public class SplitPathEndpointTests : IClassFixture<AuthenticatedLuminaApiFactor
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(path)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/split");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/path/split", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("InvalidPath", errors["General.Validation"]);
}
[Fact]
@@ -129,15 +137,13 @@ public class SplitPathEndpointTests : IClassFixture<AuthenticatedLuminaApiFactor
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/path/split?path={encodedPath}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System;
@@ -58,11 +57,11 @@ public class ValidatePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/validate?path={Uri.EscapeDataString(testPath)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PathValidResponse? result = JsonSerializer.Deserialize<PathValidResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsValid.Should().BeTrue();
Assert.NotNull(result);
Assert.True(result!.IsValid);
}
[Fact]
@@ -75,11 +74,11 @@ public class ValidatePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/validate?path={Uri.EscapeDataString(invalidPath)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PathValidResponse? result = JsonSerializer.Deserialize<PathValidResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsValid.Should().BeFalse();
Assert.NotNull(result);
Assert.False(result!.IsValid);
}
[Fact]
@@ -92,11 +91,11 @@ public class ValidatePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/validate?path={Uri.EscapeDataString(path)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PathValidResponse? result = JsonSerializer.Deserialize<PathValidResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsValid.Should().BeFalse();
Assert.NotNull(result);
Assert.False(result!.IsValid);
}
[Fact]
@@ -107,15 +106,13 @@ public class ValidatePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/path/validate?path={encodedPath}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
using Microsoft.AspNetCore.Http;
@@ -62,10 +61,10 @@ public class GetThumbnailEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
response.Content.Headers.ContentType!.MediaType.Should().Be("image/jpeg");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("image/jpeg", response.Content.Headers.ContentType!.MediaType);
byte[] content = await response.Content.ReadAsByteArrayAsync();
content.Should().NotBeEmpty();
Assert.NotEmpty(content);
}
[Fact]
@@ -79,17 +78,18 @@ public class GetThumbnailEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/thumbnails/get-thumbnail");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("General.Failure", problemDetails["title"].GetString());
Assert.Equal("/api/v1/thumbnails/get-thumbnail", problemDetails["instance"].GetString());
Assert.Equal("UnauthorizedAccess", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -103,20 +103,23 @@ public class GetThumbnailEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/thumbnails/get-thumbnail");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/thumbnails/get-thumbnail", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PathCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -129,20 +132,23 @@ public class GetThumbnailEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={invalidQuality}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/thumbnails/get-thumbnail");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/thumbnails/get-thumbnail", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["ImageQualityMustBeBetweenZeroAndOneHundred"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("ImageQualityMustBeBetweenZeroAndOneHundred", errors["General.Validation"]);
}
[Fact]
@@ -152,15 +158,13 @@ public class GetThumbnailEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
int quality = 80;
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,15 +1,12 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
@@ -63,13 +60,13 @@ public class CheckInitializationEndpointTests : IClassFixture<AuthenticatedLumin
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
InitializationResponse? result = JsonSerializer.Deserialize<InitializationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsInitialized.Should().BeFalse();
Assert.NotNull(result);
Assert.False(result!.IsInitialized);
}
[Fact]
@@ -83,13 +80,13 @@ public class CheckInitializationEndpointTests : IClassFixture<AuthenticatedLumin
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
InitializationResponse? result = JsonSerializer.Deserialize<InitializationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsInitialized.Should().BeTrue();
Assert.NotNull(result);
Assert.True(result!.IsInitialized);
}
[Fact]
@@ -98,15 +95,13 @@ public class CheckInitializationEndpointTests : IClassFixture<AuthenticatedLumin
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.GetAsync("/api/v1/initialization", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
private async Task<UserEntity> CreateTestUser()
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
@@ -76,18 +75,19 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Created);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(_testUsername);
result.Id.Should().NotBe(Guid.Empty);
result.TotpSecret.Should().NotBeNullOrEmpty();
result.TotpSecret.Should().StartWith("data:image/png;base64,");
Assert.NotNull(result);
Assert.Equal(_testUsername, result!.Username);
Assert.NotEqual(Guid.Empty, result.Id);
Assert.NotNull(result.TotpSecret);
Assert.NotEmpty(result.TotpSecret);
Assert.StartsWith("data:image/png;base64,", result.TotpSecret);
response.Headers.Location.Should().NotBeNull();
response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}");
Assert.NotNull(response.Headers.Location);
Assert.Equal($"http://localhost/api/v1/users/{result.Id}", response.Headers.Location.ToString());
// verify default permissions, roles, and role permissions are set
await VerifyDefaultSetup(result.Id);
@@ -109,17 +109,17 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Created);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(_testUsername);
result.Id.Should().NotBe(Guid.Empty);
result.TotpSecret.Should().BeNull();
Assert.NotNull(result);
Assert.Equal(_testUsername, result!.Username);
Assert.NotEqual(Guid.Empty, result.Id);
Assert.Null(result.TotpSecret);
response.Headers.Location.Should().NotBeNull();
response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}");
Assert.NotNull(response.Headers.Location);
Assert.Equal($"http://localhost/api/v1/users/{result.Id}", response.Headers.Location.ToString());
// verify default permissions, roles, and role permissions are set
await VerifyDefaultSetup(result.Id);
@@ -141,17 +141,18 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Conflict);
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
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("AdminAccountAlreadyCreated");
problemDetails["instance"].GetString().Should().Be("/api/v1/initialization");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status409Conflict, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.10", problemDetails["type"].GetString());
Assert.Equal("General.Conflict", problemDetails["title"].GetString());
Assert.Equal("AdminAccountAlreadyCreated", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/initialization", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -164,14 +165,17 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
Assert.NotNull(problemDetails);
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation")
.WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("UsernameCannotBeEmpty", errors["General.Validation"]);
Assert.Contains("PasswordCannotBeEmpty", errors["General.Validation"]);
Assert.Contains("PasswordConfirmCannotBeEmpty", errors["General.Validation"]);
}
private async Task VerifyDefaultSetup(Guid userId)
@@ -182,25 +186,25 @@ public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaAp
// TODO: update list when defaults change
// verify default permissions
List<PermissionEntity> permissions = await dbContext.Permissions.ToListAsync();
permissions.Should().Contain(p => p.PermissionName == AuthorizationPermission.CanViewUsers);
permissions.Should().Contain(p => p.PermissionName == AuthorizationPermission.CanDeleteUsers);
permissions.Should().Contain(p => p.PermissionName == AuthorizationPermission.CanRegisterUsers);
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanViewUsers);
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanDeleteUsers);
Assert.Contains(permissions, p => p.PermissionName == AuthorizationPermission.CanRegisterUsers);
// verify default roles
List<RoleEntity> roles = await dbContext.Roles.ToListAsync();
RoleEntity? adminRole = roles.FirstOrDefault(r => r.RoleName == "Admin");
adminRole.Should().NotBeNull();
Assert.NotNull(adminRole);
// verify admin role permissions
List<RolePermissionEntity> rolePermissions = await dbContext.RolePermissions
.Where(rp => rp.RoleId == adminRole!.Id)
.ToListAsync();
rolePermissions.Should().NotBeEmpty();
rolePermissions.Should().Contain(rp => permissions.Any(p => p.Id == rp.PermissionId));
Assert.NotEmpty(rolePermissions);
Assert.Contains(rolePermissions, rp => permissions.Any(p => p.Id == rp.PermissionId));
// verify user has admin role
UserRoleEntity? userRole = await dbContext.UserRoles.FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == adminRole!.Id);
userRole.Should().NotBeNull();
Assert.NotNull(userRole);
}
private async Task<UserEntity> CreateTestUser()
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
@@ -71,12 +70,12 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
// Assert
string content = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ChangePasswordResponse? result = JsonSerializer.Deserialize<ChangePasswordResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsPasswordChanged.Should().BeTrue();
Assert.NotNull(result);
Assert.True(result!.IsPasswordChanged);
}
[Fact]
@@ -94,20 +93,23 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
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.Status422UnprocessableEntity);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/change-password", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("PasswordsNotMatch");
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PasswordsNotMatch", errors["General.Validation"]);
}
[Fact]
@@ -125,17 +127,18 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
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/change-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("UsernameDoesNotExist", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/change-password", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -153,17 +156,18 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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.Failure");
problemDetails["detail"].GetString().Should().Be("InvalidCurrentPassword");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Failure", problemDetails["title"].GetString());
Assert.Equal("InvalidCurrentPassword", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/change-password", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -176,20 +180,26 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
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.Status422UnprocessableEntity);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/change-password", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "CurrentPasswordCannotBeEmpty", "NewPasswordCannotBeEmpty", "NewPasswordConfirmCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("UsernameCannotBeEmpty", errors["General.Validation"]);
Assert.Contains("CurrentPasswordCannotBeEmpty", errors["General.Validation"]);
Assert.Contains("NewPasswordCannotBeEmpty", errors["General.Validation"]);
Assert.Contains("NewPasswordConfirmCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -204,15 +214,13 @@ public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiF
);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.PostAsJsonAsync("/api/v1/auth/change-password", request, cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.UsersManagement.Users;
@@ -61,19 +60,20 @@ public class GetUsersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
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 =>
Assert.NotNull(result);
Assert.NotEmpty(result);
foreach (UserResponse user in result!)
{
user.Id.Should().NotBe(Guid.Empty);
user.Username.Should().NotBeNullOrEmpty();
user.CreatedOnUtc.Should().NotBe(default);
});
Assert.NotEqual(Guid.Empty, user.Id);
Assert.NotNull(user.Username);
Assert.NotEmpty(user.Username);
Assert.NotEqual(default, user.CreatedOnUtc);
}
}
[Fact]
@@ -86,17 +86,18 @@ public class GetUsersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/users");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/users", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -105,15 +106,13 @@ public class GetUsersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.GetAsync("/api/v1/auth/users", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Contracts.Requests.Authentication;
@@ -83,15 +82,16 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(user.Username);
result.UsesTotp.Should().BeFalse();
result.Token.Should().NotBeNullOrEmpty();
Assert.NotNull(result);
Assert.Equal(user.Username, result!.Username);
Assert.False(result.UsesTotp);
Assert.NotNull(result.Token);
Assert.NotEmpty(result.Token);
}
[Fact]
@@ -114,15 +114,16 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(user.Username);
result.UsesTotp.Should().BeTrue();
result.Token.Should().NotBeNullOrEmpty();
Assert.NotNull(result);
Assert.Equal(user.Username, result!.Username);
Assert.True(result.UsesTotp);
Assert.NotNull(result.Token);
Assert.NotEmpty(result.Token);
}
[Fact]
@@ -140,14 +141,15 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(user.Username);
result.Token.Should().NotBeNullOrEmpty();
Assert.NotNull(result);
Assert.Equal(user.Username, result!.Username);
Assert.NotNull(result.Token);
Assert.NotEmpty(result.Token);
}
[Fact]
@@ -164,17 +166,18 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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.Failure");
problemDetails["detail"].GetString().Should().Be("TempPasswordExpired");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Failure", problemDetails["title"].GetString());
Assert.Equal("TempPasswordExpired", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/login", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -191,17 +194,18 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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.Failure");
problemDetails["detail"].GetString().Should().Be("InvalidUsernameOrPassword");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Failure", problemDetails["title"].GetString());
Assert.Equal("InvalidUsernameOrPassword", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/login", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -219,20 +223,23 @@ public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>,
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
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.Status422UnprocessableEntity);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/login", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("InvalidTotpCode", errors["General.Validation"]);
}
private async Task<UserEntity> CreateTestUser()
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Contracts.Requests.Authentication;
@@ -92,13 +91,13 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
RecoverPasswordResponse? result = JsonSerializer.Deserialize<RecoverPasswordResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsPasswordReset.Should().BeTrue();
Assert.NotNull(result);
Assert.True(result!.IsPasswordReset);
// Create a new context to get fresh data
using IServiceScope verificationScope = _apiFactory.Services.CreateScope();
@@ -110,9 +109,9 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Username == user.Username);
updatedUser.Should().NotBeNull();
updatedUser!.TempPassword.Should().NotBeNull();
updatedUser.TempPasswordCreated.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(5));
Assert.NotNull(updatedUser);
Assert.NotNull(updatedUser!.TempPassword);
Assert.True(Math.Abs((updatedUser.TempPasswordCreated - DateTime.UtcNow)!.Value.TotalSeconds) < 5);
}
[Fact]
@@ -128,17 +127,18 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
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/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("UsernameDoesNotExist", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -155,20 +155,23 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
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.Status422UnprocessableEntity);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("InvalidTotpCode", errors["General.Validation"]);
}
[Fact]
@@ -181,20 +184,24 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
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.Status422UnprocessableEntity);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "TotpCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("UsernameCannotBeEmpty", errors["General.Validation"]);
Assert.Contains("TotpCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -212,20 +219,23 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
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.Status422UnprocessableEntity);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("InvalidTotpCode", errors["General.Validation"]);
}
[Fact]
@@ -260,20 +270,23 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
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.Status422UnprocessableEntity);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["TotpCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("TotpCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -286,15 +299,13 @@ public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApi
);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request, cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
private async Task<UserEntity> CreateUserWithTotp()
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
@@ -72,17 +71,17 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Created);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(_testUsername);
result.Id.Should().NotBe(Guid.Empty);
result.TotpSecret.Should().BeNull();
Assert.NotNull(result);
Assert.Equal(_testUsername, result!.Username);
Assert.NotEqual(Guid.Empty, result.Id);
Assert.Null(result.TotpSecret);
response.Headers.Location.Should().NotBeNull();
response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}");
Assert.NotNull(response.Headers.Location);
Assert.Equal($"http://localhost/api/v1/users/{result.Id}", response.Headers.Location.ToString());
}
[Fact]
@@ -100,15 +99,16 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Created);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(_testUsername);
result.Id.Should().NotBe(Guid.Empty);
result.TotpSecret.Should().NotBeNullOrEmpty();
result.TotpSecret.Should().StartWith("data:image/png;base64,");
Assert.NotNull(result);
Assert.Equal(_testUsername, result!.Username);
Assert.NotEqual(Guid.Empty, result.Id);
Assert.NotNull(result.TotpSecret);
Assert.NotEmpty(result.TotpSecret);
Assert.StartsWith("data:image/png;base64,", result.TotpSecret);
}
[Fact]
@@ -127,14 +127,14 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Conflict);
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
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["title"].GetString().Should().Be("General.Conflict");
problemDetails["detail"].GetString().Should().Be("UsernameAlreadyExists");
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status409Conflict, problemDetails!["status"].GetInt32());
Assert.Equal("General.Conflict", problemDetails["title"].GetString());
Assert.Equal("UsernameAlreadyExists", problemDetails["detail"].GetString());
}
[Fact]
@@ -152,13 +152,15 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
Assert.NotNull(problemDetails);
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("PasswordsNotMatch");
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("PasswordsNotMatch", errors["General.Validation"]);
}
[Fact]
@@ -171,14 +173,17 @@ public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
Assert.NotNull(problemDetails);
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation")
.WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("UsernameCannotBeEmpty", errors["General.Validation"]);
Assert.Contains("PasswordCannotBeEmpty", errors["General.Validation"]);
Assert.Contains("PasswordConfirmCannotBeEmpty", errors["General.Validation"]);
}
private async Task<UserEntity> CreateTestUser()
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authorization;
@@ -86,15 +85,15 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
AuthorizationResponse? result = JsonSerializer.Deserialize<AuthorizationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.UserId.Should().Be(user.Id);
result.Role.Should().Contain("Admin");
result.Permissions.Should().Contain(AuthorizationPermission.CanViewUsers);
Assert.NotNull(result);
Assert.Equal(user.Id, result!.UserId);
Assert.Contains("Admin", result.Role);
Assert.Contains(AuthorizationPermission.CanViewUsers, result.Permissions);
}
[Fact]
@@ -107,17 +106,18 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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/get-authorization");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/get-authorization", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -130,20 +130,23 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
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.Status422UnprocessableEntity);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/get-authorization");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/auth/get-authorization", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("UserIdCannotBeEmpty");
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains("UserIdCannotBeEmpty", errors["General.Validation"]);
}
[Fact]
@@ -153,15 +156,13 @@ public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaAp
GetAuthorizationRequest request = new(Guid.NewGuid());
CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
private static async Task<UserEntity> AddRolesAndPermissionsToUser(UserEntity existingUser, LuminaDbContext dbContext)
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.Authorization;
@@ -62,7 +61,7 @@ public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLumina
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault();
user.Should().NotBeNull("Test user should exist");
Assert.NotNull(user);
// Add a direct user permission
PermissionEntity permission = dbContext.Permissions.First();
@@ -83,18 +82,18 @@ public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLumina
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
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 =>
Assert.NotNull(result);
Assert.NotEmpty(result);
foreach (PermissionResponse perm in result!)
{
permission.Id.Should().NotBe(Guid.Empty);
permission.PermissionName.Should().NotBe(AuthorizationPermission.None);
});
Assert.NotEqual(Guid.Empty, perm.Id);
Assert.NotEqual(AuthorizationPermission.None, perm.PermissionName);
}
}
[Fact]
@@ -105,23 +104,24 @@ public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLumina
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault();
user.Should().NotBeNull("Test user should exist");
Assert.NotNull(user);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/permissions");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/users/{user!.Id}/permissions", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -134,17 +134,18 @@ public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLumina
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{nonExistentUserId}/permissions");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
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();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("UsernameDoesNotExist", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/users/{nonExistentUserId}/permissions", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -155,17 +156,15 @@ public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLumina
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault();
user.Should().NotBeNull("Test user should exist");
Assert.NotNull(user);
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/permissions", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,10 +1,8 @@
#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;
@@ -62,21 +60,21 @@ public class GetUserRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault();
user.Should().NotBeNull("Test user should exist");
Assert.NotNull(user);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/role");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
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");
Assert.NotNull(result);
Assert.NotEqual(Guid.Empty, result!.Id);
Assert.Equal("Admin", result.RoleName);
}
[Fact]
@@ -87,23 +85,24 @@ public class GetUserRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault();
user.Should().NotBeNull("Test user should exist");
Assert.NotNull(user);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/role");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/users/{user!.Id}/role", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -116,17 +115,18 @@ public class GetUserRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{nonExistentUserId}/role");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
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();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("UsernameDoesNotExist", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/users/{nonExistentUserId}/role", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -137,17 +137,15 @@ public class GetUserRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault();
user.Should().NotBeNull("Test user should exist");
Assert.NotNull(user);
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/role", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,11 +1,8 @@
#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;
@@ -104,15 +101,15 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
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);
Assert.NotNull(jsonNode);
Assert.Equal(user.Id, Guid.Parse(jsonNode!["userId"]!.ToString()));
Assert.Equal("Editor", jsonNode["role"]!.ToString());
Assert.True(jsonNode["permissions"]!.AsArray().Count > 0);
}
@@ -131,17 +128,18 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{request.UserId}/role-and-permissions", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/users/{request.UserId}/role-and-permissions", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -164,8 +162,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
// 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");
Assert.NotNull(adminUser);
UpdateUserRoleAndPermissionsRequest request = new(
UserId: adminUser!.Id,
RoleId: editorRole.Id,
@@ -176,17 +173,18 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{request.UserId}/role-and-permissions", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
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();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Forbidden", problemDetails["title"].GetString());
Assert.Equal("CannotRemoveLastAdmin", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/users/{request.UserId}/role-and-permissions", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -204,17 +202,18 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{nonExistentUserId}/role-and-permissions", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
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();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
Assert.Equal("UserDoesNotExist", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/auth/users/{nonExistentUserId}/role-and-permissions", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
}
[Fact]
@@ -228,15 +227,13 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<Authentic
Permissions: [Guid.NewGuid()]
);
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.PutAsJsonAsync($"/api/v1/auth/users/{request.UserId}/role-and-permissions", request, cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -1,6 +1,10 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Bogus;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Presentation.Api.IntegrationTests.Common.Converters;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.Fixtures;
using Microsoft.AspNetCore.Http;
@@ -14,11 +18,6 @@ using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Lumina.Domain.Common.Errors;
using Bogus;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Converters;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books;
@@ -73,91 +72,97 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// Assert
response.EnsureSuccessStatusCode();
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
response.StatusCode.Should().Be(HttpStatusCode.Created);
bookResponse.Should().NotBeNull();
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.NotNull(bookResponse);
// metadata checks
bookResponse!.Metadata.Title.Should().Be(bookRequest.Metadata!.Title);
bookResponse.Metadata.OriginalTitle.Value.Should().Be(bookRequest.Metadata.OriginalTitle);
bookResponse.Metadata.Description.Value.Should().Be(bookRequest.Metadata.Description);
bookResponse.Metadata.Publisher.Value.Should().Be(bookRequest.Metadata.Publisher);
bookResponse.Metadata.PageCount.Value.Should().Be(bookRequest.Metadata.PageCount);
Assert.Equal(bookRequest.Metadata!.Title, bookResponse!.Metadata.Title);
Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle.Value);
Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description.Value);
Assert.Equal(bookRequest.Metadata.Publisher, bookResponse.Metadata.Publisher.Value);
Assert.Equal(bookRequest.Metadata.PageCount, bookResponse.Metadata.PageCount.Value);
// releaseInfo checks
bookResponse.Metadata.ReleaseInfo.OriginalReleaseDate.Value.Should().Be(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate);
bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear);
bookResponse.Metadata.ReleaseInfo.ReReleaseDate.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.ReReleaseDate);
bookResponse.Metadata.ReleaseInfo.ReReleaseYear.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.ReReleaseYear);
bookResponse.Metadata.ReleaseInfo.ReleaseCountry.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.ReleaseCountry);
bookResponse.Metadata.ReleaseInfo.ReleaseVersion.Value.Should().Be(bookRequest.Metadata.ReleaseInfo.ReleaseVersion);
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate, bookResponse.Metadata.ReleaseInfo.OriginalReleaseDate.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear, bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseDate, bookResponse.Metadata.ReleaseInfo.ReReleaseDate.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseYear, bookResponse.Metadata.ReleaseInfo.ReReleaseYear.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion.Value);
// language checks
bookResponse.Metadata.Language.Value.LanguageCode.Should().Be(bookRequest.Metadata.Language!.LanguageCode);
bookResponse.Metadata.Language.Value.LanguageName.Should().Be(bookRequest.Metadata.Language.LanguageName);
bookResponse.Metadata.Language.Value.NativeName.Value.Should().Be(bookRequest.Metadata.Language.NativeName);
Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language.Value.LanguageCode);
Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.Value.LanguageName);
Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.Value.NativeName.Value);
// original language checks
bookResponse.Metadata.OriginalLanguage.Value.LanguageCode.Should().Be(bookRequest.Metadata.OriginalLanguage!.LanguageCode);
bookResponse.Metadata.OriginalLanguage.Value.LanguageName.Should().Be(bookRequest.Metadata.OriginalLanguage.LanguageName);
bookResponse.Metadata.OriginalLanguage.Value.NativeName.Value.Should().Be(bookRequest.Metadata.OriginalLanguage.NativeName);
Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage.Value.LanguageCode);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.Value.LanguageName);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.Value.NativeName.Value);
// genres checks
bookResponse.Metadata.Genres.Should().HaveCount(bookRequest.Metadata.Genres!.Count);
bookResponse.Metadata.Genres.Select(genre => genre.Name).Should().BeEquivalentTo(bookRequest.Metadata.Genres.Select(genre => genre.Name));
Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres.Count);
Assert.Equal(
bookRequest.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x),
bookResponse.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x));
// tags checks
bookResponse.Metadata.Tags.Should().HaveCount(bookRequest.Metadata.Tags!.Count);
bookResponse.Metadata.Tags.Select(tag => tag.Name).Should().BeEquivalentTo(bookRequest.Metadata.Tags.Select(tag => tag.Name));
Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags.Count);
Assert.Equal(
bookRequest.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x),
bookResponse.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x));
// book specific properties
bookResponse.Format.Value.Should().Be(bookRequest.Format);
bookResponse.Edition.Value.Should().Be(bookRequest.Edition);
bookResponse.VolumeNumber.Value.Should().Be(bookRequest.VolumeNumber);
bookResponse.ASIN.Value.Should().Be(bookRequest.ASIN);
bookResponse.GoodreadsId.Value.Should().Be(bookRequest.GoodreadsId);
bookResponse.LCCN.Value.Should().Be(bookRequest.LCCN);
bookResponse.OCLCNumber.Value.Should().Be(bookRequest.OCLCNumber);
bookResponse.OpenLibraryId.Value.Should().Be(bookRequest.OpenLibraryId);
bookResponse.LibraryThingId.Value.Should().Be(bookRequest.LibraryThingId);
bookResponse.GoogleBooksId.Value.Should().Be(bookRequest.GoogleBooksId);
bookResponse.BarnesAndNobleId.Value.Should().Be(bookRequest.BarnesAndNobleId);
bookResponse.AppleBooksId.Value.Should().Be(bookRequest.AppleBooksId);
Assert.Equal(bookRequest.Format, bookResponse.Format.Value);
Assert.Equal(bookRequest.Edition, bookResponse.Edition.Value);
Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber.Value);
Assert.Equal(bookRequest.ASIN, bookResponse.ASIN.Value);
Assert.Equal(bookRequest.GoodreadsId, bookResponse.GoodreadsId.Value);
Assert.Equal(bookRequest.LCCN, bookResponse.LCCN.Value);
Assert.Equal(bookRequest.OCLCNumber, bookResponse.OCLCNumber.Value);
Assert.Equal(bookRequest.OpenLibraryId, bookResponse.OpenLibraryId.Value);
Assert.Equal(bookRequest.LibraryThingId, bookResponse.LibraryThingId.Value);
Assert.Equal(bookRequest.GoogleBooksId, bookResponse.GoogleBooksId.Value);
Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId.Value);
Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId.Value);
// ISBNs checks
bookResponse.ISBNs.Should().HaveCount(bookRequest.ISBNs!.Count);
bookResponse.ISBNs.Should().HaveCount(bookRequest.ISBNs.Count);
bookResponse.ISBNs.Select(isbn => new { isbn.Value, isbn.Format })
.Should().BeEquivalentTo(bookRequest.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }));
// contributors checks
// TODO: update when contributors are implemented
// bookResponse.Contributors.Should().HaveCount(bookRequest.Contributors.Count);
Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs.Count);
var requestIsbnData = bookRequest.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList();
var responseIsbnData = bookResponse.ISBNs.Select(isbn => new { Value = isbn.Value, Format = isbn.Format }).OrderBy(x => x.Value).ToList();
Assert.Equal(requestIsbnData.Count, responseIsbnData.Count);
for (int i = 0; i < requestIsbnData.Count; i++)
{
Assert.Equal(requestIsbnData[i].Value, responseIsbnData[i].Value);
Assert.Equal(requestIsbnData[i].Format, responseIsbnData[i].Format);
}
// ratings checks
bookResponse.Ratings.Should().HaveCount(bookRequest.Ratings!.Count);
bookResponse.Ratings.Should().HaveCount(bookRequest.Ratings.Count);
bookResponse.Ratings.Select(bookRating => new { Source = bookRating.Source.Value, bookRating.Value, bookRating.MaxValue, VoteCount = bookRating.VoteCount.Value })
.Should().BeEquivalentTo(bookRequest.Ratings.Select(bookRating => new { bookRating.Source, bookRating.Value, bookRating.MaxValue, bookRating.VoteCount }));
Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings.Count);
var requestRatingData = bookRequest.Ratings.Select(r => new { Source = r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList();
var responseRatingData = bookResponse.Ratings.Select(r => new { Source = r.Source.Value, r.Value, r.MaxValue, VoteCount = r.VoteCount.Value }).OrderBy(x => x.Source).ToList();
Assert.Equal(requestRatingData.Count, responseRatingData.Count);
for (int i = 0; i < requestRatingData.Count; i++)
{
Assert.Equal(requestRatingData[i].Source, responseRatingData[i].Source);
Assert.Equal(requestRatingData[i].Value, responseRatingData[i].Value);
Assert.Equal(requestRatingData[i].MaxValue, responseRatingData[i].MaxValue);
Assert.Equal(requestRatingData[i].VoteCount, responseRatingData[i].VoteCount);
}
// series checks
if (bookRequest.Series is not null)
{
bookResponse.Series.Should().NotBeNull();
bookResponse.Series.Value.Metadata.Title.Should().Be(bookRequest.Series.Title);
}
Assert.Equal(bookRequest.Series.Title, bookResponse.Series.Value.Metadata.Title);
else
bookResponse.Series.Value.Should().BeNull();
Assert.Null(bookResponse.Series.Value);
// check Location header
response.Headers.Location.Should().NotBeNull();
Assert.NotNull(response.Headers.Location);
string locationUri = response.Headers.Location!.ToString();
locationUri.Should().EndWith("/api/v1/books/" + bookResponse.Id.Value);
Assert.EndsWith("/api/v1/books/" + bookResponse.Id.Value, locationUri);
// extract ID from Location header
// extract ID from Location header and compare
string idFromHeader = locationUri.Split('/').Last();
// compare with bookResponse id
bookResponse!.Id.ToString().Should().Be(idFromHeader);
Assert.Equal(idFromHeader, bookResponse!.Id.ToString());
}
[Fact]
@@ -1580,21 +1585,24 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, params string[] expectedErrorCodes)
{
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
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.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("General.Validation");
problemDetails["instance"].GetString().Should().Be("/api/v1/books");
problemDetails["detail"].GetString().Should().Be("OneOrMoreValidationErrorsOccurred");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("/api/v1/books", problemDetails["instance"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(expectedErrorCodes);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
}
private async Task AssertCreated(AddBookRequest bookRequest)
@@ -1602,8 +1610,8 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest);
response.EnsureSuccessStatusCode();
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
response.StatusCode.Should().Be(HttpStatusCode.Created);
bookResponse.Should().NotBeNull();
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.NotNull(bookResponse);
}
/// <summary>
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -60,21 +59,22 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Book[]? bookResponse = await response.Content.ReadFromJsonAsync<Book[]>(_jsonOptions);
bookResponse.Should().NotBeNull();
Assert.NotNull(bookResponse);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompletesuccessfuly()
{
// Arrange
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/books", cts.Token);
// Assert
await act.Should().NotThrowAsync();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.GetAsync($"/api/v1/books", cts.Token)
);
Assert.Null(exception);
}
[Fact]
@@ -83,15 +83,13 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel(); // Cancel the token immediately
cts.Cancel();
await _client.GetAsync($"/api/v1/books", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
@@ -24,7 +24,6 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />