Files
Heimdall/tests/Heimdall.Infrastructure.Tests/Services/NotificationRateLimiterTests.cs
T

97 lines
2.9 KiB
C#
Raw Normal View History

using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Services;
using Microsoft.Extensions.Caching.Memory;
using Shouldly;
namespace Heimdall.Infrastructure.Tests.Services;
public class NotificationRateLimiterTests
{
private readonly NotificationRateLimiter _limiter;
public NotificationRateLimiterTests()
{
var cache = new MemoryCache(new MemoryCacheOptions());
_limiter = new NotificationRateLimiter(cache);
}
[Fact]
public void ShouldSend_FirstEvent_ReturnsTrue()
{
var result = _limiter.ShouldSend(Guid.NewGuid(), EventType.PersonDetected, null);
result.ShouldBeTrue();
}
[Fact]
public void ShouldSend_WithinLimit_ReturnsTrue()
{
var cameraId = Guid.NewGuid();
// Send 19 events (20 is the limit per minute)
for (int i = 0; i < 19; i++)
{
_limiter.ShouldSend(cameraId, EventType.PersonDetected, null).ShouldBeTrue();
}
}
[Fact]
public void ShouldSend_ExceedsLimit_ReturnsFalse()
{
var cameraId = Guid.NewGuid();
// Send 20 events (limit reached)
for (int i = 0; i < 20; i++)
{
_limiter.ShouldSend(cameraId, EventType.PersonDetected, null);
}
// 21st should be rate limited
var result = _limiter.ShouldSend(cameraId, EventType.PersonDetected, null);
result.ShouldBeFalse();
}
[Fact]
public void ShouldSend_DifferentTypes_HaveSeparateCounters()
{
var cameraId = Guid.NewGuid();
// Exhaust limit for PersonDetected
for (int i = 0; i < 20; i++)
_limiter.ShouldSend(cameraId, EventType.PersonDetected, null);
// MotionDetected should still work (separate counter)
var result = _limiter.ShouldSend(cameraId, EventType.MotionDetected, null);
result.ShouldBeTrue();
}
[Fact]
public void ShouldSend_DifferentCameras_HaveSeparateCounters()
{
var camera1 = Guid.NewGuid();
var camera2 = Guid.NewGuid();
// Exhaust limit for camera1
for (int i = 0; i < 20; i++)
_limiter.ShouldSend(camera1, EventType.PersonDetected, null);
// camera2 should still work
var result = _limiter.ShouldSend(camera2, EventType.PersonDetected, null);
result.ShouldBeTrue();
}
[Fact]
public void ShouldSend_WithTrackId_ShouldBeTracked()
{
var cameraId = Guid.NewGuid();
var trackId = Guid.NewGuid();
for (int i = 0; i < 20; i++)
_limiter.ShouldSend(cameraId, EventType.PersonDetected, trackId);
// Same camera+type+track should be limited
_limiter.ShouldSend(cameraId, EventType.PersonDetected, trackId).ShouldBeFalse();
// Same camera+type, different track should still work
_limiter.ShouldSend(cameraId, EventType.PersonDetected, Guid.NewGuid()).ShouldBeTrue();
}
}