using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Febe.App;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Desktop;
using Febe.Desktop.Browser;
using Febe.Desktop.Core;
using Febe.SitoDiProva;
using Febe.Tests.Windows.Support;
using Febe.Web.Connection;
using Febe.Web.Native;
namespace Febe.Tests.Windows;
///
/// One real collection session of the shared composition () running on WebView2, as Febe.exe
/// composes it — , DesktopShell, the window «Browser di Febe» on a WPF UI thread —
/// against the local test site, with files arriving in a temporary library. The Linux suite has the equivalent with
/// Chromium (ServerEndToEndTests). Never Instagram: the browser only sees 127.0.0.1.
///
[TestClass]
public sealed class WebView2CollectionTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(420_000, CooperativeCancellation = true)]
public async Task ARealSessionOfTheCompositionRunsOnWebView2AndTheFilesArriveInTheLibrary()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
using var folder = new TestFolder("raccolta");
await using var ui = await UiThread.StartAsync();
var lines = new LogLines();
var data = folder.Combine("dati");
string[] arguments =
[
"--dati", data, "--libreria", folder.Combine("libreria"),
"--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--accesso-di-prova", "--prima-sessione", "1",
];
Assert.IsTrue(DesktopCommandLine.TryParse(arguments, out var options, out var problem), problem);
// Febe.exe's composition, on a clock ten times faster and in a zone where it is noon.
var zone = TestZones.Noon();
var clock = new CompressedClock(10, zone);
var shell = new DesktopShell(ui.Dispatcher, null, BrowserShell.Instance);
var platform = new DesktopPlatform(options, shell, new MemoryLocations(), dataFolderFixed: true);
var appOptions = options.AppOptions(data, new DesktopFolders(folder.Combine("AppData"), folder.Combine("Immagini"))) with { Zone = zone, ZoneId = zone.Id };
var hooks = new FebeAppHooks { Clock = clock, Random = new SeededRandom(20261020), Console = lines, ShutdownTimeout = TimeSpan.FromSeconds(1) };
await using var app = await FebeApp.StartAsync(appOptions, platform, hooks, ct);
Assert.IsEmpty(app.Problems, string.Join("; ", app.Problems.Select(p => p.Title)));
// The browser starts from a thread of the composition, the pipeline and the engine follow.
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
Assert.IsInstanceOfType(app.Browser);
Assert.IsTrue(lines.Any("Browser di Febe pronto: WebView2 "), lines.Text);
Assert.IsFalse(lines.Any("non parte"), lines.Text);
var connection = app.Connection!;
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State, "the test site's automatic login");
// Accounts and «Controlla ora» through the interface, with the token of this start, as the main window does.
using var client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false, UseProxy = false })
{
BaseAddress = app.Address,
Timeout = TimeSpan.FromSeconds(30),
};
var origin = $"{app.Address.Scheme}://{app.Address.Authority}";
async Task JsonAsync(HttpMethod method, string path, string? json = null)
{
using var request = new HttpRequestMessage(method, path);
request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, platform.AccessToken);
request.Headers.TryAddWithoutValidation("Origin", origin);
if (json is not null)
{
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
using var response = await client.SendAsync(request, ct);
var text = await response.Content.ReadAsStringAsync(ct);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
var added = await JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}""");
Assert.AreEqual(2, added.GetProperty("added").GetInt32());
var marta = await app.Database.Accounts.FindByUsernameAsync("marta.prova", ct) ?? throw new AssertFailedException("marta.prova manca");
var check = await JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now");
if (check.GetProperty("status").GetString() == "needsConfirmation")
{
check = await JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}""");
}
Assert.AreEqual("queued", check.GetProperty("status").GetString(), check.GetProperty("message").GetString());
// A session of the engine acts on the site through WebView2: every action has its Governor's permit.
await WaitUntilAsync(
async () => (await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, clock.Now.AddDays(1), ct)).Any(a => a.AccountId == marta.Id),
TimeSpan.FromSeconds(120),
"un'azione del motore su marta.prova nel registro delle azioni",
lines,
ct);
// Files arrive in the library, complete, downloaded through the browser from the test site's CDN.
var library = app.Library ?? throw new AssertFailedException("nessuna libreria");
List stored = [];
await WaitUntilAsync(
async () =>
{
stored = await StoredAsync(app, marta.Id, ct);
return stored.Count >= 3;
},
TimeSpan.FromSeconds(180),
"tre file di marta.prova nella libreria",
lines,
ct);
foreach (var media in stored)
{
var path = library.FullPath(marta, media.RelativePath!);
Assert.IsTrue(File.Exists(path), path);
Assert.AreEqual(media.Bytes, new FileInfo(path).Length, path);
StringAssert.StartsWith(path, folder.Path, "inside the temporary library");
}
var actions = await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, clock.Now.AddDays(1), ct);
Assert.IsTrue(actions.All(a => a.SessionId is not null), "every counted action belongs to a session");
TestContext.WriteLine($"File di marta.prova: {stored.Count}; azioni: {actions.Count}; CDN: {site.Control.CdnFilesServed} file serviti.");
TestContext.WriteLine(lines.Text);
Assert.IsFalse(lines.Any("non parte"), "the browser never failed to start");
Assert.IsFalse(lines.Any("firma="), "no signed address in the log");
}
private static async Task> StoredAsync(FebeApp app, long accountId, CancellationToken ct)
{
var list = new List();
foreach (var entry in await app.Database.Entries.ListByAccountAsync(accountId, null, ct))
{
foreach (var media in await app.Database.Media.ListByEntryAsync(entry.Id, ct))
{
if (media.State == MediaState.Downloaded && media.RelativePath is not null && media.Sha256 is not null && entry.Kind != EntryKind.ProfilePicture)
{
list.Add(media);
}
}
}
return list;
}
private static async Task WaitUntilAsync(Func> condition, TimeSpan timeout, string what, LogLines lines, CancellationToken ct)
{
var deadline = DateTime.UtcNow + timeout;
while (!await condition())
{
if (DateTime.UtcNow > deadline)
{
Assert.Fail($"Tempo scaduto: {what}.\n{lines.Text}");
}
await Task.Delay(250, ct);
}
}
}