adds unit tests to cover 80%
This commit is contained in:
@@ -0,0 +1,212 @@
|
||||
using System.Security.Claims;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ExceptionExtensions;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
using SlpModularCms.Modules.Identity.Controllers;
|
||||
|
||||
namespace SlpModularCms.Modules.Identity.Tests.Controllers;
|
||||
|
||||
public class AuthControllerTests
|
||||
{
|
||||
private readonly IAuthService _authService = Substitute.For<IAuthService>();
|
||||
private readonly JwtSettings _jwtSettings = new()
|
||||
{
|
||||
Secret = "test-secret-key-at-least-32-chars-long!",
|
||||
Issuer = "test",
|
||||
Audience = "test",
|
||||
ExpiryMinutes = 60,
|
||||
RefreshTokenExpiryDays = 7,
|
||||
CookieSameSite = "Strict"
|
||||
};
|
||||
|
||||
private AuthController CreateController(string? refreshTokenCookie = null, bool isAuthenticated = false, string? userId = null)
|
||||
{
|
||||
var options = Options.Create(_jwtSettings);
|
||||
var controller = new AuthController(_authService, options);
|
||||
|
||||
var httpContext = new DefaultHttpContext();
|
||||
|
||||
if (refreshTokenCookie is not null)
|
||||
{
|
||||
var cookiesMock = Substitute.For<IRequestCookieCollection>();
|
||||
cookiesMock["refreshToken"].Returns(refreshTokenCookie);
|
||||
cookiesMock.TryGetValue("refreshToken", out Arg.Any<string?>()).Returns(x =>
|
||||
{
|
||||
x[1] = refreshTokenCookie;
|
||||
return true;
|
||||
});
|
||||
// Use a real DefaultHttpContext but override with a simple helper
|
||||
httpContext.Request.Headers["Cookie"] = $"refreshToken={refreshTokenCookie}";
|
||||
}
|
||||
|
||||
if (isAuthenticated && userId is not null)
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
|
||||
}
|
||||
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
return controller;
|
||||
}
|
||||
|
||||
private TokenResponse MakeTokenResponse(string refresh = "refresh-token") =>
|
||||
new(AccessToken: "access", RefreshToken: refresh, ExpiresAt: DateTimeOffset.UtcNow.AddHours(1),
|
||||
User: new UserResponse(Guid.NewGuid(), "test@test.com", "Test", "User", true));
|
||||
|
||||
[Fact]
|
||||
public async Task Login_ReturnsOk_WithTokenResponse()
|
||||
{
|
||||
var response = MakeTokenResponse();
|
||||
_authService.AuthenticateAsync("test@test.com", "Password1!").Returns(response);
|
||||
|
||||
var controller = CreateController();
|
||||
var result = await controller.Login(new LoginRequest("test@test.com", "Password1!"));
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>()
|
||||
.Which.Value.Should().Be(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Refresh_ReturnsUnauthorized_WhenNoCookie()
|
||||
{
|
||||
var controller = CreateController(refreshTokenCookie: null);
|
||||
|
||||
var result = await controller.Refresh();
|
||||
|
||||
result.Should().BeOfType<UnauthorizedResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Refresh_ReturnsUnauthorized_WhenCookieIsEmpty()
|
||||
{
|
||||
var controller = CreateController(refreshTokenCookie: "");
|
||||
|
||||
var result = await controller.Refresh();
|
||||
|
||||
result.Should().BeOfType<UnauthorizedResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Refresh_ReturnsOk_WhenCookiePresent()
|
||||
{
|
||||
var response = MakeTokenResponse("new-refresh-token");
|
||||
_authService.RefreshTokenAsync(Arg.Any<string>()).Returns(response);
|
||||
|
||||
// Manually set cookie via IHeaderDictionary since DefaultHttpContext reads cookies from header
|
||||
var options = Options.Create(_jwtSettings);
|
||||
var controller = new AuthController(_authService, options);
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.Request.Headers.Append("Cookie", "refreshToken=some-token");
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
|
||||
var result = await controller.Refresh();
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>()
|
||||
.Which.Value.Should().Be(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Revoke_ReturnsNoContent_WhenCookiePresent()
|
||||
{
|
||||
var options = Options.Create(_jwtSettings);
|
||||
var controller = new AuthController(_authService, options);
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.Request.Headers.Append("Cookie", "refreshToken=some-token");
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
|
||||
var result = await controller.Revoke();
|
||||
|
||||
await _authService.Received(1).RevokeTokenAsync(Arg.Any<string>());
|
||||
result.Should().BeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Revoke_ReturnsNoContent_WhenNoCookie()
|
||||
{
|
||||
var controller = CreateController(refreshTokenCookie: null);
|
||||
|
||||
var result = await controller.Revoke();
|
||||
|
||||
await _authService.DidNotReceive().RevokeTokenAsync(Arg.Any<string>());
|
||||
result.Should().BeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_ReturnsUnauthorized_WhenNoUserIdClaim()
|
||||
{
|
||||
var controller = CreateController(isAuthenticated: false);
|
||||
|
||||
var result = await controller.ChangePassword(new ChangePasswordRequest("Old1!", "New1!"));
|
||||
|
||||
result.Should().BeOfType<UnauthorizedResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_ReturnsUnauthorized_WhenUserIdClaimIsNotAGuid()
|
||||
{
|
||||
var options = Options.Create(_jwtSettings);
|
||||
var controller = new AuthController(_authService, options);
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.User = new ClaimsPrincipal(
|
||||
new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "not-a-guid")], "TestAuth"));
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
|
||||
var result = await controller.ChangePassword(new ChangePasswordRequest("Old1!", "New1!"));
|
||||
|
||||
result.Should().BeOfType<UnauthorizedResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_SetsSecureCookie_WhenSameSiteIsNone()
|
||||
{
|
||||
// Exercises the SameSiteMode.None branch in GetCookieOptions → Secure = true
|
||||
var response = MakeTokenResponse();
|
||||
_authService.AuthenticateAsync(Arg.Any<string>(), Arg.Any<string>()).Returns(response);
|
||||
|
||||
var settings = new JwtSettings { Secret = _jwtSettings.Secret, Issuer = _jwtSettings.Issuer, Audience = _jwtSettings.Audience, CookieSameSite = "None" };
|
||||
var controller = new AuthController(_authService, Options.Create(settings));
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() };
|
||||
|
||||
var result = await controller.Login(new LoginRequest("test@test.com", "Password1!"));
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_FallsBackToStrictSameSite_WhenCookieSameSiteIsInvalid()
|
||||
{
|
||||
// Exercises the Enum.TryParse failure branch → SameSiteMode.Strict
|
||||
var response = MakeTokenResponse();
|
||||
_authService.AuthenticateAsync(Arg.Any<string>(), Arg.Any<string>()).Returns(response);
|
||||
|
||||
var settings = new JwtSettings { Secret = _jwtSettings.Secret, Issuer = _jwtSettings.Issuer, Audience = _jwtSettings.Audience, CookieSameSite = "Invalid" };
|
||||
var controller = new AuthController(_authService, Options.Create(settings));
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() };
|
||||
|
||||
var result = await controller.Login(new LoginRequest("test@test.com", "Password1!"));
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_ReturnsOk_WhenUserIdClaimIsValid()
|
||||
{
|
||||
var userId = Guid.NewGuid();
|
||||
var options = Options.Create(_jwtSettings);
|
||||
var controller = new AuthController(_authService, options);
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.User = new ClaimsPrincipal(
|
||||
new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())], "TestAuth"));
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
|
||||
var result = await controller.ChangePassword(new ChangePasswordRequest("Old1!", "New1!"));
|
||||
|
||||
await _authService.Received(1).ChangePasswordAsync(userId, "Old1!", "New1!");
|
||||
result.Should().BeOfType<OkResult>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
using SlpModularCms.Modules.Identity.Controllers;
|
||||
|
||||
namespace SlpModularCms.Modules.Identity.Tests.Controllers;
|
||||
|
||||
public class InvitationControllerTests : IDisposable
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly IInvitationService _invitationService = Substitute.For<IInvitationService>();
|
||||
|
||||
public InvitationControllerTests()
|
||||
{
|
||||
var dbOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
_context = new ApplicationDbContext(dbOptions);
|
||||
}
|
||||
|
||||
public void Dispose() => _context.Dispose();
|
||||
|
||||
private InvitationController CreateController() =>
|
||||
new(_invitationService, _context);
|
||||
|
||||
[Fact]
|
||||
public async Task Validate_ReturnsFalse_WhenTokenIsEmpty()
|
||||
{
|
||||
var controller = CreateController();
|
||||
|
||||
var result = await controller.Validate(string.Empty);
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { isValid = false, email = (string?)null, name = (string?)null, errorCode = "NOT_FOUND" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Validate_ReturnsFalse_WhenTokenNotFound()
|
||||
{
|
||||
var controller = CreateController();
|
||||
|
||||
var result = await controller.Validate("unknown-token");
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { isValid = false, email = (string?)null, name = (string?)null, errorCode = "NOT_FOUND" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Validate_ReturnsFalse_WhenInvitationIsAlreadyAccepted()
|
||||
{
|
||||
var invitation = new Invitation
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Token = "used-token",
|
||||
Email = "user@test.com",
|
||||
Role = "User",
|
||||
IsAccepted = true,
|
||||
ExpiryDate = DateTimeOffset.UtcNow.AddDays(1)
|
||||
};
|
||||
_context.Invitations.Add(invitation);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
var result = await CreateController().Validate("used-token");
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { isValid = false, email = "user@test.com", name = (string?)null, errorCode = "USED" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Validate_ReturnsFalse_WhenInvitationIsExpired()
|
||||
{
|
||||
var invitation = new Invitation
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Token = "expired-token",
|
||||
Email = "user@test.com",
|
||||
Role = "User",
|
||||
IsAccepted = false,
|
||||
ExpiryDate = DateTimeOffset.UtcNow.AddDays(-1) // in the past
|
||||
};
|
||||
_context.Invitations.Add(invitation);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
var result = await CreateController().Validate("expired-token");
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { isValid = false, email = "user@test.com", name = (string?)null, errorCode = "EXPIRED" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Validate_ReturnsTrue_WhenInvitationIsValid()
|
||||
{
|
||||
var invitation = new Invitation
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Token = "valid-token",
|
||||
Email = "user@test.com",
|
||||
Role = "User",
|
||||
IsAccepted = false,
|
||||
ExpiryDate = DateTimeOffset.UtcNow.AddDays(1)
|
||||
};
|
||||
_context.Invitations.Add(invitation);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
var result = await CreateController().Validate("valid-token");
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { isValid = true, email = "user@test.com", name = (string?)null, errorCode = (string?)null });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Complete_ReturnsOk_WithSuccessMessage()
|
||||
{
|
||||
var controller = CreateController();
|
||||
|
||||
var result = await controller.Complete(new CompleteSetupRequest("some-token", "Password1!"));
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { message = "Account succesvol ingesteld. Je kunt nu inloggen." });
|
||||
await _invitationService.Received(1).CompleteInvitationAsync("some-token", "Password1!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
using SlpModularCms.Modules.Identity.Controllers;
|
||||
|
||||
namespace SlpModularCms.Modules.Identity.Tests.Controllers;
|
||||
|
||||
public class SetupControllerTests
|
||||
{
|
||||
private readonly ISetupService _setupService = Substitute.For<ISetupService>();
|
||||
|
||||
[Fact]
|
||||
public async Task GetStatus_ReturnsOk_WithInitializedTrue_WhenSystemIsSetUp()
|
||||
{
|
||||
_setupService.IsSystemInitializedAsync().Returns(true);
|
||||
var controller = new SetupController(_setupService);
|
||||
|
||||
var result = await controller.GetStatus();
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { Initialized = true });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStatus_ReturnsOk_WithInitializedFalse_WhenSystemIsNotSetUp()
|
||||
{
|
||||
_setupService.IsSystemInitializedAsync().Returns(false);
|
||||
var controller = new SetupController(_setupService);
|
||||
|
||||
var result = await controller.GetStatus();
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { Initialized = false });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateOwner_ReturnsOk_WithSuccessMessage()
|
||||
{
|
||||
var controller = new SetupController(_setupService);
|
||||
|
||||
var result = await controller.CreateOwner(new CreateOwnerRequest("Owner", "owner@test.com", "Password1!"));
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { Message = "Systeem succesvol geïnitialiseerd. De eerste eigenaar is aangemaakt." });
|
||||
await _setupService.Received(1).CreateInitialOwnerAsync("Owner", "owner@test.com", "Password1!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
using System.Security.Claims;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
using SlpModularCms.Modules.Identity.Controllers;
|
||||
|
||||
namespace SlpModularCms.Modules.Identity.Tests.Controllers;
|
||||
|
||||
public class UsersControllerTests : IDisposable
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly RoleManager<ApplicationRole> _roleManager;
|
||||
private readonly IInvitationService _invitationService = Substitute.For<IInvitationService>();
|
||||
|
||||
public UsersControllerTests()
|
||||
{
|
||||
var dbOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
_context = new ApplicationDbContext(dbOptions);
|
||||
|
||||
var userStore = new UserStore<ApplicationUser, ApplicationRole, ApplicationDbContext, Guid>(_context);
|
||||
_userManager = new UserManager<ApplicationUser>(
|
||||
userStore,
|
||||
Options.Create(new IdentityOptions()),
|
||||
new PasswordHasher<ApplicationUser>(),
|
||||
Array.Empty<IUserValidator<ApplicationUser>>(),
|
||||
Array.Empty<IPasswordValidator<ApplicationUser>>(),
|
||||
new UpperInvariantLookupNormalizer(),
|
||||
new IdentityErrorDescriber(),
|
||||
null!,
|
||||
NullLogger<UserManager<ApplicationUser>>.Instance);
|
||||
|
||||
var roleStore = new RoleStore<ApplicationRole, ApplicationDbContext, Guid>(_context);
|
||||
_roleManager = new RoleManager<ApplicationRole>(
|
||||
roleStore,
|
||||
Array.Empty<IRoleValidator<ApplicationRole>>(),
|
||||
new UpperInvariantLookupNormalizer(),
|
||||
new IdentityErrorDescriber(),
|
||||
NullLogger<RoleManager<ApplicationRole>>.Instance);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_userManager.Dispose();
|
||||
_roleManager.Dispose();
|
||||
_context.Dispose();
|
||||
}
|
||||
|
||||
private UsersController CreateController(string? callerEmail = null)
|
||||
{
|
||||
var controller = new UsersController(_invitationService, _userManager);
|
||||
var httpContext = new DefaultHttpContext();
|
||||
if (callerEmail is not null)
|
||||
{
|
||||
httpContext.User = new ClaimsPrincipal(
|
||||
new ClaimsIdentity([new Claim(ClaimTypes.Name, callerEmail)], "TestAuth"));
|
||||
}
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
return controller;
|
||||
}
|
||||
|
||||
private async Task<ApplicationUser> CreateUser(string email, string role = "User", bool isActive = true)
|
||||
{
|
||||
if (!await _roleManager.RoleExistsAsync(role))
|
||||
await _roleManager.CreateAsync(new ApplicationRole { Name = role });
|
||||
|
||||
var user = new ApplicationUser
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Email = email,
|
||||
UserName = email,
|
||||
NormalizedEmail = email.ToUpperInvariant(),
|
||||
NormalizedUserName = email.ToUpperInvariant(),
|
||||
DisplayName = email,
|
||||
IsActive = isActive,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
await _userManager.CreateAsync(user, "Password1!");
|
||||
await _userManager.AddToRoleAsync(user, role);
|
||||
return user;
|
||||
}
|
||||
|
||||
// --- GetUsers ---
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_ReturnsOk_WithUsersList()
|
||||
{
|
||||
_invitationService.GetPendingInvitationByEmailAsync(Arg.Any<string>()).Returns((false, null));
|
||||
_invitationService.GetAllPendingInvitationsAsync().Returns([]);
|
||||
|
||||
await CreateUser("user@test.com", "User");
|
||||
|
||||
var result = await CreateController().GetUsers();
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
var list = ok.Value.Should().BeAssignableTo<IEnumerable<UserDto>>().Subject;
|
||||
list.Should().HaveCount(1);
|
||||
list.First().Email.Should().Be("user@test.com");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_IncludesPendingInvitationsWithoutAccount()
|
||||
{
|
||||
_invitationService.GetPendingInvitationByEmailAsync(Arg.Any<string>()).Returns((false, null));
|
||||
_invitationService.GetAllPendingInvitationsAsync().Returns([
|
||||
new PendingInvitationInfo(Guid.NewGuid(), "pending@test.com", "User", "tok", DateTimeOffset.UtcNow)
|
||||
]);
|
||||
|
||||
var result = await CreateController().GetUsers();
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
var list = ok.Value.Should().BeAssignableTo<IEnumerable<UserDto>>().Subject;
|
||||
list.Should().Contain(u => u.Email == "pending@test.com" && u.InvitationPending);
|
||||
}
|
||||
|
||||
// --- UpdateProfile ---
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateProfile_ReturnsUnauthorized_WhenNoNameIdentifierClaim()
|
||||
{
|
||||
var controller = new UsersController(_invitationService, _userManager);
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() };
|
||||
|
||||
var result = await controller.UpdateProfile(new UpdateProfileRequest("Name", "email@test.com"));
|
||||
|
||||
result.Should().BeOfType<UnauthorizedResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateProfile_ReturnsNotFound_WhenUserDoesNotExist()
|
||||
{
|
||||
var options = Options.Create(new IdentityOptions());
|
||||
var controller = new UsersController(_invitationService, _userManager);
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.User = new ClaimsPrincipal(
|
||||
new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "Test"));
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
|
||||
var result = await controller.UpdateProfile(new UpdateProfileRequest("Name", "newemail@test.com"));
|
||||
|
||||
result.Should().BeOfType<NotFoundResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateProfile_ReturnsBadRequest_WhenEmailAlreadyInUse()
|
||||
{
|
||||
var existingUser = await CreateUser("existing@test.com");
|
||||
var targetUser = await CreateUser("target@test.com");
|
||||
|
||||
var controller = new UsersController(_invitationService, _userManager);
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.User = new ClaimsPrincipal(
|
||||
new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, targetUser.Id.ToString())], "Test"));
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
|
||||
var result = await controller.UpdateProfile(new UpdateProfileRequest("Name", "existing@test.com"));
|
||||
|
||||
result.Should().BeOfType<BadRequestObjectResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateProfile_ReturnsOk_WhenUpdateSucceeds()
|
||||
{
|
||||
var user = await CreateUser("user@test.com");
|
||||
|
||||
var controller = new UsersController(_invitationService, _userManager);
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.User = new ClaimsPrincipal(
|
||||
new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())], "Test"));
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
|
||||
var result = await controller.UpdateProfile(new UpdateProfileRequest("New Name", "user@test.com"));
|
||||
|
||||
result.Should().BeOfType<OkObjectResult>()
|
||||
.Which.Value.Should().BeOfType<UserDto>()
|
||||
.Which.Name.Should().Be("New Name");
|
||||
}
|
||||
|
||||
// --- Invite ---
|
||||
|
||||
[Fact]
|
||||
public async Task Invite_ReturnsOk_WithInviteLink()
|
||||
{
|
||||
_invitationService.CreateInvitationAsync("new@test.com", "User").Returns("test-token");
|
||||
|
||||
var result = await CreateController().Invite(new InviteUserRequest("new@test.com", "User"));
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.Value.Should().BeEquivalentTo(new { inviteLink = "/invite/complete?token=test-token" });
|
||||
}
|
||||
|
||||
// --- SetUserActive ---
|
||||
|
||||
[Fact]
|
||||
public async Task SetUserActive_ReturnsNotFound_WhenUserDoesNotExist()
|
||||
{
|
||||
var result = await CreateController().SetUserActive(Guid.NewGuid(), new SetUserActiveRequest(false));
|
||||
|
||||
result.Should().BeOfType<NotFoundResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetUserActive_ReturnsBadRequest_WhenDeactivatingSelf()
|
||||
{
|
||||
var user = await CreateUser("self@test.com");
|
||||
|
||||
var result = await CreateController("self@test.com").SetUserActive(user.Id, new SetUserActiveRequest(false));
|
||||
|
||||
result.Should().BeOfType<BadRequestObjectResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetUserActive_ReturnsOk_WhenActivatingOtherUser()
|
||||
{
|
||||
var user = await CreateUser("other@test.com", "User", false);
|
||||
|
||||
var result = await CreateController("admin@test.com").SetUserActive(user.Id, new SetUserActiveRequest(true));
|
||||
|
||||
result.Should().BeOfType<OkResult>();
|
||||
}
|
||||
|
||||
// --- DeleteUser ---
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUser_ReturnsNotFound_WhenNoUserAndNoPendingInvitation()
|
||||
{
|
||||
_invitationService.DeleteInvitationByIdAsync(Arg.Any<Guid>()).Returns(false);
|
||||
|
||||
var result = await CreateController().DeleteUser(Guid.NewGuid());
|
||||
|
||||
result.Should().BeOfType<NotFoundResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUser_ReturnsNoContent_WhenPendingInvitationIsDeleted()
|
||||
{
|
||||
_invitationService.DeleteInvitationByIdAsync(Arg.Any<Guid>()).Returns(true);
|
||||
|
||||
var result = await CreateController().DeleteUser(Guid.NewGuid());
|
||||
|
||||
result.Should().BeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUser_ReturnsBadRequest_WhenDeletingSelf()
|
||||
{
|
||||
var user = await CreateUser("self@test.com");
|
||||
|
||||
var result = await CreateController("self@test.com").DeleteUser(user.Id);
|
||||
|
||||
result.Should().BeOfType<BadRequestObjectResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUser_ReturnsNoContent_WhenDeletingOtherUser()
|
||||
{
|
||||
var user = await CreateUser("other@test.com");
|
||||
_invitationService.DeletePendingInvitationsByEmailAsync(Arg.Any<string>()).Returns(Task.CompletedTask);
|
||||
|
||||
var result = await CreateController("admin@test.com").DeleteUser(user.Id);
|
||||
|
||||
result.Should().BeOfType<NoContentResult>();
|
||||
}
|
||||
|
||||
// --- ChangeRole ---
|
||||
|
||||
[Fact]
|
||||
public async Task ChangeRole_ReturnsNotFound_WhenNoUserAndInvitationUpdateFails()
|
||||
{
|
||||
_invitationService.UpdateInvitationRoleAsync(Arg.Any<Guid>(), Arg.Any<string>()).Returns(false);
|
||||
|
||||
var result = await CreateController().ChangeRole(Guid.NewGuid(), new ChangeRoleRequest("User"));
|
||||
|
||||
result.Should().BeOfType<NotFoundResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangeRole_ReturnsOk_WhenNoUserButInvitationUpdated()
|
||||
{
|
||||
_invitationService.UpdateInvitationRoleAsync(Arg.Any<Guid>(), Arg.Any<string>()).Returns(true);
|
||||
|
||||
// Need a caller identity with a name to check requester role
|
||||
var result = await CreateController("admin@test.com").ChangeRole(Guid.NewGuid(), new ChangeRoleRequest("User"));
|
||||
|
||||
result.Should().BeOfType<OkResult>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangeRole_ReturnsOk_WhenUserRoleUpdated()
|
||||
{
|
||||
await _roleManager.CreateAsync(new ApplicationRole { Name = "Owner" });
|
||||
await _roleManager.CreateAsync(new ApplicationRole { Name = "Administrator" });
|
||||
var user = await CreateUser("user@test.com", "User");
|
||||
|
||||
var result = await CreateController("owner@test.com").ChangeRole(user.Id, new ChangeRoleRequest("Administrator"));
|
||||
|
||||
result.Should().BeOfType<OkResult>();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user