Integrazione 0.1.1: Febe per Windows si collega, VS Code, prove su Windows, storico e vista remota #4
No files matched your search
@@ -0,0 +1,78 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop.Core;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A clock that compresses time, like the one of the Linux suite: <see cref="Delay"/> waits for real only a fraction
|
||||
/// of the requested time and <see cref="Now"/> moves on by the whole of it, so the engine keeps its order of events
|
||||
/// while a session lasts minutes instead of hours.
|
||||
/// </summary>
|
||||
internal sealed class CompressedClock(double factor, TimeZoneInfo zone) : IClock
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private TimeSpan _offset;
|
||||
|
||||
public TimeZoneInfo LocalZone { get; } = zone;
|
||||
|
||||
public DateTimeOffset Now
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return DateTimeOffset.UtcNow + _offset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Delay(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
if (time <= TimeSpan.Zero)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return;
|
||||
}
|
||||
|
||||
var real = TimeSpan.FromTicks((long)(time.Ticks / factor));
|
||||
if (real >= TimeSpan.FromMilliseconds(1))
|
||||
{
|
||||
await Task.Delay(real, ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await Task.Yield();
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_offset += time - real;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class TestZones
|
||||
{
|
||||
/// <summary>
|
||||
/// A fixed-offset zone where it is between 12:00 and 13:00 now: inside the active window of every caution profile,
|
||||
/// whatever the hour of the test.
|
||||
/// </summary>
|
||||
public static TimeZoneInfo Noon()
|
||||
{
|
||||
var offset = 12 - DateTimeOffset.UtcNow.Hour;
|
||||
return TimeZoneInfo.CreateCustomTimeZone("Febe/Mezzogiorno", TimeSpan.FromHours(offset), "Mezzogiorno di prova", "Mezzogiorno di prova");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The registry values «CartellaDati» and «NuovaCartellaDati», in memory.</summary>
|
||||
internal sealed class MemoryLocations : IDataFolderLocationStore
|
||||
{
|
||||
public string? Current { get; private set; }
|
||||
|
||||
public string? Pending { get; private set; }
|
||||
|
||||
public void SetCurrent(string? folder) => Current = folder;
|
||||
|
||||
public void SetPending(string? folder) => Pending = folder;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// One real collection session of the shared composition (<see cref="FebeApp"/>) running on WebView2, as Febe.exe
|
||||
/// composes it — <see cref="DesktopPlatform"/>, <c>DesktopShell</c>, 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.
|
||||
/// </summary>
|
||||
[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<WebView2Browser>(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<JsonElement> 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<Media> 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<List<Media>> StoredAsync(FebeApp app, long accountId, CancellationToken ct)
|
||||
{
|
||||
var list = new List<Media>();
|
||||
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<Task<bool>> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user