Files
Febe/tests/Febe.Tests/Browser/TestSupport/LocalTestSite.cs
T
Alby96andClaude Opus 5.5 c4c035d61f
verifica / controlli (push) Successful in 29s
verifica / prove (push) Successful in 15m0s
verifica / installatore (push) Successful in 4m36s
verifica / immagine (push) Successful in 14m52s
Porte delle prove fuori dall'intervallo effimero (#52)
Nella CI 350 Chromium non è partito: la porta di debug, presa dalla porta 0
del sistema e chiusa prima dell'avvio, era nell'intervallo effimero di Linux
e un'altra prova parallela l'aveva occupata nel frattempo. FreePort dà ora
porte fra 20000 e 29999, una volta sola per processo e provate prima di
darle; anche DesktopCompositionTests usa lo stesso aiuto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:12:08 +01:00

260 lines
11 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}";
/// <summary>The same site under the name «localhost»: another site for Chromium, so another renderer.</summary>
public string LocalhostUrl(string path) => $"http://localhost:{SitePort}{path}";
public string CdnUrl(string path) => $"http://{CdnHost}{path}";
// Ports handed out by FreePort come from 20000-29999: below the ephemeral ranges of Linux (32768-60999) and Windows
// (49152-65535), so an outgoing connection of another test cannot take one between the probe and the moment the
// test binds it (a port handed out by the system's port 0 could, CI run 350 of #52). Each port is handed out once
// per process; the start depends on the process id, so two test processes on one machine rarely meet.
private const int FirstTestPort = 20000;
private const int TestPorts = 10000;
private static int _nextPort = Environment.ProcessId * 7919 % TestPorts;
/// <summary>
/// A port of 127.0.0.1 that is free now, never handed out before in this process and outside the system's ephemeral
/// range. The caller binds it soon after; nothing can reserve it in between, but no other test of this process gets
/// it and no outgoing connection is given it.
/// </summary>
public static int FreePort()
{
for (var attempt = 0; attempt < TestPorts; attempt++)
{
var port = FirstTestPort + (int)((uint)Interlocked.Increment(ref _nextPort) % TestPorts);
var probe = new TcpListener(IPAddress.Loopback, port);
try
{
probe.Start();
}
catch (SocketException)
{
continue;
}
finally
{
probe.Stop();
}
return port;
}
throw new InvalidOperationException("Nessuna porta libera fra 20000 e 29999.");
}
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>",
// Keeps its renderer busy for 2 s, from 0.1 s after it has committed: a navigation away from it to a page of the
// same site (same renderer) reaches «ready to commit» at once but commits only when the script lets go.
"/occupata" => "<p>Occupata</p><script>setTimeout(() => { const end = performance.now() + 2000; while (performance.now() < end) { } }, 100);</script>",
_ => "<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);
}
}