IdentityShroud/IdentityShroud.Core.Tests/Services/RealmServiceTests.cs

100 lines
3.1 KiB
C#
Raw Normal View History

2026-02-15 07:15:11 +01:00
using IdentityShroud.Core.Contracts;
using IdentityShroud.Core.Model;
using IdentityShroud.Core.Security.Keys;
using IdentityShroud.Core.Services;
using IdentityShroud.Core.Tests.Fixtures;
using IdentityShroud.TestUtils.Substitutes;
using Microsoft.EntityFrameworkCore;
namespace IdentityShroud.Core.Tests.Services;
public class RealmServiceTests : IClassFixture<DbFixture>
{
2026-02-15 07:15:11 +01:00
private readonly DbFixture _dbFixture;
private readonly IKeyService _keyService = Substitute.For<IKeyService>();
public RealmServiceTests(DbFixture dbFixture)
{
2026-02-15 07:15:11 +01:00
_dbFixture = dbFixture;
using Db db = dbFixture.CreateDbContext();
if (!db.Database.EnsureCreated())
TruncateTables(db);
}
2026-02-15 07:15:11 +01:00
private void TruncateTables(Db db)
{
2026-02-15 07:15:11 +01:00
db.Database.ExecuteSqlRaw("TRUNCATE realm CASCADE;");
}
[Theory]
[InlineData(null)]
[InlineData("a7c2a39c-3ed9-4790-826e-43bb2e5e480c")]
public async Task Create(string? idString)
{
2026-02-15 07:15:11 +01:00
// Setup
Guid? realmId = null;
if (idString is not null)
realmId = new(idString);
2026-02-15 07:15:11 +01:00
RealmCreateResponse? val;
await using (var db = _dbFixture.CreateDbContext())
{
_keyService.CreateKey(Arg.Any<KeyPolicy>())
.Returns(new RealmKey(Guid.NewGuid(), "TST", [21], DateTime.UtcNow));
// Act
RealmService sut = new(db, _keyService);
var response = await sut.Create(
new(realmId, "slug", "New realm"),
TestContext.Current.CancellationToken);
// Verify
val = ResultAssert.Success(response);
if (realmId.HasValue)
Assert.Equal(realmId, val.Id);
else
Assert.NotEqual(Guid.Empty, val.Id);
Assert.Equal("slug", val.Slug);
Assert.Equal("New realm", val.Name);
_keyService.Received().CreateKey(Arg.Any<KeyPolicy>());
}
await using (var db = _dbFixture.CreateDbContext())
{
var dbRecord = await db.Realms
.Include(e => e.Keys)
.SingleAsync(e => e.Id == val.Id, TestContext.Current.CancellationToken);
Assert.Equal("TST", dbRecord.Keys[0].KeyType);
}
}
2026-02-15 07:15:11 +01:00
[Theory]
[InlineData("slug", null)]
[InlineData("foo", "Foo")]
public async Task FindBySlug(string slug, string? name)
{
await using (var setupContext = _dbFixture.CreateDbContext())
2026-02-15 07:15:11 +01:00
{
setupContext.Realms.Add(new()
{
Slug = "foo",
Name = "Foo",
});
setupContext.Realms.Add(new()
{
Slug = "bar",
Name = "Bar",
});
await setupContext.SaveChangesAsync(TestContext.Current.CancellationToken);
}
await using var actContext = _dbFixture.CreateDbContext();
RealmService sut = new(actContext, _keyService);
2026-02-15 07:15:11 +01:00
// Act
var result = await sut.FindBySlug(slug, TestContext.Current.CancellationToken);
Assert.Equal(name, result?.Name);
}
}