Files
Heimdall/tests/Heimdall.Infrastructure.Tests/Services/NotificationServiceTests.cs
T
Arnaud Dartois 45ce41ce7e fix(deps): CVE bloquantes Trivy — AutoMapper 16.1.1, OpenApi 10.0.11, Newtonsoft 13, SQLitePCLRaw 2.1.13 (#128)
## Contexte
Trivy (bloquant) détecte 4 CVE HIGH dans les images PR. Ces vulnérabilités sont dans la base du projet (pas liées aux PR #117/#118) → PR dédiée.

## Changements
- **AutoMapper 13.0.1 → 16.1.1** (CVE-2026-32933) : AddAutoMapper passe par cfg.AddMaps(assembly) (v16 : plus de surcharge Assembly) ; MapperConfiguration des tests → constructeur 2 args (NullLoggerFactory.Instance).
- **Microsoft.AspNetCore.OpenApi 10.0.8 → 10.0.11** (CVE-2026-49451) : tire Microsoft.OpenApi 2.7.5.
- **Newtonsoft.Json 13.0.1** en référence directe (CVE-2024-21907, transitif 11.0.1 forcé).
- **SQLitePCLRaw.bundle_e_sqlite3 2.1.13** en référence directe (CVE-2025-6965, transitif 2.1.11 forcé).

## Tickets liés
Fixes #127

## Résultats des tests
- dotnet build Heimdall.slnx -c Release : 0 erreur, 0 warning
- Application.Tests (Mapping + NotificationHandler) : 22/22
- Infrastructure.Tests (NotificationServiceTests, Testcontainers) : 10/10

## SonarQube
À valider sur la CI (gate bloquant).

## CVE
Corrigées par les bumps ci-dessus (à confirmer par Trivy sur le run).

## Checklist
- [x] PR par ticket
- [x] Build + tests locaux verts
- [ ] CI verte (Trivy sans HIGH/CRITICAL)
- [ ] Sonar gate OK

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/128
2026-08-15 09:11:25 +02:00

296 lines
10 KiB
C#

using AutoMapper;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Notifications.Mapping;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Services;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Shouldly;
namespace Heimdall.Infrastructure.Tests.Services;
/// <summary>
/// Unit tests for <see cref="NotificationService"/>.
/// Uses SQLite in-memory for real EF Core behavior with mocked external channels.
/// </summary>
public class NotificationServiceTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly AppDbContext _context;
private readonly IMapper _mapper;
private readonly INotificationBroadcastService _broadcast;
private readonly IEmailService _emailService;
private readonly INtfyService _ntfyService;
private readonly INotificationRateLimiter _rateLimiter;
private readonly ILogger<NotificationService> _logger;
private readonly NotificationService _service;
public NotificationServiceTests()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(_connection)
.Options;
_context = new AppDbContext(opts, new AuditInterceptor());
_context.Database.EnsureCreated();
// Real AutoMapper with the actual notification mapping profile
// (v16 : constructeur 2 args — ILoggerFactory requis)
var mapperConfig = new MapperConfiguration(cfg =>
cfg.AddProfile<NotificationMappingProfile>(), NullLoggerFactory.Instance);
_mapper = mapperConfig.CreateMapper();
_broadcast = Substitute.For<INotificationBroadcastService>();
_emailService = Substitute.For<IEmailService>();
_ntfyService = Substitute.For<INtfyService>();
_rateLimiter = Substitute.For<INotificationRateLimiter>();
_logger = Substitute.For<ILogger<NotificationService>>();
_service = new NotificationService(
_context, _mapper, _broadcast, _emailService, _ntfyService,
_rateLimiter, _logger);
}
public void Dispose()
{
_context.Dispose();
_connection.Close();
_connection?.Dispose();
GC.SuppressFinalize(this);
}
[Fact]
public async Task CreateNotificationAsync_ShouldAddAndBroadcast()
{
// Arrange
var userId = Guid.NewGuid();
_rateLimiter.ShouldSend(Arg.Any<Guid>(), Arg.Any<EventType>(), Arg.Any<Guid?>())
.Returns(true);
// Act
var result = await _service.CreateNotificationAsync(
userId, "Test Title", "Test message", NotificationType.Info,
EventType.PersonDetected, Guid.NewGuid());
// Assert
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Title.ShouldBe("Test Title");
result.Data.UserId.ShouldBe(userId);
// Verify broadcast was called
await _broadcast.Received(1).NotifyNewNotification(
Arg.Is<NotificationDto>(d => d!.Title == "Test Title"),
Arg.Any<CancellationToken>());
// Verify it was persisted
var count = await _context.Notifications.CountAsync();
count.ShouldBe(1);
}
[Fact]
public async Task CreateNotificationAsync_RateLimited_ShouldSkipSilently()
{
// Arrange
_rateLimiter.ShouldSend(Arg.Any<Guid>(), Arg.Any<EventType>(), Arg.Any<Guid?>())
.Returns(false);
// Act
var result = await _service.CreateNotificationAsync(
Guid.NewGuid(), "Test", "Message", NotificationType.Info,
EventType.PersonDetected, Guid.NewGuid());
// Assert
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeNull(); // Silently skipped
// Nothing should be persisted
var count = await _context.Notifications.CountAsync();
count.ShouldBe(0);
// No broadcast should happen
await _broadcast.DidNotReceiveWithAnyArgs().NotifyNewNotification(default!, default);
}
[Fact]
public async Task GetUnreadCountAsync_ShouldReturnCount()
{
// Arrange
var userId = Guid.NewGuid();
// Seed notifications directly in the database
_context.Notifications.Add(new Notification(userId, "Unread1", "Msg", NotificationType.Info));
_context.Notifications.Add(new Notification(userId, "Unread2", "Msg", NotificationType.Info));
var readNotification = new Notification(userId, "Read", "Msg", NotificationType.Info);
readNotification.MarkAsRead();
_context.Notifications.Add(readNotification);
await _context.SaveChangesAsync();
// Act
var count = await _service.GetUnreadCountAsync(userId);
// Assert
count.ShouldBe(2);
}
[Fact]
public async Task GetUnreadCountAsync_OtherUsers_NotCounted()
{
// Arrange
var userId = Guid.NewGuid();
var otherUserId = Guid.NewGuid();
_context.Notifications.Add(new Notification(userId, "Mine", "Msg", NotificationType.Info));
_context.Notifications.Add(new Notification(otherUserId, "Theirs", "Msg", NotificationType.Info));
await _context.SaveChangesAsync();
// Act
var count = await _service.GetUnreadCountAsync(userId);
// Assert
count.ShouldBe(1);
}
[Fact]
public async Task CreateNotificationAsync_WithoutRateLimiter_ShouldWork()
{
// Arrange
var userId = Guid.NewGuid();
// cameraId is null, so rate limiter is skipped entirely
// Act
var result = await _service.CreateNotificationAsync(
userId, "No Cam", "Message", NotificationType.Alert,
eventType: null, cameraId: null);
// Assert
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Type.ShouldBe(NotificationType.Alert.ToString());
// Broadcast should still be called
await _broadcast.Received(1).NotifyNewNotification(
Arg.Any<NotificationDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task MarkAsReadAsync_ExistingNotification_MarksItRead()
{
// Arrange
var userId = Guid.NewGuid();
var notification = new Notification(userId, "Read Test", "Msg", NotificationType.Info);
_context.Notifications.Add(notification);
await _context.SaveChangesAsync();
notification.IsRead.ShouldBeFalse();
// Act
await _service.MarkAsReadAsync(notification.Id, userId);
// Assert
var updated = await _context.Notifications.FindAsync(notification.Id);
updated.ShouldNotBeNull();
updated.IsRead.ShouldBeTrue();
updated.ReadAt.ShouldNotBeNull();
}
[Fact]
public async Task MarkAsReadAsync_OtherUsersNotification_DoesNothing()
{
// Arrange
var ownerId = Guid.NewGuid();
var otherUserId = Guid.NewGuid();
var notification = new Notification(ownerId, "Not Mine", "Msg", NotificationType.Info);
_context.Notifications.Add(notification);
await _context.SaveChangesAsync();
// Act
await _service.MarkAsReadAsync(notification.Id, otherUserId);
// Assert — should NOT mark as read since it belongs to another user
var updated = await _context.Notifications.FindAsync(notification.Id);
updated.ShouldNotBeNull();
updated.IsRead.ShouldBeFalse();
}
[Fact]
public async Task MarkAllAsReadAsync_MarksAllUserNotifications()
{
// Arrange
var userId = Guid.NewGuid();
_context.Notifications.Add(new Notification(userId, "A", "Msg", NotificationType.Info));
_context.Notifications.Add(new Notification(userId, "B", "Msg", NotificationType.Warning));
_context.Notifications.Add(new Notification(Guid.NewGuid(), "Other", "Msg", NotificationType.Info));
await _context.SaveChangesAsync();
// Act
await _service.MarkAllAsReadAsync(userId);
// Assert
var userUnread = await _context.Notifications
.CountAsync(n => n.UserId == userId && !n.IsRead);
userUnread.ShouldBe(0);
// Other user's notification should remain unread
var otherUnread = await _context.Notifications
.CountAsync(n => n.UserId != userId && !n.IsRead);
otherUnread.ShouldBe(1);
}
[Fact]
public async Task GetNotificationsAsync_ShouldReturnPagedResults()
{
// Arrange
var userId = Guid.NewGuid();
for (int i = 0; i < 5; i++)
{
_context.Notifications.Add(new Notification(userId, $"Title {i}", $"Msg {i}", NotificationType.Info));
}
await _context.SaveChangesAsync();
// Act
var result = await _service.GetNotificationsAsync(userId, null, page: 1, pageSize: 3);
// Assert
result.Items.Count.ShouldBe(3);
result.TotalCount.ShouldBe(5);
result.Page.ShouldBe(1);
result.TotalPages.ShouldBe(2);
result.HasNextPage.ShouldBeTrue();
result.HasPreviousPage.ShouldBeFalse();
}
[Fact]
public async Task GetNotificationsAsync_FilterByRead_ReturnsFiltered()
{
// Arrange
var userId = Guid.NewGuid();
var n1 = new Notification(userId, "Unread", "Msg", NotificationType.Info);
var n2 = new Notification(userId, "Read", "Msg", NotificationType.Info);
n2.MarkAsRead();
_context.Notifications.Add(n1);
_context.Notifications.Add(n2);
await _context.SaveChangesAsync();
// Act
var unread = await _service.GetNotificationsAsync(userId, isRead: false, page: 1, pageSize: 20);
var read = await _service.GetNotificationsAsync(userId, isRead: true, page: 1, pageSize: 20);
// Assert
unread.Items.Count.ShouldBe(1);
unread.TotalCount.ShouldBe(1);
read.Items.Count.ShouldBe(1);
read.TotalCount.ShouldBe(1);
}
}