Files
Heimdall/tests/Heimdall.Agent.Tests/AgentStateTests.cs
T

109 lines
2.9 KiB
C#
Raw Normal View History

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 */ }
}
}