Files
Febe/tests/Febe.Tests/Web/EngineConnectionStateTests.cs
Alby96andClaude Opus 5.5 c69755db23 Sessione salvata: correzioni della revisione di S4b (#36)
Un errore imprevisto durante la copia senza «Ho finito» (database, disco) non trattiene più per sempre il permesso di guida: la copia scrive solo il tipo d'errore e la guida finisce lo stesso, così il motore non resta in «Stai usando il browser». Un «Ho finito» tardivo dopo una copia fatta lasciando il browser dice che la sessione era già stata copiata invece di chiedere un nuovo accesso. Il registro distingue la finestra chiusa da quella ridotta a icona troppo a lungo. /api/engine e gli eventi prendono «Serve «Ho finito»» dall'istantanea del motore (EngineSnapshot.SessionCopyMissing) senza chiedere al browser a ogni evento. La prova di WebView2 aspetta la riga del registro, non solo la sessione in memoria. Documenti: nove operazioni GraphQL con __spin_*, H23 descritta in prove-dal-vivo (parte E), guida aggiornata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:13:25 +01:00

118 lines
6.2 KiB
C#

using System.Runtime.CompilerServices;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Support;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// The link to Instagram in the sidebar (<c>/api/engine</c>, «connection»): it comes from the session cookie, as the
/// engine's mode or the connection says, never from whether the account «Tu» is already known (H10: its name may come
/// much later, and meanwhile the sidebar says «Collegato» with «Nome non ancora noto»).
/// </summary>
[TestClass]
public sealed class EngineConnectionStateTests
{
[TestMethod]
public async Task TheSidebarSaysConnectedFromTheSessionCookieEvenBeforeTuIsKnown()
{
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.Connected, null, null, false, null) };
await using var server = await Part2.StartAsync(services: s =>
{
s.AddSingleton<IEngineMonitor>(sp => new FixedModeMonitor(sp.GetRequiredService<IClock>()));
s.AddSingleton<IConnectionService>(connection);
});
var monitor = (FixedModeMonitor)server.App.Services.GetRequiredService<IEngineMonitor>();
async Task<JsonElement> LinkAsync(EngineMode mode)
{
monitor.Mode = mode;
return (await server.GetJsonAsync("/api/engine")).GetProperty("connection");
}
// Collecting (or about to), with the cookie and without «Tu»: connected, no name yet.
foreach (var mode in new[] { EngineMode.Starting, EngineMode.InSession, EngineMode.Resting, EngineMode.OutsideWindow, EngineMode.Paused, EngineMode.Throttled, EngineMode.UserDriving })
{
var link = await LinkAsync(mode);
Assert.AreEqual("connected", link.Str("state"), mode.ToString());
Assert.AreEqual(JsonValueKind.Null, link.GetProperty("username").ValueKind, mode.ToString());
}
Assert.AreEqual("notConnected", (await LinkAsync(EngineMode.NotConnected)).Str("state"));
Assert.AreEqual("disconnected", (await LinkAsync(EngineMode.Disconnected)).Str("state"));
Assert.AreEqual("verification", (await LinkAsync(EngineMode.StoppedForVerification)).Str("state"));
// The engine loop does not run: the connection itself is asked.
Assert.AreEqual("connected", (await LinkAsync(EngineMode.Off)).Str("state"));
connection.Status = new ConnectionStatus(ConnectionState.NotConnected, null, null, false, null);
Assert.AreEqual("notConnected", (await LinkAsync(EngineMode.Off)).Str("state"));
// Once «Tu» is known, its name comes along.
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
var named = await LinkAsync(EngineMode.Resting);
Assert.AreEqual("connected", named.Str("state"));
Assert.AreEqual("tuo.profilo", named.Str("username"));
Assert.AreEqual(JsonValueKind.Null, (await LinkAsync(EngineMode.NotConnected)).GetProperty("username").ValueKind, "Not connected: no name.");
}
[TestMethod]
public async Task NotConnectedTakesCopyMissingFromTheSnapshotWithoutAskingTheBrowser()
{
// Issue #36, S4b: the engine already knows whether the copy for the requests is missing (its headline says
// «Serve «Ho finito»»); every event of the stream must not cost a look at the browser for it.
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.SessionCopyMissing, null, null, false, null) };
await using var server = await Part2.StartAsync(services: s =>
{
s.AddSingleton<IEngineMonitor>(sp => new FixedModeMonitor(sp.GetRequiredService<IClock>()) { Mode = EngineMode.NotConnected });
s.AddSingleton<IConnectionService>(connection);
});
var monitor = (FixedModeMonitor)server.App.Services.GetRequiredService<IEngineMonitor>();
var reads = connection.StatusReads;
Assert.AreEqual("notConnected", (await server.GetJsonAsync("/api/engine")).GetProperty("connection").Str("state"), "the engine's word, not the connection's");
monitor.CopyMissing = true;
var engine = await server.GetJsonAsync("/api/engine");
Assert.AreEqual("copyMissing", engine.GetProperty("connection").Str("state"));
Assert.IsTrue(engine.GetProperty("snapshot").GetProperty("sessionCopyMissing").GetBoolean());
Assert.AreEqual(reads, connection.StatusReads, "no status asked while the engine runs");
// Only when the engine loop does not run is the connection asked.
monitor.Mode = EngineMode.Off;
Assert.AreEqual("copyMissing", (await server.GetJsonAsync("/api/engine")).GetProperty("connection").Str("state"));
Assert.AreEqual(reads + 1, connection.StatusReads);
}
[TestMethod]
public async Task WithoutEngineAndBrowserTheSidebarSaysNotConnectedEvenIfTuIsKnown()
{
await using var server = await Part2.StartAsync();
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
var engine = await server.GetJsonAsync("/api/engine");
Assert.AreEqual("Off", engine.GetProperty("snapshot").Str("mode"));
Assert.AreEqual("notConnected", engine.GetProperty("connection").Str("state"), "No engine has looked at the cookie and the browser is not there.");
}
/// <summary>An engine that reports the mode the test sets.</summary>
private sealed class FixedModeMonitor(IClock clock) : IEngineMonitor
{
public EngineMode Mode { get; set; } = EngineMode.Resting;
public bool CopyMissing { get; set; }
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default) =>
Task.FromResult(SnapshotParts.Build(clock, Mode, "Prova", [], "Prova", CautionProfile.Prudent) with { SessionCopyMissing = CopyMissing });
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
await Task.Delay(Timeout.Infinite, ct);
yield break;
}
}
}