Files
Febe/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs
T

224 lines
8.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
namespace Febe.Tests.Browser.TestSupport;
/// <summary>
/// Tiny local site served by the test itself on 127.0.0.1 (never Instagram): one port plays the site, another the CDN.
/// </summary>
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, "<p>Cookie impostato</p>");
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 => $"<p>Riga {i} di una pagina lunga.</p>"))
+ "<script>window.__wheel = { count: 0, trusted: true };"
+ "addEventListener('wheel', (e) => { window.__wheel.count++; window.__wheel.trusted = window.__wheel.trusted && e.isTrusted; }, { passive: true });</script>",
"/bottoni" => """
<div style="height:3000px;position:relative">
<button id="b1" aria-label="Indietro" style="position:absolute;left:100px;top:100px;width:120px;height:40px">‹</button>
<button id="b2" aria-label="Avanti" style="position:absolute;left:400px;top:300px;width:160px;height:50px">›</button>
<button id="b3" aria-label="Avanti" style="display:none">nascosto</button>
<a id="l1" href="/profilo/alice/" style="position:absolute;left:100px;top:500px">alice</a>
<a id="l2" href="/stories/alice/123/" style="position:absolute;left:300px;top:500px"><span>Storia di alice</span></a>
<button id="b4" aria-label="Coperto" style="position:absolute;left:700px;top:100px;width:100px;height:40px">x</button>
<div style="position:absolute;left:690px;top:90px;width:140px;height:70px;background:#ddd"></div>
<button id="b5" style="position:absolute;left:400px;top:2400px;width:120px;height:40px">Lontano</button>
</div>
<script>
window.__clicks = [];
window.__moves = 0;
document.addEventListener('mousemove', () => { window.__moves++; });
document.addEventListener('click', (e) => {
const t = e.target.closest('[id]');
window.__clicks.push({ id: t ? t.id : '', x: e.clientX, y: e.clientY, trusted: e.isTrusted });
});
</script>
""",
"/cattura" => "<p>Cattura</p><script>addEventListener('load', () => fetch('/api/dati.json').then((r) => r.json()).then(() => { document.title = 'caricato'; }));</script>",
"/cattura-429" => "<p>Troppe</p><script>addEventListener('load', () => fetch('/api/troppe').then((r) => r.text()));</script>",
"/cattura-attendi" => "<p>Attendi</p><script>addEventListener('load', () => fetch('/api/attendi.json').then((r) => r.json()));</script>",
"/animata" => """
<style>@keyframes giro { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
#q { width: 200px; height: 200px; margin: 100px; background: #c63; animation: giro 1s linear infinite; }</style>
<div id="q"></div>
""",
"/modulo" => """
<input id="campo" aria-label="Campo" style="position:absolute;left:200px;top:200px;width:300px;height:30px">
<script>
window.__keys = 0;
window.__clicks = 0;
document.addEventListener('keydown', () => { window.__keys++; });
document.addEventListener('mousedown', () => { window.__clicks++; });
</script>
""",
"/spa" => "<p>Applicazione</p><script>addEventListener('load', () => setTimeout(() => history.pushState({}, '', '/verifica/interna?x=1'), 300));</script>",
"/verifica" => "<h1>Verifica</h1>",
"/accesso" => "<h1>Accesso</h1>",
_ => "<p>Pagina di prova</p>",
};
private static Task HtmlAsync(HttpListenerResponse response, string body) =>
WriteAsync(response, 200, "text/html; charset=utf-8", $"<!doctype html><html lang=\"it\"><head><meta charset=\"utf-8\"><title>Prova</title></head><body>{body}</body></html>");
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);
}
}