diff --git a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs index 1d6375d..59c8f31 100644 --- a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs +++ b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs @@ -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(); diff --git a/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs new file mode 100644 index 0000000..ffa7b2f --- /dev/null +++ b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs @@ -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>()); + service.ActiveStreamCount.ShouldBe(0); + } + + [Fact] + public async Task StartStreamAsync_FfmpegNotFound_ReturnsFalse() + { + using var service = new CameraStreamService(Substitute.For>()); + 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>()); + 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>()); + await service.StopStreamAsync(Guid.NewGuid()); + } + + [Fact] + public async Task ActiveStreamCount_AfterMultipleStarts_RemainsZero() + { + using var service = new CameraStreamService(Substitute.For>()); + 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>()); + service.Dispose(); + service.Dispose(); + } + + [Fact] + public async Task StartStreamAsync_EmptyRtspUrl_ReturnsFalse() + { + using var service = new CameraStreamService(Substitute.For>()); + 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>()); + await service.StartStreamAsync(Guid.NewGuid(), "rtsp://localhost:8554/test", CancellationToken.None); + service.ActiveStreamCount.ShouldBe(0); + } +} diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs new file mode 100644 index 0000000..23f6e87 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -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>(); + var httpFactory = Substitute.For(); + 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); + } +} diff --git a/tests/Heimdall.Agent.Tests/DetectionResultTests.cs b/tests/Heimdall.Agent.Tests/DetectionResultTests.cs new file mode 100644 index 0000000..1170055 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/DetectionResultTests.cs @@ -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(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); + } +} diff --git a/tests/Heimdall.Agent.Tests/FrameAnalysisResultTests.cs b/tests/Heimdall.Agent.Tests/FrameAnalysisResultTests.cs new file mode 100644 index 0000000..df5e3bb --- /dev/null +++ b/tests/Heimdall.Agent.Tests/FrameAnalysisResultTests.cs @@ -0,0 +1,103 @@ +using System.Text.Json; +using Heimdall.Agent.Services; + +namespace Heimdall.Agent.Tests; + +public class FrameAnalysisResultTests +{ + private static readonly IReadOnlyList 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 + { + 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 + { + 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(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>(); + } +} diff --git a/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs b/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs new file mode 100644 index 0000000..1118a45 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/FrameAnalyzerServiceTests.cs @@ -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>()); + service.ShouldNotBeNull(); + } + + [Fact] + public async Task AnalyzeFrameAsync_WhenPassthrough_ReturnsNull() + { + using var service = new FrameAnalyzerService(Substitute.For>()); + var result = await service.AnalyzeFrameAsync([1, 2, 3]); + result.ShouldBeNull(); + } + + [Fact] + public void AnalyzeFrame_WhenPassthrough_ReturnsNull() + { + using var service = new FrameAnalyzerService(Substitute.For>()); + var result = service.AnalyzeFrame([1, 2, 3]); + result.ShouldBeNull(); + } + + [Fact] + public async Task AnalyzeFrameAsync_EmptyArray_ReturnsNull() + { + using var service = new FrameAnalyzerService(Substitute.For>()); + var result = await service.AnalyzeFrameAsync([]); + result.ShouldBeNull(); + } + + [Fact] + public async Task AnalyzeFrameAsync_LargeBuffer_ReturnsNull() + { + using var service = new FrameAnalyzerService(Substitute.For>()); + var result = await service.AnalyzeFrameAsync(new byte[1024 * 1024]); + result.ShouldBeNull(); + } + + [Fact] + public void Dispose_MultipleTimes_DoesNotThrow() + { + var service = new FrameAnalyzerService(Substitute.For>()); + service.Dispose(); + service.Dispose(); + } + + [Fact] + public async Task AnalyzeFrameAsync_AfterDispose_ReturnsNull() + { + var service = new FrameAnalyzerService(Substitute.For>()); + 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>()); + var tasks = Enumerable.Range(0, 10) + .Select(_ => service.AnalyzeFrameAsync([1, 2, 3])) + .ToArray(); + var results = await Task.WhenAll(tasks); + results.ShouldAllBe(r => r == null); + } +} diff --git a/tests/Heimdall.Agent.Tests/HeartbeatRequestTests.cs b/tests/Heimdall.Agent.Tests/HeartbeatRequestTests.cs new file mode 100644 index 0000000..a79b91e --- /dev/null +++ b/tests/Heimdall.Agent.Tests/HeartbeatRequestTests.cs @@ -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(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(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"); + } +} diff --git a/tests/Heimdall.Agent.Tests/RetryDelayedTests.cs b/tests/Heimdall.Agent.Tests/RetryDelayedTests.cs new file mode 100644 index 0000000..fa34028 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/RetryDelayedTests.cs @@ -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)); + } +} diff --git a/tests/Heimdall.Agent.Tests/SystemInfoTests.cs b/tests/Heimdall.Agent.Tests/SystemInfoTests.cs new file mode 100644 index 0000000..d79bca8 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/SystemInfoTests.cs @@ -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); + } + } +} diff --git a/tests/Heimdall.Agent.Tests/SystemMetricsProviderTests.cs b/tests/Heimdall.Agent.Tests/SystemMetricsProviderTests.cs new file mode 100644 index 0000000..8f5ecd5 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/SystemMetricsProviderTests.cs @@ -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); + } + } +}