The 7 failing test files used IDbContextFactory<AppDbContext> for a field that's always initialized with TestDbContextFactory. Narrowing to the concrete type satisfies the analyzer and matches the pattern already used in 5 other tests in the same folder. Fixes: AgentFailoverJobTests, BusinessEntityPersistenceTests, AnalysisJobDispatcherJobTests, AnalysisJobSchedulerServiceTests, AgentDiscoveryServiceTests, CameraAssignmentServiceTests, CameraEventServiceTests
285 lines
12 KiB
C#
285 lines
12 KiB
C#
using Heimdall.Application.Common;
|
|
using Heimdall.Application.Discovery;
|
|
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 Microsoft.Extensions.Logging.Abstractions;
|
|
using NSubstitute;
|
|
using Shouldly;
|
|
|
|
namespace Heimdall.Infrastructure.Tests;
|
|
|
|
public class AgentDiscoveryServiceTests : IDisposable
|
|
{
|
|
private readonly SqliteConnection _connection;
|
|
private readonly TestDbContextFactory _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,
|
|
new SqliteCameraDatabase(NullLogger<SqliteCameraDatabase>.Instance),
|
|
_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", 554)], 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", 554), Device("192.168.1.11", 554)], 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", 554)], 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", 554)], 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));
|
|
}
|
|
}
|