using System.Net; using Heimdall.Infrastructure.Services.Discovery; using Microsoft.Extensions.Logging; using NSubstitute; using Shouldly; namespace Heimdall.Infrastructure.Tests; public class OnvifProbeServiceTests { private readonly ILogger _logger = Substitute.For>(); private readonly IHttpClientFactory _httpClientFactory = Substitute.For(); [Fact] public void Constructor_CreatesService() { var service = new OnvifProbeService(_httpClientFactory, _logger); service.ShouldNotBeNull(); } [Fact] public async Task ProbeDeviceService_with_credentials_should_send_ws_security_header() { string? capturedBody = null; var handler = new StubHttpMessageHandler(request => { capturedBody = request.Content?.ReadAsStringAsync().GetAwaiter().GetResult(); const string soapResponse = """ Hikvision DS-2CD2T47 """; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(soapResponse, System.Text.Encoding.UTF8, "application/soap+xml") }; }); _httpClientFactory.CreateClient("Discovery").Returns(new HttpClient(handler)); var service = new OnvifProbeService(_httpClientFactory, _logger); var result = await service.ProbeDeviceServiceAsync( "http://192.168.1.10/onvif/device_service", "admin", "secret", CancellationToken.None); result.ShouldNotBeNull(); result.Name.ShouldBe("Hikvision"); result.Hardware.ShouldBe("DS-2CD2T47"); capturedBody.ShouldNotBeNull(); capturedBody.ShouldContain(""); capturedBody.ShouldContain("admin"); capturedBody.ShouldContain("PasswordDigest"); } [Fact] public async Task ProbeDeviceService_without_credentials_should_send_no_security_header() { string? capturedBody = null; var handler = new StubHttpMessageHandler(request => { capturedBody = request.Content?.ReadAsStringAsync().GetAwaiter().GetResult(); const string soapResponse = """ Axis M3085 """; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(soapResponse, System.Text.Encoding.UTF8, "application/soap+xml") }; }); _httpClientFactory.CreateClient("Discovery").Returns(new HttpClient(handler)); var service = new OnvifProbeService(_httpClientFactory, _logger); var result = await service.ProbeDeviceServiceAsync( "http://192.168.1.11/onvif/device_service", null, null, CancellationToken.None); result.ShouldNotBeNull(); result.Name.ShouldBe("Axis"); capturedBody.ShouldNotBeNull(); capturedBody.ShouldNotContain("Security"); } /// HttpMessageHandler stub for capturing request bodies. private sealed class StubHttpMessageHandler(Func responder) : HttpMessageHandler { protected override Task SendAsync( HttpRequestMessage request, CancellationToken ct) => Task.FromResult(responder(request)); } }