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; /// /// 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. /// 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; } /// A client without cookies of its own (each test decides what to send). public HttpClient Client { get; } /// «http://127.0.0.1:port», the value of Origin for requests coming from the interface. public string Origin => $"{Address.Scheme}://{Address.Authority}"; public LibraryChanges Changes => App.Services.GetRequiredService(); public static async Task StartAsync(FebeWebOptions? options = null, Action? 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(db); s.AddSingleton(library); s.AddSingleton(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) }; } /// A request as the interface sends it (Origin of the interface on commands). 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 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); } /// Adds an account with a few stored entries spread over days (no files on disk). public async Task 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(); 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(); } } /// Small JSON helpers for the API answers. 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 ReadAsync(this HttpContent content) => content.ReadFromJsonAsync(WebTestServer.Json); }