using System.Net; using System.Net.Sockets; using System.Text; using Microsoft.Extensions.DependencyInjection; using Titano.Protocol; using Titano.Server.Api; using Titano.Server.Hosting; using Titano.Testing; namespace Titano.Server.Tests.Hosting; [Category("server")] public sealed class DiscoveryTests(TestContext context) { [Test] public async Task TheBeaconTravelsOverUdpAndParses() { await using var server = await TestServer.StartAsync(context, o => o.ServerName = "Studio NAS"); var service = server.Services.GetRequiredService(); using var listener = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0)); using var sender = new UdpClient(AddressFamily.InterNetwork); await service.SendOnceAsync(sender, [(IPEndPoint)listener.Client.LocalEndPoint!], context.Cancellation); var datagram = await listener.ReceiveAsync(context.Cancellation).AsTask().WaitAsync(TimeSpan.FromSeconds(5)); var beacon = Assert.NotNull(DiscoveryBeacon.TryParse(datagram.Buffer)); Assert.Equal("Studio NAS", beacon.Name); Assert.Equal(SystemEndpoints.Version, beacon.Version); Assert.Equal(server.HttpBase.Port, beacon.HttpPort); Assert.Equal(server.HttpsBase!.Port, beacon.HttpsPort); using var info = await server.Client.GetAsync("/api/v1/server/info"); Assert.Equal((await info.ReadAsync(ProtocolJson.Default.ServerInfo)).TlsFingerprint, beacon.TlsFingerprint); } [Test] public void ForeignDatagramsAreIgnored() { Assert.Null(DiscoveryBeacon.TryParse(Encoding.UTF8.GetBytes("HELLO {}"))); Assert.Null(DiscoveryBeacon.TryParse(Encoding.UTF8.GetBytes("TITANO1 {not json"))); Assert.Null(DiscoveryBeacon.TryParse(new byte[4096])); } }