Files
jobtrackingapp/JobTrackerApi.MariaDb.Tests/UserListProjectionTests.cs
T

95 lines
5.4 KiB
C#

using System.Data.Common;
using System.Security.Claims;
using JobTrackerApi.Controllers;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
using Xunit.Abstractions;
namespace JobTrackerApi.MariaDb.Tests;
public sealed class UserListProjectionTests(ITestOutputHelper output)
{
[Theory]
[InlineData(1)]
[InlineData(2)]
public async Task Summary_projects_only_required_columns_and_retains_global_admin_safety(int adminCount)
{
await using var database = await MariaDbDatabase.CreateAsync();
var recorder = new ReaderRecorder();
await using var db = database.Context(interceptor: recorder);
var linkedAt = new DateTimeOffset(2026, 11, 18, 10, 0, 0, TimeSpan.Zero);
db.Roles.AddRange(new IdentityRole("Admin") { Id = "admins", NormalizedName = "ADMIN" },
new IdentityRole("Member") { Id = "members", NormalizedName = "MEMBER" });
for (var index = 0; index < 75; index++)
{
var id = $"summary-{index:D2}";
db.Users.Add(new ApplicationUser
{
Id = id, Email = id + "@example.test", UserName = id,
FirstName = index == 0 ? "Åse" : null, LastName = index == 0 ? "Nordlys" : null,
DisplayName = index == 0 ? "Reviewed administrator" : null,
EmailConfirmed = index == 0, TwoFactorEnabled = index == 0,
GoogleEmail = index == 0 ? "linked@example.test" : null, GoogleLinkedAt = index == 0 ? linkedAt : null,
ProfileCvText = new string('c', 65_536), ProfileCvStructureJson = new string('j', 65_536),
AvatarImageDataUrl = new string('a', 16_384), PasswordHash = "synthetic-private-hash",
TotpSecretEncrypted = "synthetic-private-totp"
});
db.UserRoles.Add(new IdentityUserRole<string> { UserId = id, RoleId = index < adminCount ? "admins" : "members" });
}
await db.SaveChangesAsync();
db.ChangeTracker.Clear();
recorder.Commands.Clear();
await using var scope = database.App.Services.CreateAsyncScope();
var controller = new UsersController(scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>(),
scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>(), Mock.Of<IAppEmailSender>(),
new ConfigurationBuilder().Build(), NullLogger<UsersController>.Instance,
ExternalOrigin.Parse("http://localhost:3000", production: false), db: db)
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext
{ User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "summary-00")], "test")) } }
};
var result = await controller.List(default);
var rows = Assert.IsType<List<UsersController.UserDto>>(Assert.IsType<OkObjectResult>(result.Result).Value);
Assert.Equal(75, rows.Count);
var current = Assert.Single(rows, row => row.Id == "summary-00");
Assert.Equal("Åse", current.FirstName); Assert.Equal("Nordlys", current.LastName);
Assert.Equal("Reviewed administrator", current.DisplayName);
Assert.Equal("linked@example.test", current.GoogleEmail); Assert.Equal(linkedAt, current.GoogleLinkedAt);
Assert.True(current.EmailConfirmed); Assert.True(current.TwoFactorEnabled); Assert.True(current.IsCurrentUser);
Assert.Equal(adminCount > 1, current.CanRemoveAdmin); Assert.Equal(["Admin"], current.Roles);
var member = rows[^1];
Assert.Null(member.FirstName); Assert.Null(member.GoogleLinkedAt); Assert.False(member.IsCurrentUser);
Assert.True(member.CanRemoveAdmin); Assert.Equal(["Member"], member.Roles);
Assert.Equal(Enumerable.Range(0, 75).Select(index => $"summary-{index:D2}"), rows.Select(row => row.Id));
Assert.Empty(db.ChangeTracker.Entries<ApplicationUser>());
Assert.Equal(2, recorder.Commands.Count);
var sql = recorder.Commands[0];
Assert.Equal(10, sql.Split("FROM", StringSplitOptions.None)[0].Split(',').Length);
foreach (var excluded in new[] { "ProfileCvText", "ProfileCvStructureJson", "AvatarImageDataUrl", "PasswordHash", "TotpSecretEncrypted", "SecurityStamp", "StripeCustomerId", "DashboardLayoutJson" })
Assert.DoesNotContain(excluded, sql, StringComparison.Ordinal);
output.WriteLine($"Actual server:{database.ActualVersion}; users:75; admins:{adminCount}; SELECT columns:10; reader commands:2; excluded large fixture text:11059200 bytes");
output.WriteLine(sql);
}
private sealed class ReaderRecorder : DbCommandInterceptor
{
public List<string> Commands { get; } = [];
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command,
CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
{
Commands.Add(command.CommandText);
return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
}
}
}