test(agent): add unit tests for AgentState, AgentHealthCheck, AgentRegistrationService
13 tests covering: - AgentState file persistence (save, load, corrupt file, empty ID, clear) - AgentHealthCheck (healthy, degraded, unhealthy states) - AgentRegistrationService (successful registration, retry on failure, all retries exhausted, reuse existing identity, offline heartbeat on stop)
This commit is contained in:
1 parent
f937117f5a
commit
3fc42be4b2
4 files changed
+384
No files matched your search
@@ -0,0 +1,40 @@
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class AgentHealthCheckTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task CheckHealth_WhenRegistered_ReturnsHealthy()
|
||||
{
|
||||
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "valid-key" };
|
||||
var check = new AgentHealthCheck(state);
|
||||
|
||||
var result = await check.CheckHealthAsync(new HealthCheckContext());
|
||||
|
||||
result.Status.ShouldBe(HealthStatus.Healthy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckHealth_WhenNotRegistered_ReturnsUnhealthy()
|
||||
{
|
||||
var state = new AgentState { AgentId = Guid.Empty };
|
||||
var check = new AgentHealthCheck(state);
|
||||
|
||||
var result = await check.CheckHealthAsync(new HealthCheckContext());
|
||||
|
||||
result.Status.ShouldBe(HealthStatus.Unhealthy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckHealth_WhenNoApiKey_ReturnsDegraded()
|
||||
{
|
||||
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = null };
|
||||
var check = new AgentHealthCheck(state);
|
||||
|
||||
var result = await check.CheckHealthAsync(new HealthCheckContext());
|
||||
|
||||
result.Status.ShouldBe(HealthStatus.Degraded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class AgentRegistrationServiceTests : IDisposable
|
||||
{
|
||||
private readonly AgentOptions _options = new()
|
||||
{
|
||||
CentralUrl = "http://heimdall.test",
|
||||
SiteToken = "test-token",
|
||||
AgentName = "test-agent",
|
||||
HeartbeatIntervalSeconds = 1,
|
||||
RegistrationMaxRetries = 3,
|
||||
Version = "1.0.0"
|
||||
};
|
||||
|
||||
private readonly TempDir _tmp = new();
|
||||
private readonly AgentState _state = new();
|
||||
private readonly SystemMetricsProvider _metrics = new();
|
||||
|
||||
public AgentRegistrationServiceTests()
|
||||
{
|
||||
_state.ConfigureStateDirectory(_tmp.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Registration_Success_SetsAgentIdAndApiKey()
|
||||
{
|
||||
var handler = CreateOkHandler();
|
||||
var factory = CreateHttpClientFactory(handler);
|
||||
var service = CreateService(factory);
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
await Task.Delay(500);
|
||||
await service.StopAsync(CancellationToken.None);
|
||||
|
||||
_state.AgentId.ShouldNotBe(Guid.Empty);
|
||||
_state.ApiKey.ShouldBe("sk_test_abc123");
|
||||
_state.ApiKeyPrefix.ShouldBe("sk_test");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Registration_WithRetry_EventuallySucceeds()
|
||||
{
|
||||
var attempt = 0;
|
||||
var handler = new MockHttpMessageHandler(req =>
|
||||
{
|
||||
attempt++;
|
||||
if (attempt < 3)
|
||||
return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
|
||||
|
||||
return CreateRegistrationResponse();
|
||||
});
|
||||
|
||||
var factory = CreateHttpClientFactory(handler);
|
||||
var service = CreateService(factory);
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
// Retry backoff: 2^1=2s, 2^2=4s → need ~7s total for 3 attempts
|
||||
// Use a shorter deadline by reducing retries in options
|
||||
await Task.Delay(8000);
|
||||
await service.StopAsync(CancellationToken.None);
|
||||
|
||||
_state.AgentId.ShouldNotBe(Guid.Empty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Registration_AllRetriesFail_LogsError()
|
||||
{
|
||||
var handler = new MockHttpMessageHandler(_ =>
|
||||
new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
|
||||
|
||||
var factory = CreateHttpClientFactory(handler);
|
||||
var service = CreateService(factory);
|
||||
|
||||
// StartAsync does not throw — the exception is caught by BackgroundService.
|
||||
// Verify the service enters a faulted state.
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
|
||||
// Wait for all retries to exhaust (6s backoff + margin)
|
||||
await Task.Delay(9000);
|
||||
|
||||
// AgentId should remain empty because registration never succeeded
|
||||
_state.AgentId.ShouldBe(Guid.Empty);
|
||||
_state.ApiKey.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExistingIdentity_SkipsRegistration()
|
||||
{
|
||||
// Pre-populate the state file so LoadAsync() finds an identity
|
||||
var saved = new AgentState();
|
||||
saved.ConfigureStateDirectory(_tmp.Path);
|
||||
saved.AgentId = Guid.NewGuid();
|
||||
saved.ApiKey = "existing-key";
|
||||
saved.ApiKeyPrefix = "existing";
|
||||
await saved.SaveAsync();
|
||||
|
||||
// Also set the DI singleton state with same values
|
||||
_state.AgentId = saved.AgentId;
|
||||
_state.ApiKey = saved.ApiKey;
|
||||
_state.ApiKeyPrefix = saved.ApiKeyPrefix;
|
||||
|
||||
var registrationCalled = false;
|
||||
var handler = new MockHttpMessageHandler(req =>
|
||||
{
|
||||
if (req.RequestUri?.ToString().Contains("/register") == true)
|
||||
registrationCalled = true;
|
||||
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(JsonSerializer.Serialize(new
|
||||
{
|
||||
agentId = Guid.NewGuid(),
|
||||
apiKey = "new-key",
|
||||
apiKeyPrefix = "new"
|
||||
}))
|
||||
};
|
||||
});
|
||||
|
||||
var factory = CreateHttpClientFactory(handler);
|
||||
var service = CreateService(factory);
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
await Task.Delay(500);
|
||||
await service.StopAsync(CancellationToken.None);
|
||||
|
||||
registrationCalled.ShouldBeFalse();
|
||||
_state.ApiKey.ShouldBe("existing-key"); // unchanged
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopAsync_SendsOfflineHeartbeat()
|
||||
{
|
||||
HttpResponseMessage? lastHeartbeat = null;
|
||||
var handler = new MockHttpMessageHandler(req =>
|
||||
{
|
||||
if (req.RequestUri?.ToString().Contains("/register") == true)
|
||||
return CreateRegistrationResponse();
|
||||
|
||||
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
||||
{
|
||||
lastHeartbeat = new HttpResponseMessage(HttpStatusCode.OK);
|
||||
return lastHeartbeat;
|
||||
}
|
||||
|
||||
return new HttpResponseMessage(HttpStatusCode.OK);
|
||||
});
|
||||
|
||||
var factory = CreateHttpClientFactory(handler);
|
||||
var service = CreateService(factory);
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
await Task.Delay(500);
|
||||
|
||||
await service.StopAsync(CancellationToken.None);
|
||||
|
||||
// Agent must be registered after the flow
|
||||
_state.AgentId.ShouldNotBe(Guid.Empty);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_tmp.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
private AgentRegistrationService CreateService(
|
||||
IHttpClientFactory factory,
|
||||
AgentState? state = null)
|
||||
{
|
||||
state ??= _state;
|
||||
return new AgentRegistrationService(
|
||||
factory,
|
||||
state,
|
||||
Options.Create(_options),
|
||||
_metrics,
|
||||
NullLogger<AgentRegistrationService>.Instance);
|
||||
}
|
||||
|
||||
private static IHttpClientFactory CreateHttpClientFactory(
|
||||
MockHttpMessageHandler handler)
|
||||
{
|
||||
var client = new HttpClient(handler) { BaseAddress = new Uri("http://heimdall.test") };
|
||||
var factory = Substitute.For<IHttpClientFactory>();
|
||||
factory.CreateClient("Central").Returns(client);
|
||||
factory.CreateClient("IpResolver").Returns(client);
|
||||
return factory;
|
||||
}
|
||||
|
||||
private static MockHttpMessageHandler CreateOkHandler()
|
||||
{
|
||||
return new MockHttpMessageHandler(req =>
|
||||
{
|
||||
if (req.RequestUri?.ToString().Contains("/register") == true)
|
||||
return CreateRegistrationResponse();
|
||||
|
||||
return new HttpResponseMessage(HttpStatusCode.OK);
|
||||
});
|
||||
}
|
||||
|
||||
private static HttpResponseMessage CreateRegistrationResponse()
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(JsonSerializer.Serialize(new
|
||||
{
|
||||
agentId = Guid.NewGuid(),
|
||||
apiKey = "sk_test_abc123",
|
||||
apiKeyPrefix = "sk_test"
|
||||
}))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mock HTTP handler that returns predefined responses per request.
|
||||
/// </summary>
|
||||
public class MockHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handler)
|
||||
: HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(handler(request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class AgentStateTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task SaveAndLoad_PersistsIdentity()
|
||||
{
|
||||
using var tmp = new TempDir();
|
||||
|
||||
var state = new AgentState();
|
||||
state.ConfigureStateDirectory(tmp.Path);
|
||||
state.AgentId = Guid.NewGuid();
|
||||
state.ApiKey = "test-api-key-abc123";
|
||||
state.ApiKeyPrefix = "abc";
|
||||
state.PublicIp = "192.168.1.1";
|
||||
|
||||
await state.SaveAsync();
|
||||
|
||||
var loaded = new AgentState();
|
||||
loaded.ConfigureStateDirectory(tmp.Path);
|
||||
var result = await loaded.LoadAsync();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
result!.AgentId.ShouldBe(state.AgentId);
|
||||
result.ApiKey.ShouldBe("test-api-key-abc123");
|
||||
result.ApiKeyPrefix.ShouldBe("abc");
|
||||
result.PublicIp.ShouldBe("192.168.1.1");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Load_WhenNoFile_ReturnsNull()
|
||||
{
|
||||
using var tmp = new TempDir();
|
||||
|
||||
var state = new AgentState();
|
||||
state.ConfigureStateDirectory(tmp.Path);
|
||||
var result = await state.LoadAsync();
|
||||
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Load_WhenFileIsCorrupt_ReturnsNull()
|
||||
{
|
||||
using var tmp = new TempDir();
|
||||
Directory.CreateDirectory(tmp.Path);
|
||||
await File.WriteAllTextAsync(Path.Combine(tmp.Path, "agent-state.json"), "not-json");
|
||||
|
||||
var state = new AgentState();
|
||||
state.ConfigureStateDirectory(tmp.Path);
|
||||
var result = await state.LoadAsync();
|
||||
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Clear_RemovesStateFile()
|
||||
{
|
||||
using var tmp = new TempDir();
|
||||
|
||||
var state = new AgentState();
|
||||
state.ConfigureStateDirectory(tmp.Path);
|
||||
state.AgentId = Guid.NewGuid();
|
||||
await state.SaveAsync();
|
||||
|
||||
state.Clear();
|
||||
|
||||
File.Exists(Path.Combine(tmp.Path, "agent-state.json")).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Load_WhenAgentIdIsEmpty_ReturnsNull()
|
||||
{
|
||||
using var tmp = new TempDir();
|
||||
|
||||
var state = new AgentState();
|
||||
state.ConfigureStateDirectory(tmp.Path);
|
||||
state.AgentId = Guid.Empty;
|
||||
state.ApiKey = "some-key";
|
||||
await state.SaveAsync();
|
||||
|
||||
var loaded = new AgentState();
|
||||
loaded.ConfigureStateDirectory(tmp.Path);
|
||||
var result = await loaded.LoadAsync();
|
||||
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper that creates a temporary directory and cleans it up on dispose.
|
||||
/// </summary>
|
||||
public sealed class TempDir : IDisposable
|
||||
{
|
||||
public string Path { get; } = System.IO.Path.Combine(
|
||||
System.IO.Path.GetTempPath(),
|
||||
"heimdall-agent-tests",
|
||||
Guid.NewGuid().ToString("N"));
|
||||
|
||||
public TempDir() => Directory.CreateDirectory(Path);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(Path, recursive: true); }
|
||||
catch { /* best effort cleanup */ }
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
<Using Include="Shouldly" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
Reference in new issue
Block a user