70 lines
2.1 KiB
C#
70 lines
2.1 KiB
C#
using System.Net;
|
|||
|
|
using System.Net.Sockets;
|
||
|
|
using Heimdall.Infrastructure.Services.Discovery;
|
||
|
|
using Microsoft.Extensions.Logging;
|
||
|
|
using NSubstitute;
|
||
|
|
using Shouldly;
|
||
|
|
|
||
|
|
namespace Heimdall.Infrastructure.Tests;
|
||
|
|
|
||
|
|
public class HttpProbeServiceTests
|
||
|
|
{
|
||
|
|
private readonly ILogger<HttpProbeService> _logger = Substitute.For<ILogger<HttpProbeService>>();
|
||
|
|
private readonly IHttpClientFactory _httpClientFactory = Substitute.For<IHttpClientFactory>();
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public async Task ProbeAsync_AllPortsClosed_ReturnsNull()
|
||
|
|
{
|
||
|
|
var handler = new SimpleMockHttpHandler(_ =>
|
||
|
|
throw new HttpRequestException("No response",
|
||
|
|
new SocketException((int)SocketError.ConnectionRefused)));
|
||
|
|
|
||
|
|
var client = new HttpClient(handler);
|
||
|
|
_httpClientFactory.CreateClient("Discovery").Returns(client);
|
||
|
|
|
||
|
|
var service = new HttpProbeService(_httpClientFactory, _logger);
|
||
|
|
var result = await service.ProbeAsync("192.168.1.100");
|
||
|
|
|
||
|
|
result.ShouldBeNull();
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public async Task ProbeAsync_Timeout_ReturnsNull()
|
||
|
|
{
|
||
|
|
var handler = new SimpleMockHttpHandler(_ =>
|
||
|
|
{
|
||
|
|
throw new TaskCanceledException();
|
||
|
|
});
|
||
|
|
|
||
|
|
var client = new HttpClient(handler);
|
||
|
|
_httpClientFactory.CreateClient("Discovery").Returns(client);
|
||
|
|
|
||
|
|
var service = new HttpProbeService(_httpClientFactory, _logger);
|
||
|
|
var result = await service.ProbeAsync("192.168.1.100");
|
||
|
|
|
||
|
|
result.ShouldBeNull();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
internal sealed class SimpleMockHttpHandler : HttpMessageHandler
|
||
|
|
{
|
||
|
|
private readonly Func<HttpRequestMessage, HttpResponseMessage> _handler;
|
||
|
|
|
||
|
|
public SimpleMockHttpHandler(Func<HttpRequestMessage, HttpResponseMessage> handler)
|
||
|
|
{
|
||
|
|
_handler = handler;
|
||
|
|
}
|
||
|
|
|
||
|
|
protected override Task<HttpResponseMessage> SendAsync(
|
||
|
|
HttpRequestMessage request, CancellationToken cancellationToken)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
return Task.FromResult(_handler(request));
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
return Task.FromException<HttpResponseMessage>(ex);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|