Files
Arnaud Dartois 249c4ef0de
Heimdall Gitea / Build and tests (pull_request) Successful in 31m9s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
fix: scope email digests to accessible camera events
2026-10-21 18:59:50 +02:00

131 lines
5.6 KiB
C#

using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Jobs;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Shouldly;
namespace Heimdall.Infrastructure.Tests;
public sealed class DigestJobTests : IDisposable
{
private readonly SqliteConnection _connection = new("DataSource=:memory:");
private readonly TestDbContextFactory _dbFactory;
public DigestJobTests()
{
_connection.Open();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(_connection)
.Options;
using var db = new AppDbContext(options, new AuditInterceptor());
db.Database.EnsureCreated();
_dbFactory = new TestDbContextFactory(options);
}
public void Dispose()
{
_connection.Dispose();
GC.SuppressFinalize(this);
}
[Fact]
public async Task DailyDigest_UsesUtcDayAndOnlyAccessibleCameraEvents()
{
var (userId, allowedCameraId, otherCameraId, email) = await SeedUserAndCamerasAsync(daily: true, weekly: false);
var now = DateTime.UtcNow;
var todayStart = now.Date;
await AddEventAsync(allowedCameraId, todayStart.AddMinutes(1));
await AddEventAsync(allowedCameraId, todayStart.AddTicks(-1));
await AddEventAsync(allowedCameraId, now.AddHours(1));
await AddEventAsync(otherCameraId, todayStart.AddMinutes(2));
var access = Substitute.For<ICameraAccessService>();
access.GetUserAccessibleCameraIdsAsync(userId, Arg.Any<CancellationToken>())
.Returns(Task.FromResult(new List<Guid> { allowedCameraId }));
var emailService = Substitute.For<IEmailService>();
var job = new DailyDigestJob(_dbFactory, emailService, access, NullLogger<DailyDigestJob>.Instance);
await job.ExecuteAsync();
await emailService.Received(1).SendEmailAsync(
email, Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
var emailArguments = emailService.ReceivedCalls().Single().GetArguments();
((string)emailArguments[1]!).ShouldContain("quotidien");
((string)emailArguments[2]!).ShouldContain("aujourd'hui (UTC)");
((string)emailArguments[2]!).ShouldContain("<strong>1</strong>");
await access.Received(1).GetUserAccessibleCameraIdsAsync(userId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task WeeklyDigest_UsesRollingSevenDayWindowAndOnlyAccessibleCameraEvents()
{
var (userId, allowedCameraId, otherCameraId, email) = await SeedUserAndCamerasAsync(daily: false, weekly: true);
var now = DateTime.UtcNow;
await AddEventAsync(allowedCameraId, now.AddDays(-1));
await AddEventAsync(allowedCameraId, now.AddDays(-8));
await AddEventAsync(allowedCameraId, now.AddHours(1));
await AddEventAsync(otherCameraId, now.AddDays(-1));
var access = Substitute.For<ICameraAccessService>();
access.GetUserAccessibleCameraIdsAsync(userId, Arg.Any<CancellationToken>())
.Returns(Task.FromResult(new List<Guid> { allowedCameraId }));
var emailService = Substitute.For<IEmailService>();
var job = new WeeklyDigestJob(_dbFactory, emailService, access, NullLogger<WeeklyDigestJob>.Instance);
await job.ExecuteAsync();
await emailService.Received(1).SendEmailAsync(
email, Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
var emailArguments = emailService.ReceivedCalls().Single().GetArguments();
((string)emailArguments[1]!).ShouldContain("hebdomadaire");
((string)emailArguments[2]!).ShouldContain("7 derniers jours (UTC)");
((string)emailArguments[2]!).ShouldContain("<strong>1</strong>");
await access.Received(1).GetUserAccessibleCameraIdsAsync(userId, Arg.Any<CancellationToken>());
}
private async Task<(Guid UserId, Guid AllowedCameraId, Guid OtherCameraId, string Email)> SeedUserAndCamerasAsync(
bool daily,
bool weekly)
{
var userId = Guid.NewGuid();
const string email = "digest@example.test";
await using var db = await _dbFactory.CreateDbContextAsync();
var site = new Site("Digest site");
db.Sites.Add(site);
await db.SaveChangesAsync();
var allowedCamera = new Camera(site.Id, "Allowed camera");
var otherCamera = new Camera(site.Id, "Other camera");
db.Cameras.AddRange(allowedCamera, otherCamera);
var config = new UserNotificationConfig(userId);
config.UpdateEmail(email, enabled: true);
config.UpdateDigests(daily, weekly);
db.UserNotificationConfigs.Add(config);
await db.SaveChangesAsync();
return (userId, allowedCamera.Id, otherCamera.Id, email);
}
private async Task AddEventAsync(Guid cameraId, DateTime occurredAt)
{
await using var db = await _dbFactory.CreateDbContextAsync();
db.CameraEvents.Add(new CameraEvent(cameraId, EventType.MotionDetected, 0.9, occurredAt));
await db.SaveChangesAsync();
}
private sealed class TestDbContextFactory(DbContextOptions<AppDbContext> options)
: IDbContextFactory<AppDbContext>
{
private static readonly AuditInterceptor Audit = new();
public AppDbContext CreateDbContext() => new(options, Audit);
public Task<AppDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default)
=> Task.FromResult(new AppDbContext(options, Audit));
}
}