test(agent): add service tests for CameraStream, ConfigReceiver, FrameAnalyzer, SystemMetrics, DTOs
This commit is contained in:
1 parent
06247d4f5c
commit
262adc07cf
10 files changed
+769
No files matched your search
@@ -166,8 +166,12 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
return [];
|
||||
}
|
||||
|
||||
private bool _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_cts.Cancel();
|
||||
_cts.Dispose();
|
||||
_frameQueue.Writer.TryComplete();
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class CameraStreamServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_ActiveStreamCount_IsZero()
|
||||
{
|
||||
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
|
||||
service.ActiveStreamCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartStreamAsync_FfmpegNotFound_ReturnsFalse()
|
||||
{
|
||||
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
|
||||
var result = await service.StartStreamAsync(Guid.NewGuid(), "rtsp://localhost:8554/test");
|
||||
result.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartStreamAsync_MultipleCalls_AllReturnFalse()
|
||||
{
|
||||
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
|
||||
var id = Guid.NewGuid();
|
||||
var first = await service.StartStreamAsync(id, "rtsp://localhost:8554/test");
|
||||
var second = await service.StartStreamAsync(id, "rtsp://localhost:8554/test");
|
||||
first.ShouldBeFalse();
|
||||
second.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopStreamAsync_UnknownCamera_DoesNotThrow()
|
||||
{
|
||||
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
|
||||
await service.StopStreamAsync(Guid.NewGuid());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ActiveStreamCount_AfterMultipleStarts_RemainsZero()
|
||||
{
|
||||
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
await service.StartStreamAsync(Guid.NewGuid(), $"rtsp://camera{i}/test");
|
||||
}
|
||||
service.ActiveStreamCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_MultipleTimes_DoesNotThrow()
|
||||
{
|
||||
var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
|
||||
service.Dispose();
|
||||
service.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartStreamAsync_EmptyRtspUrl_ReturnsFalse()
|
||||
{
|
||||
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
|
||||
var result = await service.StartStreamAsync(Guid.NewGuid(), string.Empty);
|
||||
result.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartStreamAsync_WithCancellationToken_RespectsCancellation()
|
||||
{
|
||||
using var service = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>());
|
||||
await service.StartStreamAsync(Guid.NewGuid(), "rtsp://localhost:8554/test", CancellationToken.None);
|
||||
service.ActiveStreamCount.ShouldBe(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class ConfigReceiverServiceTests
|
||||
{
|
||||
private static ConfigReceiverService CreateService(AgentState? state = null)
|
||||
{
|
||||
state ??= new AgentState { AgentId = Guid.Empty };
|
||||
var options = Options.Create(new AgentOptions
|
||||
{
|
||||
CentralUrl = "http://localhost:5000",
|
||||
SiteToken = "test"
|
||||
});
|
||||
var logger = Substitute.For<ILogger<ConfigReceiverService>>();
|
||||
var httpFactory = Substitute.For<IHttpClientFactory>();
|
||||
return new ConfigReceiverService(state, options, logger, httpFactory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WithDependencies_DoesNotThrow()
|
||||
{
|
||||
var service = CreateService();
|
||||
service.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartStop_WhenNotRegistered_StopsGracefully()
|
||||
{
|
||||
var state = new AgentState { AgentId = Guid.Empty };
|
||||
var service = CreateService(state);
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
|
||||
await service.StopAsync(cts.Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartStop_WhenRegistered_StopsGracefully()
|
||||
{
|
||||
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
|
||||
var service = CreateService(state);
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
await service.StopAsync(cts.Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopAsync_WithoutStart_DoesNotThrow()
|
||||
{
|
||||
var service = CreateService();
|
||||
await service.StopAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Text.Json;
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class DetectionResultTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_WithAllValues_SetsProperties()
|
||||
{
|
||||
var result = new DetectionResult(
|
||||
Label: "person",
|
||||
Confidence: 0.95f,
|
||||
X: 100f, Y: 200f,
|
||||
Width: 50f, Height: 80f,
|
||||
ClassIndex: 0);
|
||||
|
||||
result.Label.ShouldBe("person");
|
||||
result.Confidence.ShouldBe(0.95f);
|
||||
result.X.ShouldBe(100f);
|
||||
result.Y.ShouldBe(200f);
|
||||
result.Width.ShouldBe(50f);
|
||||
result.Height.ShouldBe(80f);
|
||||
result.ClassIndex.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WithoutClassIndex_DefaultsToNull()
|
||||
{
|
||||
var result = new DetectionResult("car", 0.87f, 10f, 20f, 30f, 40f);
|
||||
|
||||
result.ClassIndex.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_SameValues_AreEqual()
|
||||
{
|
||||
var a = new DetectionResult("person", 0.95f, 100f, 200f, 50f, 80f, 0);
|
||||
var b = new DetectionResult("person", 0.95f, 100f, 200f, 50f, 80f, 0);
|
||||
|
||||
(a == b).ShouldBeTrue();
|
||||
a.Equals(b).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_DifferentValues_AreNotEqual()
|
||||
{
|
||||
var a = new DetectionResult("person", 0.95f, 100f, 200f, 50f, 80f);
|
||||
var b = new DetectionResult("car", 0.95f, 100f, 200f, 50f, 80f);
|
||||
|
||||
(a != b).ShouldBeTrue();
|
||||
a.Equals(b).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonSerialization_Roundtrip_PreservesValues()
|
||||
{
|
||||
var original = new DetectionResult("dog", 0.88f, 150f, 300f, 60f, 90f, 16);
|
||||
var json = JsonSerializer.Serialize(original);
|
||||
var deserialized = JsonSerializer.Deserialize<DetectionResult>(json);
|
||||
|
||||
deserialized.ShouldNotBeNull();
|
||||
deserialized.Label.ShouldBe(original.Label);
|
||||
deserialized.Confidence.ShouldBe(original.Confidence);
|
||||
deserialized.X.ShouldBe(original.X);
|
||||
deserialized.Y.ShouldBe(original.Y);
|
||||
deserialized.Width.ShouldBe(original.Width);
|
||||
deserialized.Height.ShouldBe(original.Height);
|
||||
deserialized.ClassIndex.ShouldBe(original.ClassIndex);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToString_ReturnsLabelAndConfidence()
|
||||
{
|
||||
var result = new DetectionResult("person", 0.95f, 100f, 200f, 50f, 80f);
|
||||
var str = result.ToString();
|
||||
|
||||
str.ShouldContain("person");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deconstruct_ReturnsAllProperties()
|
||||
{
|
||||
var result = new DetectionResult("bicycle", 0.75f, 0f, 0f, 100f, 200f, 1);
|
||||
var (label, confidence, x, y, w, h, ci) = result;
|
||||
|
||||
label.ShouldBe("bicycle");
|
||||
confidence.ShouldBe(0.75f);
|
||||
x.ShouldBe(0f);
|
||||
y.ShouldBe(0f);
|
||||
w.ShouldBe(100f);
|
||||
h.ShouldBe(200f);
|
||||
ci.ShouldBe(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Text.Json;
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class FrameAnalysisResultTests
|
||||
{
|
||||
private static readonly IReadOnlyList<DetectionResult> SampleDetections =
|
||||
[
|
||||
new DetectionResult("person", 0.95f, 100f, 200f, 50f, 80f),
|
||||
new DetectionResult("car", 0.87f, 300f, 400f, 120f, 90f)
|
||||
];
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WithValues_SetsProperties()
|
||||
{
|
||||
var result = new FrameAnalysisResult("base64data", SampleDetections, 42);
|
||||
|
||||
result.ImageBase64.ShouldBe("base64data");
|
||||
result.Detections.ShouldBeSameAs(SampleDetections);
|
||||
result.Detections.Count.ShouldBe(2);
|
||||
result.ProcessingMs.ShouldBe(42);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WithEmptyDetections_HasEmptyList()
|
||||
{
|
||||
var result = new FrameAnalysisResult("base64data", [], 0);
|
||||
|
||||
result.Detections.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_SameValues_AreEqual()
|
||||
{
|
||||
var detections = new List<DetectionResult>
|
||||
{
|
||||
new("person", 0.95f, 100f, 200f, 50f, 80f)
|
||||
};
|
||||
|
||||
var a = new FrameAnalysisResult("img1", detections, 10);
|
||||
var b = new FrameAnalysisResult("img1", detections, 10);
|
||||
|
||||
(a == b).ShouldBeTrue();
|
||||
a.Equals(b).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_DifferentImageBase64_AreNotEqual()
|
||||
{
|
||||
var detections = new List<DetectionResult>
|
||||
{
|
||||
new("person", 0.95f, 100f, 200f, 50f, 80f)
|
||||
};
|
||||
|
||||
var a = new FrameAnalysisResult("img1", detections, 10);
|
||||
var b = new FrameAnalysisResult("img2", detections, 10);
|
||||
|
||||
(a != b).ShouldBeTrue();
|
||||
a.Equals(b).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonSerialization_Roundtrip_PreservesValues()
|
||||
{
|
||||
var original = new FrameAnalysisResult("dGVzdA==", SampleDetections, 123);
|
||||
var json = JsonSerializer.Serialize(original);
|
||||
var deserialized = JsonSerializer.Deserialize<FrameAnalysisResult>(json);
|
||||
|
||||
deserialized.ShouldNotBeNull();
|
||||
deserialized.ImageBase64.ShouldBe(original.ImageBase64);
|
||||
deserialized.ProcessingMs.ShouldBe(original.ProcessingMs);
|
||||
deserialized.Detections.Count.ShouldBe(original.Detections.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessingMs_IsMeasurementDuration()
|
||||
{
|
||||
var result = new FrameAnalysisResult("data", SampleDetections, 0);
|
||||
result.ProcessingMs.ShouldBe(0);
|
||||
|
||||
result = new FrameAnalysisResult("data", SampleDetections, long.MaxValue);
|
||||
result.ProcessingMs.ShouldBe(long.MaxValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ImageBase64_HoldsEncodedImageData()
|
||||
{
|
||||
var imageBytes = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 };
|
||||
var base64 = Convert.ToBase64String(imageBytes);
|
||||
var result = new FrameAnalysisResult(base64, SampleDetections, 5);
|
||||
|
||||
result.ImageBase64.ShouldBe(base64);
|
||||
Convert.FromBase64String(result.ImageBase64).ShouldBe(imageBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Detections_AreReadOnly()
|
||||
{
|
||||
var result = new FrameAnalysisResult("data", SampleDetections, 1);
|
||||
result.Detections.ShouldBeAssignableTo<IReadOnlyList<DetectionResult>>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class FrameAnalyzerServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_WhenModelNotFound_DoesNotThrow()
|
||||
{
|
||||
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
|
||||
service.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnalyzeFrameAsync_WhenPassthrough_ReturnsNull()
|
||||
{
|
||||
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
|
||||
var result = await service.AnalyzeFrameAsync([1, 2, 3]);
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnalyzeFrame_WhenPassthrough_ReturnsNull()
|
||||
{
|
||||
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
|
||||
var result = service.AnalyzeFrame([1, 2, 3]);
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnalyzeFrameAsync_EmptyArray_ReturnsNull()
|
||||
{
|
||||
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
|
||||
var result = await service.AnalyzeFrameAsync([]);
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnalyzeFrameAsync_LargeBuffer_ReturnsNull()
|
||||
{
|
||||
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
|
||||
var result = await service.AnalyzeFrameAsync(new byte[1024 * 1024]);
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_MultipleTimes_DoesNotThrow()
|
||||
{
|
||||
var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
|
||||
service.Dispose();
|
||||
service.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnalyzeFrameAsync_AfterDispose_ReturnsNull()
|
||||
{
|
||||
var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
|
||||
service.Dispose();
|
||||
var result = await service.AnalyzeFrameAsync([1, 2, 3]);
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnalyzeFrameAsync_ConcurrentCalls_DoNotThrow()
|
||||
{
|
||||
using var service = new FrameAnalyzerService(Substitute.For<ILogger<FrameAnalyzerService>>());
|
||||
var tasks = Enumerable.Range(0, 10)
|
||||
.Select(_ => service.AnalyzeFrameAsync([1, 2, 3]))
|
||||
.ToArray();
|
||||
var results = await Task.WhenAll(tasks);
|
||||
results.ShouldAllBe(r => r == null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System.Text.Json;
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class HeartbeatRequestTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_WithAllValues_SetsProperties()
|
||||
{
|
||||
var request = new HeartbeatRequest(
|
||||
PublicIp: "1.2.3.4",
|
||||
IsOffline: true,
|
||||
CpuUsagePercent: 45.5,
|
||||
MemoryUsageBytes: 1024L * 1024 * 512,
|
||||
DiskUsagePercent: 67.8,
|
||||
UptimeSeconds: 3600);
|
||||
|
||||
request.PublicIp.ShouldBe("1.2.3.4");
|
||||
request.IsOffline.ShouldBeTrue();
|
||||
request.CpuUsagePercent.ShouldBe(45.5);
|
||||
request.MemoryUsageBytes.ShouldBe(1024L * 1024 * 512);
|
||||
request.DiskUsagePercent.ShouldBe(67.8);
|
||||
request.UptimeSeconds.ShouldBe(3600);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WithDefaults_HasCorrectDefaults()
|
||||
{
|
||||
var request = new HeartbeatRequest(null);
|
||||
|
||||
request.PublicIp.ShouldBeNull();
|
||||
request.IsOffline.ShouldBeFalse();
|
||||
request.CpuUsagePercent.ShouldBeNull();
|
||||
request.MemoryUsageBytes.ShouldBeNull();
|
||||
request.DiskUsagePercent.ShouldBeNull();
|
||||
request.UptimeSeconds.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WithOnlyPublicIp_SetsPublicIpOnly()
|
||||
{
|
||||
var request = new HeartbeatRequest("192.168.1.1");
|
||||
|
||||
request.PublicIp.ShouldBe("192.168.1.1");
|
||||
request.IsOffline.ShouldBeFalse();
|
||||
request.CpuUsagePercent.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonSerialization_UsesSnakeCasePropertyNames()
|
||||
{
|
||||
var request = new HeartbeatRequest("10.0.0.1", IsOffline: true, CpuUsagePercent: 50.0);
|
||||
var json = JsonSerializer.Serialize(request);
|
||||
|
||||
json.ShouldContain("publicIp");
|
||||
json.ShouldContain("isOffline");
|
||||
json.ShouldContain("cpuUsagePercent");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonSerializeDeserialize_Roundtrip_PreservesValues()
|
||||
{
|
||||
var original = new HeartbeatRequest("10.0.0.1", IsOffline: false, CpuUsagePercent: 75.2,
|
||||
MemoryUsageBytes: 123456789, DiskUsagePercent: 42.0, UptimeSeconds: 99999);
|
||||
var json = JsonSerializer.Serialize(original);
|
||||
var deserialized = JsonSerializer.Deserialize<HeartbeatRequest>(json);
|
||||
|
||||
deserialized.ShouldNotBeNull();
|
||||
deserialized.PublicIp.ShouldBe(original.PublicIp);
|
||||
deserialized.IsOffline.ShouldBe(original.IsOffline);
|
||||
deserialized.CpuUsagePercent.ShouldBe(original.CpuUsagePercent);
|
||||
deserialized.MemoryUsageBytes.ShouldBe(original.MemoryUsageBytes);
|
||||
deserialized.DiskUsagePercent.ShouldBe(original.DiskUsagePercent);
|
||||
deserialized.UptimeSeconds.ShouldBe(original.UptimeSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonDeserialize_MissingFields_GetsDefaults()
|
||||
{
|
||||
var json = """{"publicIp": "10.0.0.1"}""";
|
||||
var request = JsonSerializer.Deserialize<HeartbeatRequest>(json);
|
||||
|
||||
request.ShouldNotBeNull();
|
||||
request.PublicIp.ShouldBe("10.0.0.1");
|
||||
request.IsOffline.ShouldBeFalse();
|
||||
request.CpuUsagePercent.ShouldBeNull();
|
||||
request.MemoryUsageBytes.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_SameValues_AreEqual()
|
||||
{
|
||||
var a = new HeartbeatRequest("1.2.3.4", true, 50.0, 1024, 30.0, 3600);
|
||||
var b = new HeartbeatRequest("1.2.3.4", true, 50.0, 1024, 30.0, 3600);
|
||||
|
||||
(a == b).ShouldBeTrue();
|
||||
a.Equals(b).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_DifferentValues_AreNotEqual()
|
||||
{
|
||||
var a = new HeartbeatRequest("1.2.3.4");
|
||||
var b = new HeartbeatRequest("5.6.7.8");
|
||||
|
||||
(a != b).ShouldBeTrue();
|
||||
a.Equals(b).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JsonSerialize_NullableFields_AreSerializedAsNull()
|
||||
{
|
||||
var request = new HeartbeatRequest(null);
|
||||
var json = JsonSerializer.Serialize(request);
|
||||
|
||||
json.ShouldContain("null");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class RetryDelayedTests
|
||||
{
|
||||
[Fact]
|
||||
public void NextRetryDelay_ReturnsSpecifiedDelaysInOrder()
|
||||
{
|
||||
var retry = new RetryDelayed(
|
||||
TimeSpan.FromSeconds(1),
|
||||
TimeSpan.FromSeconds(5),
|
||||
TimeSpan.FromSeconds(30));
|
||||
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = 0 })
|
||||
.ShouldBe(TimeSpan.FromSeconds(1));
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = 1 })
|
||||
.ShouldBe(TimeSpan.FromSeconds(5));
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = 2 })
|
||||
.ShouldBe(TimeSpan.FromSeconds(30));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextRetryDelay_AfterExhaustingDelays_ReturnsSixtySeconds()
|
||||
{
|
||||
var retry = new RetryDelayed(TimeSpan.FromSeconds(1));
|
||||
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = 1 })
|
||||
.ShouldBe(TimeSpan.FromSeconds(60));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextRetryDelay_WithNoDelays_AlwaysReturnsSixtySeconds()
|
||||
{
|
||||
var retry = new RetryDelayed();
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = i })
|
||||
.ShouldBe(TimeSpan.FromSeconds(60));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextRetryDelay_WithSingleDelay_ReturnsFallbackAfterExhaustion()
|
||||
{
|
||||
var retry = new RetryDelayed(TimeSpan.FromMilliseconds(500));
|
||||
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = 0 })
|
||||
.ShouldBe(TimeSpan.FromMilliseconds(500));
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = 1 })
|
||||
.ShouldBe(TimeSpan.FromSeconds(60));
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = 100 })
|
||||
.ShouldBe(TimeSpan.FromSeconds(60));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextRetryDelay_LargeRetryCount_DoesNotOverflow()
|
||||
{
|
||||
var retry = new RetryDelayed(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
|
||||
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = int.MaxValue })
|
||||
.ShouldBe(TimeSpan.FromSeconds(60));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextRetryDelay_AtExactBoundary_WorksCorrectly()
|
||||
{
|
||||
var retry = new RetryDelayed(TimeSpan.FromSeconds(1));
|
||||
|
||||
// PreviousRetryCount == _delays.Length → exhausted, returns 60s
|
||||
retry.NextRetryDelay(new RetryContext { PreviousRetryCount = 1 })
|
||||
.ShouldBe(TimeSpan.FromSeconds(60));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NextRetryDelay_ContextWithReason_StillReturnsCorrectDelay()
|
||||
{
|
||||
var retry = new RetryDelayed(TimeSpan.FromSeconds(3));
|
||||
|
||||
var context = new RetryContext
|
||||
{
|
||||
PreviousRetryCount = 0
|
||||
};
|
||||
|
||||
retry.NextRetryDelay(context).ShouldBe(TimeSpan.FromSeconds(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class SystemInfoTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetPhysicalMemory_ReturnsNonNegativeValue()
|
||||
{
|
||||
var mem = SystemInfo.GetPhysicalMemory();
|
||||
mem.ShouldBeGreaterThanOrEqualTo(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPhysicalMemory_OnNonMacOS_FallsBackToZero()
|
||||
{
|
||||
// On non-macOS platforms, sysctl may not exist → returns 0
|
||||
// On macOS with sysctl working, returns actual memory
|
||||
var mem = SystemInfo.GetPhysicalMemory();
|
||||
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
// Should return actual physical memory (> 0)
|
||||
mem.ShouldBeGreaterThan(0);
|
||||
}
|
||||
// On Linux returns 0 because sysctl either doesn't exist or hw.memsize is unknown
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPhysicalMemory_CalledMultipleTimes_DoesNotThrow()
|
||||
{
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
var mem = SystemInfo.GetPhysicalMemory();
|
||||
mem.ShouldBeGreaterThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class SystemMetricsProviderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_ReturnsNonNullSnapshot()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
var metrics = provider.Collect();
|
||||
metrics.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_UptimeSeconds_IsNonNegative()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
var metrics = provider.Collect();
|
||||
metrics.UptimeSeconds.ShouldNotBeNull();
|
||||
metrics.UptimeSeconds.Value.ShouldBeGreaterThanOrEqualTo(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_MemoryUsageBytes_IsNonNegative()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
var metrics = provider.Collect();
|
||||
metrics.MemoryUsageBytes.ShouldNotBeNull();
|
||||
metrics.MemoryUsageBytes.Value.ShouldBeGreaterThanOrEqualTo(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_TotalMemoryBytes_MayBeNull()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
var metrics = provider.Collect();
|
||||
// On Linux /proc/meminfo exists, on other platforms it may be null
|
||||
if (OperatingSystem.IsLinux())
|
||||
metrics.TotalMemoryBytes.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_DiskUsagePercent_MayBeNull()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
var metrics = provider.Collect();
|
||||
// On Linux with a valid drive it returns a value
|
||||
if (!OperatingSystem.IsLinux())
|
||||
metrics.DiskUsagePercent.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_CpuUsagePercent_MayBeNull()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
// First call within <500ms of construction returns null
|
||||
var metrics = provider.Collect();
|
||||
// Acceptable to be null (too soon for delta or non-Linux)
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_CalledTenTimes_DoesNotThrow()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
var metrics = provider.Collect();
|
||||
metrics.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_WithDelay_CpuUsageMayBecomeAvailable()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
provider.Collect(); // First call, sets baseline
|
||||
|
||||
Thread.Sleep(600); // Wait >500ms for a meaningful delta
|
||||
|
||||
var metrics = provider.Collect();
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
// If /proc/stat is available, CPU should now have a value
|
||||
// It could still be null if parsing fails somehow
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_MultipleSnapshots_HaveConsistentStructure()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
var first = provider.Collect();
|
||||
var second = provider.Collect();
|
||||
|
||||
first.UptimeSeconds.ShouldNotBeNull();
|
||||
second.UptimeSeconds.ShouldNotBeNull();
|
||||
first.UptimeSeconds.Value.ShouldBeLessThanOrEqualTo(second.UptimeSeconds.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_DiskUsage_IsBetweenZeroAndOneHundred()
|
||||
{
|
||||
var provider = new SystemMetricsProvider();
|
||||
var metrics = provider.Collect();
|
||||
if (metrics.DiskUsagePercent.HasValue)
|
||||
{
|
||||
metrics.DiskUsagePercent.Value.ShouldBeGreaterThanOrEqualTo(0);
|
||||
metrics.DiskUsagePercent.Value.ShouldBeLessThanOrEqualTo(100);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user