Files
Heimdall/tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs
T
Arnaud Dartois 2678009444 fix(test): List_pending déterministe — cible l'IP exacte au lieu de FirstAsync() non ordonné
FirstAsync() sans ORDER BY n'est pas stable entre providers (SQLite local
vs PostgreSQL CI) : le test List_pending_should_return_only_unprocessed_results
échouait en CI quand le premier résultat retourné était 192.168.1.11 au
lieu de 192.168.1.10. On marque maintenant explicitement l'IP à rejeter.
2026-08-11 16:27:35 +02:00

281 lines
12 KiB
C#

using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Services;
using Heimdall.Infrastructure.Services.Discovery;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
namespace Heimdall.Infrastructure.Tests;
public class AgentDiscoveryServiceTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly IOnvifProbeService _onvif = Substitute.For<IOnvifProbeService>();
private readonly ICredentialProtector _protector = Substitute.For<ICredentialProtector>();
private readonly ILogger<CameraDiscoveryService> _logger = Substitute.For<ILogger<CameraDiscoveryService>>();
public AgentDiscoveryServiceTests()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
_dbFactory = CreateFactory(_connection);
_protector.Encrypt(Arg.Any<string>()).Returns(c => $"enc_{c.Arg<string>()}");
_protector.Decrypt(Arg.Any<string>()).Returns(c => (c.Arg<string>() ?? "").Replace("enc_", ""));
}
public void Dispose()
{
_connection?.Close();
_connection?.Dispose();
GC.SuppressFinalize(this);
}
private static TestDbContextFactory CreateFactory(SqliteConnection connection)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
using var ctx = new AppDbContext(opts, new AuditInterceptor());
ctx.Database.EnsureCreated();
return new TestDbContextFactory(opts);
}
private CameraDiscoveryService CreateService() => new(
_dbFactory, _onvif,
Substitute.For<IMdnsProbeService>(),
Substitute.For<IHttpProbeService>(),
Substitute.For<IArpProbeService>(),
Substitute.For<IPortScanService>(),
new StreamTesterService(Substitute.For<IHttpClientFactory>(), Substitute.For<ILogger<StreamTesterService>>()),
_protector, _logger);
private async Task<(Guid SiteId, Guid AgentId)> SeedSiteAndAgentAsync(string siteName = "Site A")
{
await using var db = await _dbFactory.CreateDbContextAsync();
var site = new Site(siteName);
var agent = new Agent(site.Id, "Agent 1", "host1", "1.0.0");
db.Sites.Add(site);
db.Agents.Add(agent);
await db.SaveChangesAsync();
return (site.Id, agent.Id);
}
private static AgentDiscoveredDevice Device(string ip, params int[] ports) => new(
ip, true, ports, "AA:BB:CC:DD:EE:FF", null, null, null, null, null,
null, null, null, ports.Contains(3702) ? 3702 : null, null, null, null);
// ─── Submit ────────────────────────────────────────────────────
[Fact]
public async Task Submit_new_devices_should_create_discovery_results()
{
var (siteId, agentId) = await SeedSiteAndAgentAsync();
var service = CreateService();
var result = await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80, 554)], CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Received.ShouldBe(1);
result.Data.New.ShouldBe(1);
result.Data.Updated.ShouldBe(0);
await using var db = await _dbFactory.CreateDbContextAsync();
var saved = await db.CameraDiscoveryResults.SingleAsync();
saved.ShouldNotBeNull();
saved.SiteId.ShouldBe(siteId);
saved.IpAddress.ShouldBe("192.168.1.10");
saved.MacAddress.ShouldBe("AA:BB:CC:DD:EE:FF");
saved.IsProcessed.ShouldBeFalse();
saved.OpenPorts.ShouldBe([80, 554]);
}
[Fact]
public async Task Submit_same_ip_should_update_not_duplicate()
{
var (_, agentId) = await SeedSiteAndAgentAsync();
var service = CreateService();
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80)], CancellationToken.None);
var result = await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80, 554)], CancellationToken.None);
result.Data.ShouldNotBeNull();
result.Data.New.ShouldBe(0);
result.Data.Updated.ShouldBe(1);
await using var db = await _dbFactory.CreateDbContextAsync();
db.CameraDiscoveryResults.Count().ShouldBe(1);
var savedAgain = await db.CameraDiscoveryResults.SingleAsync();
savedAgain.ShouldNotBeNull();
savedAgain.OpenPorts.ShouldBe([80, 554]);
}
[Fact]
public async Task Submit_unknown_agent_should_not_found()
{
var service = CreateService();
var result = await service.SubmitAgentDiscoveriesAsync(Guid.NewGuid(), [Device("192.168.1.10", 80)], CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
[Fact]
public async Task Submit_should_persist_agent_enriched_onvif_and_mark_credential_used()
{
var (siteId, agentId) = await SeedSiteAndAgentAsync();
await using (var seedDb = await _dbFactory.CreateDbContextAsync())
{
seedDb.SiteCredentials.Add(new SiteCredential(siteId, "admin", "admin", _protector.Encrypt("secret")));
await seedDb.SaveChangesAsync();
}
var service = CreateService();
// The agent is on the camera network: it already performed the authenticated
// ONVIF enrichment (OnvifName = manufacturer, OnvifHardware = model) and
// reports which credential label succeeded. The Central only persists.
var device = new AgentDiscoveredDevice(
"192.168.1.10", true, [3702], "3C:EF:8C:12:34:56", null, null, null, null, null,
"http://192.168.1.10/onvif/device_service", "Hikvision", "DS-2CD2T47", 3702,
null, null, null, CredentialLabel: "admin");
await service.SubmitAgentDiscoveriesAsync(agentId, [device], CancellationToken.None);
await using var db = await _dbFactory.CreateDbContextAsync();
var saved = await db.CameraDiscoveryResults.Include(r => r.DiscoveredStreams).SingleAsync();
saved.OnvifHardware.ShouldBe("DS-2CD2T47");
saved.OnvifName.ShouldBe("Hikvision");
saved.Vendor.ShouldBe("hikvision"); // normalisé depuis le fabricant ONVIF remonté par l'agent
saved.OnvifDeviceServiceUrl.ShouldBe("http://192.168.1.10/onvif/device_service");
saved.DiscoveredStreams.Count.ShouldBeGreaterThan(0);
var cred = await db.SiteCredentials.SingleAsync();
cred.LastUsedAt.ShouldNotBeNull(); // marqué via CredentialLabel remonté par l'agent
}
[Fact]
public async Task Submit_should_not_call_onvif_probe_on_central()
{
// The Central is not on the camera network: it must never probe ONVIF
// itself for agent-submitted devices (authenticated enrichment is the
// agent's job). Persisting raw data without enrichment must not throw.
var (_, agentId) = await SeedSiteAndAgentAsync();
var service = CreateService();
var device = Device("192.168.1.10", 3702);
var result = await service.SubmitAgentDiscoveriesAsync(agentId, [device], CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
await _onvif.DidNotReceiveWithAnyArgs().ProbeWithCredentialsAsync(
Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
await _onvif.DidNotReceiveWithAnyArgs().ProbeDeviceServiceAsync(
Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Submit_should_build_candidate_stream_urls()
{
var (_, agentId) = await SeedSiteAndAgentAsync();
var service = CreateService();
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.20", 554)], CancellationToken.None);
await using var db = await _dbFactory.CreateDbContextAsync();
var saved = await db.CameraDiscoveryResults.Include(r => r.DiscoveredStreams).SingleAsync();
saved.DiscoveredStreams.Select(s => s.Url).ShouldContain(u => u.Contains("192.168.1.20"));
}
// ─── List pending ─────────────────────────────────────────────
[Fact]
public async Task List_pending_should_return_only_unprocessed_results()
{
var (siteId, agentId) = await SeedSiteAndAgentAsync();
var service = CreateService();
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80), Device("192.168.1.11", 80)], CancellationToken.None);
// Reject one of them — target the exact IP so the assertion below is
// deterministic (FirstAsync() without ORDER BY is not stable across
// providers: SQLite local vs PostgreSQL CI).
await using (var db = await _dbFactory.CreateDbContextAsync())
{
var toReject = await db.CameraDiscoveryResults.FirstAsync(r => r.IpAddress == "192.168.1.10");
toReject.MarkProcessed();
await db.SaveChangesAsync();
}
var result = await service.ListPendingDiscoveriesAsync(siteId, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(1);
result.Data[0].IpAddress.ShouldBe("192.168.1.11");
result.Data.ShouldNotContain(d => d.IpAddress == "192.168.1.10");
}
[Fact]
public async Task List_pending_unknown_site_returns_empty()
{
var service = CreateService();
var result = await service.ListPendingDiscoveriesAsync(Guid.NewGuid(), CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeEmpty();
}
// ─── Reject ───────────────────────────────────────────────────
[Fact]
public async Task Reject_should_mark_result_processed()
{
var (_, agentId) = await SeedSiteAndAgentAsync();
var service = CreateService();
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80)], CancellationToken.None);
await using (var db = await _dbFactory.CreateDbContextAsync())
{
var saved = await db.CameraDiscoveryResults.SingleAsync();
var result = await service.RejectDiscoveryAsync(saved.Id, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
}
await using var db2 = await _dbFactory.CreateDbContextAsync();
(await db2.CameraDiscoveryResults.SingleAsync()).IsProcessed.ShouldBeTrue();
}
[Fact]
public async Task Reject_already_processed_should_not_found()
{
var (_, agentId) = await SeedSiteAndAgentAsync();
var service = CreateService();
await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80)], CancellationToken.None);
await using (var db = await _dbFactory.CreateDbContextAsync())
{
var saved = await db.CameraDiscoveryResults.SingleAsync();
saved.ShouldNotBeNull();
await service.RejectDiscoveryAsync(saved.Id, CancellationToken.None);
var result = await service.RejectDiscoveryAsync(saved.Id, CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
}
}
private sealed class TestDbContextFactory(DbContextOptions<AppDbContext> opts)
: IDbContextFactory<AppDbContext>
{
private static readonly AuditInterceptor Audit = new();
public AppDbContext CreateDbContext() => new(opts, Audit);
public Task<AppDbContext> CreateDbContextAsync(CancellationToken ct = default)
=> Task.FromResult(new AppDbContext(opts, Audit));
}
}