using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
namespace Febe.Tests.Browser.TestSupport;
///
/// Tiny local site served by the test itself on 127.0.0.1 (never Instagram): one port plays the site, another the CDN.
///
public sealed class LocalTestSite : IDisposable
{
public const int BigFileBytes = 24 * 1024 * 1024;
private static readonly Lazy<(byte[] Bytes, string Sha256)> BigFile = new(() =>
{
var bytes = new byte[BigFileBytes];
new Random(20261013).NextBytes(bytes);
return (bytes, Convert.ToHexString(SHA256.HashData(bytes)));
});
private readonly HttpListener _listener = new();
private readonly CancellationTokenSource _stop = new();
public LocalTestSite()
{
SitePort = FreePort();
CdnPort = FreePort();
_listener.Prefixes.Add($"http://127.0.0.1:{SitePort}/");
_listener.Prefixes.Add($"http://127.0.0.1:{CdnPort}/");
_listener.Start();
_ = Task.Run(LoopAsync);
}
public int SitePort { get; }
public int CdnPort { get; }
public string SiteHost => $"127.0.0.1:{SitePort}";
public string CdnHost => $"127.0.0.1:{CdnPort}";
public static string BigFileSha256 => BigFile.Value.Sha256;
public string Url(string path) => $"http://{SiteHost}{path}";
public string CdnUrl(string path) => $"http://{CdnHost}{path}";
public static int FreePort()
{
var probe = new TcpListener(IPAddress.Loopback, 0);
probe.Start();
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
probe.Stop();
return port;
}
private int _disposed;
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
_stop.Cancel();
try
{
_listener.Stop();
_listener.Close();
}
catch (ObjectDisposedException)
{
}
_stop.Dispose();
}
private async Task LoopAsync()
{
while (!_stop.IsCancellationRequested)
{
HttpListenerContext context;
try
{
context = await _listener.GetContextAsync();
}
catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or InvalidOperationException)
{
return;
}
_ = Task.Run(() => HandleAsync(context));
}
}
private async Task HandleAsync(HttpListenerContext context)
{
var response = context.Response;
try
{
var path = context.Request.Url!.AbsolutePath;
if (context.Request.Url.Port == CdnPort)
{
if (path == "/file.bin")
{
response.ContentType = "application/octet-stream";
response.ContentLength64 = BigFile.Value.Bytes.Length;
await response.OutputStream.WriteAsync(BigFile.Value.Bytes);
}
else
{
response.StatusCode = 404;
}
return;
}
switch (path)
{
case "/api/dati.json":
await JsonAsync(response, 200, """{"elementi":[{"id":"1","testo":"ciao"},{"id":"2","testo":"mondo"}]}""");
return;
case "/api/troppe":
await JsonAsync(response, 429, """{"messaggio":"troppe richieste"}""");
return;
case "/api/attendi.json":
await JsonAsync(response, 200, """{"messaggio":"Attendi qualche minuto prima di riprovare."}""");
return;
case "/vai-a-verifica":
response.StatusCode = 302;
response.RedirectLocation = "/verifica?da=prova";
return;
case "/cookie":
response.AppendHeader("Set-Cookie", "sessionid=valore-finto-di-prova; Path=/; Max-Age=86400; SameSite=Lax");
await HtmlAsync(response, "
Cookie impostato
");
return;
default:
await HtmlAsync(response, Page(path));
return;
}
}
catch (Exception ex) when (ex is HttpListenerException or IOException or ObjectDisposedException)
{
}
finally
{
try
{
response.Close();
}
catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException or InvalidOperationException)
{
}
}
}
private static string Page(string path) => path switch
{
"/lunga" => string.Concat(Enumerable.Range(1, 300).Select(i => $"Riga {i} di una pagina lunga.
"))
+ "",
"/bottoni" => """
""",
"/cattura" => "Cattura
",
"/cattura-429" => "Troppe
",
"/cattura-attendi" => "Attendi
",
"/animata" => """
""",
"/modulo" => """
""",
"/spa" => "Applicazione
",
"/verifica" => "Verifica
",
"/accesso" => "Accesso
",
_ => "Pagina di prova
",
};
private static Task HtmlAsync(HttpListenerResponse response, string body) =>
WriteAsync(response, 200, "text/html; charset=utf-8", $"Prova{body}");
private static Task JsonAsync(HttpListenerResponse response, int status, string json) =>
WriteAsync(response, status, "application/json; charset=utf-8", json);
private static async Task WriteAsync(HttpListenerResponse response, int status, string contentType, string body)
{
var bytes = Encoding.UTF8.GetBytes(body);
response.StatusCode = status;
response.ContentType = contentType;
response.ContentLength64 = bytes.Length;
response.AddHeader("Cache-Control", "no-store");
await response.OutputStream.WriteAsync(bytes);
}
}