Adds 2 units and docs for unit 3. nfr-requirements plan
This commit is contained in:
+80
@@ -0,0 +1,80 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ExceptionExtensions;
|
||||
using SlpModularCms.Modules.Master.BackgroundServices;
|
||||
using SlpModularCms.Modules.Master.Config;
|
||||
using SlpModularCms.Modules.Master.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Master.Tests.BackgroundServices;
|
||||
|
||||
public class IntegrityCheckBackgroundServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task ExecuteTickAsync_CallsVerifyIntegrityAsync()
|
||||
{
|
||||
var cmsService = Substitute.For<ICmsInstanceService>();
|
||||
var sut = CreateSut(cmsService);
|
||||
|
||||
await sut.ExecuteTickAsync(CancellationToken.None);
|
||||
|
||||
await cmsService.Received(1).VerifyIntegrityAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteTickAsync_DoesNotThrow_WhenVerifyIntegrityThrows()
|
||||
{
|
||||
var cmsService = Substitute.For<ICmsInstanceService>();
|
||||
cmsService.VerifyIntegrityAsync().ThrowsAsync(new InvalidOperationException("boom"));
|
||||
var sut = CreateSut(cmsService);
|
||||
|
||||
var act = async () => await sut.ExecuteTickAsync(CancellationToken.None);
|
||||
|
||||
await act.Should().NotThrowAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteTickAsync_LogsError_WhenVerifyIntegrityThrows()
|
||||
{
|
||||
var cmsService = Substitute.For<ICmsInstanceService>();
|
||||
cmsService.VerifyIntegrityAsync().ThrowsAsync(new InvalidOperationException("boom"));
|
||||
var logger = Substitute.For<ILogger<IntegrityCheckBackgroundService>>();
|
||||
var sut = CreateSut(cmsService, logger);
|
||||
|
||||
await sut.ExecuteTickAsync(CancellationToken.None);
|
||||
|
||||
logger.Received().Log(
|
||||
LogLevel.Error,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
private static IntegrityCheckBackgroundService CreateSut(
|
||||
ICmsInstanceService cmsService,
|
||||
ILogger<IntegrityCheckBackgroundService>? logger = null)
|
||||
{
|
||||
var scopeFactory = BuildScopeFactory(cmsService);
|
||||
var options = Options.Create(new MasterModuleOptions { IntegrityCheckIntervalMinutes = 60 });
|
||||
return new IntegrityCheckBackgroundService(
|
||||
scopeFactory,
|
||||
options,
|
||||
logger ?? Substitute.For<ILogger<IntegrityCheckBackgroundService>>());
|
||||
}
|
||||
|
||||
private static IServiceScopeFactory BuildScopeFactory(ICmsInstanceService cmsService)
|
||||
{
|
||||
var provider = Substitute.For<IServiceProvider>();
|
||||
provider.GetService(typeof(ICmsInstanceService)).Returns(cmsService);
|
||||
|
||||
var scope = Substitute.For<IServiceScope>();
|
||||
scope.ServiceProvider.Returns(provider);
|
||||
|
||||
var factory = Substitute.For<IServiceScopeFactory>();
|
||||
factory.CreateAsyncScope().Returns(new AsyncServiceScope(scope));
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ExceptionExtensions;
|
||||
using SlpModularCms.Modules.Master.Controllers;
|
||||
using SlpModularCms.Modules.Master.Data.Entities;
|
||||
using SlpModularCms.Modules.Master.Models;
|
||||
using SlpModularCms.Modules.Master.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Master.Tests.Controllers;
|
||||
|
||||
public class CmsInstanceControllerTests
|
||||
{
|
||||
private readonly ICmsInstanceService _service = Substitute.For<ICmsInstanceService>();
|
||||
private CmsInstanceController CreateSut() => new(_service);
|
||||
|
||||
private static CmsInstanceDto SampleDto() => new(
|
||||
Guid.NewGuid(), "Slave", "https://slave.test",
|
||||
CmsInstanceStatus.Available, null, null, null, null);
|
||||
|
||||
// --- GetAll ---
|
||||
|
||||
[Fact]
|
||||
public async Task GetAll_Returns200_WithList()
|
||||
{
|
||||
_service.GetAllAsync().Returns(new List<CmsInstanceDto> { SampleDto() });
|
||||
|
||||
var result = await CreateSut().GetAll();
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.StatusCode.Should().Be(200);
|
||||
}
|
||||
|
||||
// --- Add ---
|
||||
|
||||
[Fact]
|
||||
public async Task Add_Returns201Created_OnSuccess()
|
||||
{
|
||||
var dto = SampleDto();
|
||||
_service.AddAsync(Arg.Any<CreateCmsInstanceRequest>()).Returns(dto);
|
||||
|
||||
var result = await CreateSut().Add(new CreateCmsInstanceRequest("Slave", "https://slave.test", "key"));
|
||||
|
||||
var created = result.Should().BeOfType<CreatedAtActionResult>().Subject;
|
||||
created.StatusCode.Should().Be(201);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_Returns400_WhenArgumentExceptionThrown()
|
||||
{
|
||||
_service.AddAsync(Arg.Any<CreateCmsInstanceRequest>()).ThrowsAsync(new ArgumentException("Name is required."));
|
||||
|
||||
var result = await CreateSut().Add(new CreateCmsInstanceRequest("", "https://slave.test", "key"));
|
||||
|
||||
result.Should().BeOfType<BadRequestObjectResult>().Which.StatusCode.Should().Be(400);
|
||||
}
|
||||
|
||||
// --- UpdateStatus ---
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateStatus_Returns200_WithResult()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
_service.UpdateStatusAsync(id, Arg.Any<UpdateStatusRequest>())
|
||||
.Returns(new UpdateStatusResult(true, true));
|
||||
|
||||
var result = await CreateSut().UpdateStatus(id, new UpdateStatusRequest(CmsInstanceStatus.Available, null));
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
ok.StatusCode.Should().Be(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateStatus_Returns404_WhenKeyNotFoundExceptionThrown()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
_service.UpdateStatusAsync(id, Arg.Any<UpdateStatusRequest>())
|
||||
.ThrowsAsync(new KeyNotFoundException("Not found."));
|
||||
|
||||
var result = await CreateSut().UpdateStatus(id, new UpdateStatusRequest(CmsInstanceStatus.Available, null));
|
||||
|
||||
result.Should().BeOfType<NotFoundObjectResult>().Which.StatusCode.Should().Be(404);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateStatus_Returns400_WhenArgumentExceptionThrown()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
_service.UpdateStatusAsync(id, Arg.Any<UpdateStatusRequest>())
|
||||
.ThrowsAsync(new ArgumentException("DisableMessage required."));
|
||||
|
||||
var result = await CreateSut().UpdateStatus(id, new UpdateStatusRequest(CmsInstanceStatus.NotAvailable, null));
|
||||
|
||||
result.Should().BeOfType<BadRequestObjectResult>().Which.StatusCode.Should().Be(400);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SlpModularCms.Modules.Master.Data;
|
||||
using SlpModularCms.Modules.Master.Data.Entities;
|
||||
using SlpModularCms.Modules.Master.Repositories;
|
||||
|
||||
namespace SlpModularCms.Modules.Master.Tests.Repositories;
|
||||
|
||||
public class CmsInstanceRepositoryTests : IDisposable
|
||||
{
|
||||
private readonly MasterDbContext _context;
|
||||
private readonly CmsInstanceRepository _sut;
|
||||
|
||||
public CmsInstanceRepositoryTests()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<MasterDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
_context = new MasterDbContext(options);
|
||||
_sut = new CmsInstanceRepository(_context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_ReturnsAllInstances()
|
||||
{
|
||||
await _sut.AddAsync(Instance("A", CmsInstanceStatus.Available));
|
||||
await _sut.AddAsync(Instance("B", CmsInstanceStatus.Inactive));
|
||||
await _sut.SaveChangesAsync();
|
||||
|
||||
var result = await _sut.GetAllAsync();
|
||||
|
||||
result.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetActiveAsync_ExcludesInactive()
|
||||
{
|
||||
await _sut.AddAsync(Instance("Active", CmsInstanceStatus.Available));
|
||||
await _sut.AddAsync(Instance("Inactive", CmsInstanceStatus.Inactive));
|
||||
await _sut.SaveChangesAsync();
|
||||
|
||||
var result = await _sut.GetActiveAsync();
|
||||
|
||||
result.Should().HaveCount(1);
|
||||
result[0].Name.Should().Be("Active");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_ReturnsInstance_WhenFound()
|
||||
{
|
||||
var inst = Instance("Test", CmsInstanceStatus.Available);
|
||||
await _sut.AddAsync(inst);
|
||||
await _sut.SaveChangesAsync();
|
||||
|
||||
var result = await _sut.GetByIdAsync(inst.Id);
|
||||
|
||||
result.Should().NotBeNull();
|
||||
result!.Name.Should().Be("Test");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_ReturnsNull_WhenNotFound()
|
||||
{
|
||||
var result = await _sut.GetByIdAsync(Guid.NewGuid());
|
||||
|
||||
result.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAsync_AndSaveChangesAsync_PersistsInstance()
|
||||
{
|
||||
var inst = Instance("New", CmsInstanceStatus.Available);
|
||||
|
||||
await _sut.AddAsync(inst);
|
||||
await _sut.SaveChangesAsync();
|
||||
|
||||
var all = await _sut.GetAllAsync();
|
||||
all.Should().ContainSingle(i => i.Name == "New");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_PersistsChanges()
|
||||
{
|
||||
var inst = Instance("Original", CmsInstanceStatus.Available);
|
||||
await _sut.AddAsync(inst);
|
||||
await _sut.SaveChangesAsync();
|
||||
|
||||
inst.Name = "Updated";
|
||||
_sut.Update(inst);
|
||||
await _sut.SaveChangesAsync();
|
||||
|
||||
var result = await _sut.GetByIdAsync(inst.Id);
|
||||
result!.Name.Should().Be("Updated");
|
||||
}
|
||||
|
||||
private static CmsInstance Instance(string name, CmsInstanceStatus status) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = name,
|
||||
Url = "https://slave.test",
|
||||
ApiKey = "encrypted-key",
|
||||
Status = status
|
||||
};
|
||||
|
||||
public void Dispose() => _context.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using SlpModularCms.Modules.Master.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Master.Tests.Services;
|
||||
|
||||
public class ApiKeyProtectorTests
|
||||
{
|
||||
private readonly ApiKeyProtector _sut;
|
||||
|
||||
public ApiKeyProtectorTests()
|
||||
{
|
||||
var provider = new EphemeralDataProtectionProvider();
|
||||
_sut = new ApiKeyProtector(provider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Protect_ReturnsNonPlaintext()
|
||||
{
|
||||
var plain = "my-secret-api-key";
|
||||
|
||||
var result = _sut.Protect(plain);
|
||||
|
||||
result.Should().NotBe(plain);
|
||||
result.Should().NotBeNullOrEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unprotect_ReturnsOriginalValue_AfterProtect()
|
||||
{
|
||||
var plain = "my-secret-api-key";
|
||||
|
||||
var encrypted = _sut.Protect(plain);
|
||||
var decrypted = _sut.Unprotect(encrypted);
|
||||
|
||||
decrypted.Should().Be(plain);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unprotect_Throws_WhenGivenInvalidCiphertext()
|
||||
{
|
||||
var act = () => _sut.Unprotect("not-a-valid-ciphertext");
|
||||
|
||||
act.Should().Throw<Exception>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Modules.Master.Data.Entities;
|
||||
using SlpModularCms.Modules.Master.Models;
|
||||
using SlpModularCms.Modules.Master.Config;
|
||||
using SlpModularCms.Modules.Master.Repositories;
|
||||
using SlpModularCms.Modules.Master.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Master.Tests.Services;
|
||||
|
||||
public class CmsInstanceServiceTests
|
||||
{
|
||||
private readonly ICmsInstanceRepository _repo = Substitute.For<ICmsInstanceRepository>();
|
||||
private readonly ISlaveApiClient _slaveClient = Substitute.For<ISlaveApiClient>();
|
||||
private readonly IApiKeyProtector _protector = Substitute.For<IApiKeyProtector>();
|
||||
private readonly IHttpContextAccessor _httpContextAccessor = Substitute.For<IHttpContextAccessor>();
|
||||
private readonly ILogger<CmsInstanceService> _logger = Substitute.For<ILogger<CmsInstanceService>>();
|
||||
private readonly IOptions<MasterModuleOptions> _options = Options.Create(new MasterModuleOptions { MasterUrl = "https://master.test" });
|
||||
|
||||
private CmsInstanceService CreateSut() => new(new MasterServiceDependencies(
|
||||
_repo, _slaveClient, _protector, _options, _httpContextAccessor, _logger));
|
||||
|
||||
// --- GetAllAsync ---
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_ReturnsDtos_WithoutApiKey()
|
||||
{
|
||||
var instance = ActiveInstance();
|
||||
_repo.GetAllAsync().Returns([instance]);
|
||||
|
||||
var result = await CreateSut().GetAllAsync();
|
||||
|
||||
result.Should().HaveCount(1);
|
||||
result[0].Id.Should().Be(instance.Id);
|
||||
}
|
||||
|
||||
// --- AddAsync ---
|
||||
|
||||
[Fact]
|
||||
public async Task AddAsync_ThrowsArgumentException_WhenNameIsEmpty()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
var act = async () => await sut.AddAsync(new CreateCmsInstanceRequest("", "https://slave.test", "key"));
|
||||
|
||||
await act.Should().ThrowAsync<ArgumentException>().WithMessage("*Name*");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAsync_ThrowsArgumentException_WhenUrlIsEmpty()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
var act = async () => await sut.AddAsync(new CreateCmsInstanceRequest("Slave", "", "key"));
|
||||
|
||||
await act.Should().ThrowAsync<ArgumentException>().WithMessage("*Url*");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAsync_ThrowsArgumentException_WhenApiKeyIsEmpty()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
var act = async () => await sut.AddAsync(new CreateCmsInstanceRequest("Slave", "https://slave.test", ""));
|
||||
|
||||
await act.Should().ThrowAsync<ArgumentException>().WithMessage("*ApiKey*");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAsync_EncryptsAndPersists_AndRegistersWithSlave()
|
||||
{
|
||||
_protector.Protect("plain").Returns("encrypted");
|
||||
_slaveClient.RegisterMasterAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()).Returns(true);
|
||||
_httpContextAccessor.HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = await sut.AddAsync(new CreateCmsInstanceRequest("Slave", "https://slave.test", "plain"));
|
||||
|
||||
result.Should().NotBeNull();
|
||||
await _repo.Received(1).AddAsync(Arg.Is<CmsInstance>(i => i.ApiKey == "encrypted"));
|
||||
await _slaveClient.Received(1).RegisterMasterAsync("https://slave.test", "plain", "https://master.test");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAsync_StillPersists_WhenSlaveRegistrationFails()
|
||||
{
|
||||
_protector.Protect("plain").Returns("encrypted");
|
||||
_slaveClient.RegisterMasterAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()).Returns(false);
|
||||
_httpContextAccessor.HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
var sut = CreateSut();
|
||||
var result = await sut.AddAsync(new CreateCmsInstanceRequest("Slave", "https://slave.test", "plain"));
|
||||
|
||||
result.Should().NotBeNull();
|
||||
await _repo.Received(1).AddAsync(Arg.Any<CmsInstance>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddAsync_UsesMasterUrlFromHttpContext_WhenAvailable()
|
||||
{
|
||||
_protector.Protect(Arg.Any<string>()).Returns("enc");
|
||||
_slaveClient.RegisterMasterAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()).Returns(true);
|
||||
|
||||
var httpContext = Substitute.For<HttpContext>();
|
||||
var httpRequest = Substitute.For<HttpRequest>();
|
||||
httpRequest.Scheme.Returns("https");
|
||||
httpRequest.Host.Returns(new HostString("my-master.test"));
|
||||
httpContext.Request.Returns(httpRequest);
|
||||
_httpContextAccessor.HttpContext.Returns(httpContext);
|
||||
|
||||
var sut = CreateSut();
|
||||
await sut.AddAsync(new CreateCmsInstanceRequest("Slave", "https://slave.test", "plain"));
|
||||
|
||||
await _slaveClient.Received(1).RegisterMasterAsync(Arg.Any<string>(), Arg.Any<string>(), "https://my-master.test");
|
||||
}
|
||||
|
||||
// --- UpdateStatusAsync ---
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateStatusAsync_ThrowsKeyNotFoundException_WhenInstanceNotFound()
|
||||
{
|
||||
_repo.GetByIdAsync(Arg.Any<Guid>()).Returns((CmsInstance?)null);
|
||||
|
||||
var act = async () => await CreateSut().UpdateStatusAsync(Guid.NewGuid(), new UpdateStatusRequest(CmsInstanceStatus.Available, null));
|
||||
|
||||
await act.Should().ThrowAsync<KeyNotFoundException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateStatusAsync_ThrowsArgumentException_WhenDisableMessageMissingForNotAvailable()
|
||||
{
|
||||
_repo.GetByIdAsync(Arg.Any<Guid>()).Returns(ActiveInstance());
|
||||
|
||||
var act = async () => await CreateSut().UpdateStatusAsync(Guid.NewGuid(), new UpdateStatusRequest(CmsInstanceStatus.NotAvailable, null));
|
||||
|
||||
await act.Should().ThrowAsync<ArgumentException>().WithMessage("*DisableMessage*");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateStatusAsync_DoesNotPushToSlave_WhenStatusIsInactive()
|
||||
{
|
||||
var instance = ActiveInstance();
|
||||
_repo.GetByIdAsync(instance.Id).Returns(instance);
|
||||
|
||||
var result = await CreateSut().UpdateStatusAsync(instance.Id, new UpdateStatusRequest(CmsInstanceStatus.Inactive, null));
|
||||
|
||||
result.Success.Should().BeTrue();
|
||||
result.SlaveContactSuccess.Should().BeTrue();
|
||||
await _slaveClient.DidNotReceive().PushStatusAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<string?>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateStatusAsync_PushesToSlave_AndReturnsSlaveContactSuccess_WhenPushSucceeds()
|
||||
{
|
||||
var instance = ActiveInstance();
|
||||
_repo.GetByIdAsync(instance.Id).Returns(instance);
|
||||
_protector.Unprotect("encrypted-key").Returns("plain");
|
||||
_slaveClient.PushStatusAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<string?>()).Returns(true);
|
||||
|
||||
var result = await CreateSut().UpdateStatusAsync(instance.Id, new UpdateStatusRequest(CmsInstanceStatus.Available, null));
|
||||
|
||||
result.Success.Should().BeTrue();
|
||||
result.SlaveContactSuccess.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateStatusAsync_ReturnsSlaveContactFalse_WhenPushFails()
|
||||
{
|
||||
var instance = ActiveInstance();
|
||||
_repo.GetByIdAsync(instance.Id).Returns(instance);
|
||||
_protector.Unprotect("encrypted-key").Returns("plain");
|
||||
_slaveClient.PushStatusAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<string?>()).Returns(false);
|
||||
|
||||
var result = await CreateSut().UpdateStatusAsync(instance.Id, new UpdateStatusRequest(CmsInstanceStatus.Available, null));
|
||||
|
||||
result.Success.Should().BeTrue();
|
||||
result.SlaveContactSuccess.Should().BeFalse();
|
||||
}
|
||||
|
||||
// --- VerifyIntegrityAsync ---
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyIntegrityAsync_SkipsCheck_WhenMasterUrlNotConfigured()
|
||||
{
|
||||
_httpContextAccessor.HttpContext.Returns((HttpContext?)null);
|
||||
var optionsNoUrl = Options.Create(new MasterModuleOptions { MasterUrl = null });
|
||||
var sut = new CmsInstanceService(new MasterServiceDependencies(
|
||||
_repo, _slaveClient, _protector, optionsNoUrl, _httpContextAccessor, _logger));
|
||||
|
||||
await sut.VerifyIntegrityAsync();
|
||||
|
||||
await _repo.DidNotReceive().GetActiveAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyIntegrityAsync_SetsLastIntegrityCheckFailedAt_WhenSlaveUnreachable()
|
||||
{
|
||||
var instance = ActiveInstance();
|
||||
_repo.GetActiveAsync().Returns([instance]);
|
||||
_protector.Unprotect("encrypted-key").Returns("plain");
|
||||
_slaveClient.GetRegisteredMasterUrlAsync(Arg.Any<string>(), Arg.Any<string>()).Returns((string?)null);
|
||||
_httpContextAccessor.HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
await CreateSut().VerifyIntegrityAsync();
|
||||
|
||||
_repo.Received().Update(Arg.Is<CmsInstance>(i => i.LastIntegrityCheckFailedAt.HasValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyIntegrityAsync_ReregistersAndClearsFlag_WhenUrlMismatch()
|
||||
{
|
||||
var instance = ActiveInstance();
|
||||
_repo.GetActiveAsync().Returns([instance]);
|
||||
_protector.Unprotect("encrypted-key").Returns("plain");
|
||||
_slaveClient.GetRegisteredMasterUrlAsync(Arg.Any<string>(), Arg.Any<string>()).Returns("https://old-master.test");
|
||||
_slaveClient.RegisterMasterAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()).Returns(true);
|
||||
_httpContextAccessor.HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
await CreateSut().VerifyIntegrityAsync();
|
||||
|
||||
_repo.Received().Update(Arg.Is<CmsInstance>(i => i.LastIntegrityCheckFailedAt == null && i.LastContactedAt.HasValue));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyIntegrityAsync_ClearsFlag_WhenUrlMatches()
|
||||
{
|
||||
var instance = ActiveInstance();
|
||||
instance.LastIntegrityCheckFailedAt = DateTimeOffset.UtcNow.AddHours(-1);
|
||||
_repo.GetActiveAsync().Returns([instance]);
|
||||
_protector.Unprotect("encrypted-key").Returns("plain");
|
||||
_slaveClient.GetRegisteredMasterUrlAsync(Arg.Any<string>(), Arg.Any<string>()).Returns("https://master.test");
|
||||
_httpContextAccessor.HttpContext.Returns((HttpContext?)null);
|
||||
|
||||
await CreateSut().VerifyIntegrityAsync();
|
||||
|
||||
_repo.Received().Update(Arg.Is<CmsInstance>(i => i.LastIntegrityCheckFailedAt == null));
|
||||
}
|
||||
|
||||
private static CmsInstance ActiveInstance() => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Slave",
|
||||
Url = "https://slave.test",
|
||||
ApiKey = "encrypted-key",
|
||||
Status = CmsInstanceStatus.Available
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using FluentAssertions;
|
||||
using SlpModularCms.Modules.Master.Services;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SlpModularCms.Modules.Master.Tests.Services;
|
||||
|
||||
public class SlaveApiClientTests
|
||||
{
|
||||
private const string SlaveUrl = "https://slave.test";
|
||||
private const string ApiKey = "plain-key";
|
||||
private const string MasterUrl = "https://master.test";
|
||||
|
||||
private static SlaveApiClient CreateSut(HttpMessageHandler handler)
|
||||
=> new(new HttpClient(handler));
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterMasterAsync_ReturnsTrue_WhenResponseIsSuccess()
|
||||
{
|
||||
var handler = new FakeHttpMessageHandler(HttpStatusCode.OK);
|
||||
var sut = CreateSut(handler);
|
||||
|
||||
var result = await sut.RegisterMasterAsync(SlaveUrl, ApiKey, MasterUrl);
|
||||
|
||||
result.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterMasterAsync_ReturnsFalse_WhenResponseIsFailure()
|
||||
{
|
||||
var handler = new FakeHttpMessageHandler(HttpStatusCode.InternalServerError);
|
||||
var sut = CreateSut(handler);
|
||||
|
||||
var result = await sut.RegisterMasterAsync(SlaveUrl, ApiKey, MasterUrl);
|
||||
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterMasterAsync_ReturnsFalse_WhenExceptionIsThrown()
|
||||
{
|
||||
var handler = new ThrowingHttpMessageHandler();
|
||||
var sut = CreateSut(handler);
|
||||
|
||||
var result = await sut.RegisterMasterAsync(SlaveUrl, ApiKey, MasterUrl);
|
||||
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PushStatusAsync_ReturnsTrue_WhenResponseIsSuccess()
|
||||
{
|
||||
var handler = new FakeHttpMessageHandler(HttpStatusCode.OK);
|
||||
var sut = CreateSut(handler);
|
||||
|
||||
var result = await sut.PushStatusAsync(SlaveUrl, ApiKey, isAvailable: false, disableMessage: "Maintenance");
|
||||
|
||||
result.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PushStatusAsync_ReturnsFalse_WhenResponseIsFailure()
|
||||
{
|
||||
var handler = new FakeHttpMessageHandler(HttpStatusCode.BadGateway);
|
||||
var sut = CreateSut(handler);
|
||||
|
||||
var result = await sut.PushStatusAsync(SlaveUrl, ApiKey, isAvailable: true, disableMessage: null);
|
||||
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRegisteredMasterUrlAsync_ReturnsMasterUrl_WhenResponseIsSuccess()
|
||||
{
|
||||
var json = JsonSerializer.Serialize(new { MasterUrl = MasterUrl });
|
||||
var handler = new FakeHttpMessageHandler(HttpStatusCode.OK, json);
|
||||
var sut = CreateSut(handler);
|
||||
|
||||
var result = await sut.GetRegisteredMasterUrlAsync(SlaveUrl, ApiKey);
|
||||
|
||||
result.Should().Be(MasterUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRegisteredMasterUrlAsync_ReturnsNull_WhenResponseIsFailure()
|
||||
{
|
||||
var handler = new FakeHttpMessageHandler(HttpStatusCode.NotFound);
|
||||
var sut = CreateSut(handler);
|
||||
|
||||
var result = await sut.GetRegisteredMasterUrlAsync(SlaveUrl, ApiKey);
|
||||
|
||||
result.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterMasterAsync_SetsApiKeyHeader()
|
||||
{
|
||||
string? capturedKey = null;
|
||||
var handler = new CapturingHttpMessageHandler(req =>
|
||||
{
|
||||
req.Headers.TryGetValues("X-Master-Api-Key", out var values);
|
||||
capturedKey = values?.FirstOrDefault();
|
||||
});
|
||||
var sut = CreateSut(handler);
|
||||
|
||||
await sut.RegisterMasterAsync(SlaveUrl, ApiKey, MasterUrl);
|
||||
|
||||
capturedKey.Should().Be(ApiKey);
|
||||
}
|
||||
|
||||
private class FakeHttpMessageHandler(HttpStatusCode statusCode, string? content = null) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var response = new HttpResponseMessage(statusCode);
|
||||
if (content is not null)
|
||||
response.Content = new StringContent(content, Encoding.UTF8, "application/json");
|
||||
return Task.FromResult(response);
|
||||
}
|
||||
}
|
||||
|
||||
private class ThrowingHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
=> throw new HttpRequestException("Connection refused");
|
||||
}
|
||||
|
||||
private class CapturingHttpMessageHandler(Action<HttpRequestMessage> capture) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
capture(request);
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="FluentAssertions" Version="8.10.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="NSubstitute" Version="5.3.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Microsoft.Extensions.Options" />
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user