Files
Febe/tests/Febe.Tests/Web/Support/WebTestServer.cs
T
Claude e33540246e Interfaccia web, parte 1: ospite, sicurezza, API, modalità dimostrativa, libreria, visualizzatore e account
Febe.Web: AddFebeWeb/UseFebe/FebeWebHost per le due vesti, interfaccia incorporata con IFileProvider proprio, indirizzi italiani, API JSON con contesto generato, eventi SSE, controlli di Host/Origin, gettone del desktop e password con blocco (§13.1), INativeShell e capacità per veste. Modalità --demo con 38 account e circa 18.000 elementi finti e scene del motore. Pagine Libreria, Visualizzatore, Account, Aggiungi account e Scheda account (contenuti, impostazioni con piano, cronologia); schermate in docs/schermate con le differenze dai mockup; prove delle API, della sicurezza, dell'esportazione CSV e dei dati dimostrativi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
2026-10-13 19:14:35 +00:00

158 lines
6.3 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
using Febe.Web;
using Febe.Web.Library;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web.Support;
/// <summary>
/// Febe.Web on a real Kestrel listening on 127.0.0.1 with a free port (no test server package needed), with a
/// temporary database and library, and an HttpClient pointed at it.
/// </summary>
internal sealed class WebTestServer : IAsyncDisposable
{
private WebTestServer(TempFolder temp, FebeDatabase db, FebeLibrary library, ManualClock clock, WebApplication app, Uri address)
{
Temp = temp;
Db = db;
Library = library;
Clock = clock;
App = app;
Address = address;
Client = NewClient();
}
public TempFolder Temp { get; }
public FebeDatabase Db { get; }
public FebeLibrary Library { get; }
public ManualClock Clock { get; }
public WebApplication App { get; }
public Uri Address { get; }
/// <summary>A client without cookies of its own (each test decides what to send).</summary>
public HttpClient Client { get; }
/// <summary>«http://127.0.0.1:port», the value of Origin for requests coming from the interface.</summary>
public string Origin => $"{Address.Scheme}://{Address.Authority}";
public LibraryChanges Changes => App.Services.GetRequiredService<LibraryChanges>();
public static async Task<WebTestServer> StartAsync(FebeWebOptions? options = null, Action<IServiceCollection>? services = null)
{
var temp = new TempFolder("web");
var db = await FebeDatabase.OpenAsync(temp.Combine("dati"));
var clock = new ManualClock(Make.T0);
var library = new FebeLibrary(db, new DataFolderLayout(temp.Combine("dati")), new LibraryLayout(temp.Combine("libreria")), clock);
options ??= new FebeWebOptions { Access = AccessMode.None };
options = options with { AllowedHosts = options.AllowedHosts.Count == 0 ? FebeWebOptions.LoopbackHosts(0) : options.AllowedHosts };
var app = FebeWebHost.Build(options, FebeListen.Loopback(0), s =>
{
s.AddSingleton<IFebeStorage>(db);
s.AddSingleton(library);
s.AddSingleton<IClock>(clock);
services?.Invoke(s);
});
await app.StartAsync();
return new WebTestServer(temp, db, library, clock, app, FebeWebHost.BoundAddress(app));
}
public HttpClient NewClient(bool cookies = false, bool redirects = false)
{
var handler = new HttpClientHandler { AllowAutoRedirect = redirects, UseCookies = cookies, CookieContainer = new CookieContainer() };
return new HttpClient(handler) { BaseAddress = Address, Timeout = TimeSpan.FromSeconds(30) };
}
/// <summary>A request as the interface sends it (Origin of the interface on commands).</summary>
public HttpRequestMessage Request(HttpMethod method, string path, object? body = null, string? origin = "")
{
var request = new HttpRequestMessage(method, path);
if (body is not null)
{
request.Content = new StringContent(body as string ?? JsonSerializer.Serialize(body, Json), Encoding.UTF8, "application/json");
}
if (origin is not null)
{
request.Headers.TryAddWithoutValidation("Origin", origin.Length == 0 ? Origin : origin);
}
return request;
}
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
public async Task<JsonElement> GetJsonAsync(string path)
{
using var response = await Client.GetAsync(path);
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
public async Task<(HttpStatusCode Status, JsonElement Body)> SendJsonAsync(HttpMethod method, string path, object? body = null)
{
using var request = Request(method, path, body);
using var response = await Client.SendAsync(request);
var text = await response.Content.ReadAsStringAsync();
var json = text.Length > 0 && (response.Content.Headers.ContentType?.MediaType?.Contains("json", StringComparison.Ordinal) ?? false)
? JsonDocument.Parse(text).RootElement.Clone()
: default;
return (response.StatusCode, json);
}
/// <summary>Adds an account with a few stored entries spread over days (no files on disk).</summary>
public async Task<Account> AddAccountWithEntriesAsync(string username, int entries, DateTimeOffset newest, TimeSpan step, EntryKind kind = EntryKind.Post, string? caption = null)
{
var account = await Db.Accounts.AddAsync(Make.Account(username));
var items = new List<NewEntry>();
for (var i = 0; i < entries; i++)
{
var media = Make.Stored(kind == EntryKind.Story ? Make.Video() : Make.Photo(), Make.Sha((1000 * username.Length) + i + 1), $"post/{username}-{i}.jpg");
items.Add(new NewEntry(Make.Entry(account.Id, $"{username}-{i}", newest - (step * i), kind, caption) with { State = EntryState.Downloaded }, [media]));
}
await Db.Entries.AddManyAsync(items);
return account;
}
public async ValueTask DisposeAsync()
{
Client.Dispose();
await App.StopAsync();
await App.DisposeAsync();
await Db.DisposeAsync();
Temp.Dispose();
}
}
/// <summary>Small JSON helpers for the API answers.</summary>
internal static class JsonAnswers
{
public static string Str(this JsonElement e, string name) => e.GetProperty(name).GetString() ?? string.Empty;
public static int Int(this JsonElement e, string name) => e.GetProperty(name).GetInt32();
public static long Long(this JsonElement e, string name) => e.GetProperty(name).GetInt64();
public static bool Bool(this JsonElement e, string name) => e.GetProperty(name).GetBoolean();
public static JsonElement.ArrayEnumerator Items(this JsonElement e, string name) => e.GetProperty(name).EnumerateArray();
public static Task<T?> ReadAsync<T>(this HttpContent content) => content.ReadFromJsonAsync<T>(WebTestServer.Json);
}