using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Library;
using Febe.Server;
using Febe.SitoDiProva;
using Febe.Tests.Browser.TestSupport;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Server.Support;
///
/// The real server composition () against the local test site, with Xvfb and a real Chromium,
/// in a temporary Data/Library/Import folder, on free ports and a free display. Never Instagram: the browser only ever
/// sees 127.0.0.1. Time runs on a compressed clock (10×) in a time zone where it is around noon now, so that the
/// engine is inside its active window whatever the hour of the test.
///
internal sealed class ServerTestBed : IAsyncDisposable
{
public const string Password = "una password di prova per il server";
private ServerTestBed(TempFolder temp, TestSite site, FebeServer server, CompressedClock clock, ServerOptions options)
{
Temp = temp;
Site = site;
Server = server;
Clock = clock;
Options = options;
Client = new HttpClient(new HttpClientHandler { UseCookies = true, CookieContainer = Cookies, AllowAutoRedirect = false })
{
BaseAddress = server.Address,
Timeout = TimeSpan.FromSeconds(30),
};
}
public TempFolder Temp { get; }
public TestSite Site { get; }
public FebeServer Server { get; }
public CompressedClock Clock { get; }
public ServerOptions Options { get; }
public CookieContainer Cookies { get; } = new();
public HttpClient Client { get; }
/// «http://127.0.0.1:port»: the Origin of requests coming from the interface.
public string Origin => $"{Server.Address.Scheme}://{Server.Address.Authority}";
public static string? UnavailableReason() => RealBrowser.UnavailableReason();
public static async Task StartAsync(bool autoLogin = false, double factor = 10, HttpMessageHandler? telegram = null, IFreeSpaceProbe? freeSpace = null)
{
var temp = new TempFolder("server");
var site = await SyntheticSite.StartAsync();
var zone = NoonZone();
var clock = new CompressedClock(factor, zone);
var options = new ServerOptions
{
Password = Password,
ListenAddress = IPAddress.Loopback,
Port = 0,
ZoneId = zone.Id,
Zone = zone,
Language = "it_IT.UTF-8",
DataFolder = temp.Combine("dati"),
LibraryFolder = temp.Combine("libreria"),
ImportFolder = temp.Combine("importa"),
NoSandbox = RealBrowser.IsRoot,
ChromiumPath = RealBrowser.ChromiumPath(),
DebugPort = LocalTestSite.FreePort(),
Display = XvfbProcess.FindFreeDisplay(300, 399) ?? throw new InvalidOperationException("Nessun display libero."),
TestSite = new Uri(site.SiteUrl + "/"),
TestCdn = new Uri(site.CdnUrl + "/"),
TestSiteAutoLogin = autoLogin,
FirstSessionDelay = TimeSpan.FromSeconds(1),
};
Directory.CreateDirectory(options.ImportFolder);
FebeServer server;
try
{
server = await FebeServer.StartAsync(options, new ServerHooks { Clock = clock, Random = new SeededRandom(20261013), Console = TextWriter.Null, TelegramHandler = telegram, FreeSpace = freeSpace });
}
catch
{
await site.DisposeAsync();
temp.Dispose();
throw;
}
return new ServerTestBed(temp, site, server, clock, options);
}
///
/// A fixed-offset zone where the local time is between 12:00 and 13:00 now: inside the active window of every
/// caution profile, so the test does not depend on when it runs.
///
public static TimeZoneInfo NoonZone()
{
var offset = 12 - DateTimeOffset.UtcNow.Hour;
if (offset > 12)
{
offset -= 24;
}
else if (offset < -12)
{
offset += 24;
}
// The sign of the Etc/GMT names is inverted: Etc/GMT-2 is two hours east of Greenwich.
var id = offset == 0 ? "Etc/GMT" : offset > 0 ? $"Etc/GMT-{offset}" : $"Etc/GMT+{-offset}";
return TimeZoneInfo.FindSystemTimeZoneById(id);
}
/// Logs in with the interface password (cookie in ).
public async Task LoginAsync()
{
using var response = await SendAsync(HttpMethod.Post, "/api/accesso", $$"""{"password":"{{Password}}"}""");
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync());
}
/// A request as the interface sends it: Origin of the interface, JSON body.
public async Task SendAsync(HttpMethod method, string path, string? json = null)
{
using var request = new HttpRequestMessage(method, path);
request.Headers.TryAddWithoutValidation("Origin", Origin);
if (json is not null)
{
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
return await Client.SendAsync(request);
}
public async Task JsonAsync(HttpMethod method, string path, string? json = null)
{
using var response = await SendAsync(method, path, json);
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
/// The remote view, opened like the Browser page does: session cookie and Origin of the interface.
public async Task OpenRemoteViewAsync(CancellationToken ct)
{
var socket = new ClientWebSocket();
socket.Options.Cookies = Cookies;
socket.Options.SetRequestHeader("Origin", Origin);
var address = new UriBuilder(Server.Address) { Scheme = "ws", Path = "/api/vista" }.Uri;
await socket.ConnectAsync(address, ct);
return socket;
}
public LibraryLayout Library => Server.Library ?? throw new InvalidOperationException("Nessuna libreria.");
public ThumbnailStore Thumbnails => new(Server.Data!.Thumbnails);
/// Waits (real time) until holds; fails with otherwise.
public static async Task WaitUntilAsync(Func> condition, TimeSpan timeout, string what)
{
var deadline = DateTime.UtcNow + timeout;
while (true)
{
if (await condition())
{
return;
}
if (DateTime.UtcNow > deadline)
{
Assert.Fail($"Tempo scaduto: {what}.");
}
await Task.Delay(250);
}
}
public async ValueTask DisposeAsync()
{
Client.Dispose();
await Server.DisposeAsync();
await Site.DisposeAsync();
Temp.Dispose();
}
}