using System.Diagnostics;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Browser.Recipes;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
using Febe.Desktop.Core;
using Febe.SitoDiProva;
using Febe.Tests.Windows.Support;
namespace Febe.Tests.Windows;
///
/// The life of the browser of Febe on a real Windows, driven from thread-pool threads as the composition and the
/// connection service drive it: a start that really fails is retried (and only that), the window comes on screen and
/// goes away with the «driving» lease (the login), «Scollega» empties the profile and the browser comes back, a browser
/// process that dies is started again, and the second hosting of S2 (composition) starts and draws.
///
/// Two tests bring the window «Browser di Febe» on screen for a moment, as «Accedi a Instagram» does.
[TestClass]
public sealed class WebView2LifecycleTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AStartThatReallyFailsIsRetriedAndThenTheBrowserIsReady()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("tentativi");
// A file where the profile folder must go: WebView2 cannot start.
var profile = bed.Browser.ProfileDirectory;
Directory.CreateDirectory(Path.GetDirectoryName(profile)!);
await File.WriteAllTextAsync(profile, "occupa il posto della cartella del profilo", ct);
var run = Task.Run(() => bed.Browser.RunAsync(ct), ct);
await bed.WaitUntilAsync(() => bed.Lines.Any("non parte"), TimeSpan.FromSeconds(30), "il primo avvio non riuscito", ct);
Assert.IsFalse(bed.Browser.IsAvailable);
StringAssert.StartsWith(bed.Browser.LastError, "WebView2 non parte (IOException:");
StringAssert.EndsWith(bed.Lines.Lines.Single(l => l.Contains("non parte", StringComparison.Ordinal)), "Nuovo tentativo fra 5 s.");
// The obstacle goes away: the next attempt, 5 s later, works.
File.Delete(profile);
await run.WaitAsync(TimeSpan.FromSeconds(60), ct);
TestContext.WriteLine(bed.Lines.Text);
Assert.IsTrue(bed.Browser.IsAvailable);
Assert.IsNull(bed.Browser.LastError);
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("non parte", StringComparison.Ordinal)), "one failed attempt only");
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("Browser di Febe pronto: WebView2 ", StringComparison.Ordinal)));
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheWindowComesOnScreenWithTheLeaseAndGoesAwayWithIt()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("finestra");
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "the window is open");
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen), "after the start it is parked out of view");
Assert.IsFalse(bed.Browser.UserIsDriving);
// «Accedi a Instagram» / «Portalo in primo piano», from the connection service's thread.
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
Assert.IsTrue(await bed.OnUiAsync(() => window.IsOnScreen), "the window came on screen");
Assert.IsTrue(bed.Browser.UserIsDriving, "while it is in front the engine is still");
Assert.IsNotNull(bed.Tracker.LastUsedAt, "using it counts for «Riprendi»");
// «Ho finito».
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
Assert.IsFalse(bed.Browser.UserIsDriving);
// Closing the window is «ho finito» too: out of view, still open, still painting.
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
Assert.IsTrue(bed.Browser.UserIsDriving);
await bed.OnUiAsync(() =>
{
window.Close();
return true;
});
Assert.IsFalse(bed.Browser.UserIsDriving);
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "closing it never closes it");
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(bed.Browser.Cdp, 50, ct), ct);
Assert.AreEqual(0xFF, jpeg[0], "the page still draws out of view");
Assert.IsTrue(bed.Browser.IsAvailable);
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task ScollegaDeletesTheProfileWithTheSessionAndTheBrowserComesBackEmpty()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
await using var bed = await BrowserBed.CreateAsync("scollega");
await bed.StartAsync(ct);
var cdp = bed.Browser.Cdp;
var cookie = CollectionSite.TestSite(site.SiteHost, site.CdnHost).SessionCookie;
var clock = new SystemClock();
// «Collegato»: the site's session cookie is in the profile.
await Task.Run(
async () =>
{
await cdp.NavigateAsync(site.Url("/"), ct);
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
},
ct);
Assert.IsTrue(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "connected to the test site");
var marker = Path.Combine(bed.Browser.ProfileDirectory, "segno-della-prova");
await File.WriteAllTextAsync(marker, "x", ct);
var before = bed.Browser.Host.BrowserProcessId;
// «Scollega», from the connection service's thread.
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
TestContext.WriteLine(bed.Lines.Text);
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
Assert.IsTrue(bed.Browser.IsAvailable, "the browser runs again");
Assert.AreNotEqual(before, bed.Browser.Host.BrowserProcessId, "with a new browser process");
Assert.IsFalse(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "the session went with the profile");
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => cdp.GetMainFrameUrlAsync(ct), ct));
Assert.IsTrue(bed.Lines.Any("Profilo del browser cancellato; il browser è ripartito vuoto."));
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task WhenItsBrowserProcessDiesTheBrowserStartsAgainByItself()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("arresto");
await bed.StartAsync(ct);
var reconnected = 0;
bed.Browser.Host.Connection.Reconnected += (_, _) => Interlocked.Increment(ref reconnected);
// The browser process this test started — by its id, never by name.
var pid = bed.Browser.Host.BrowserProcessId;
Assert.AreNotEqual(0, pid);
using (var process = Process.GetProcessById(pid))
{
Assert.AreEqual("msedgewebview2", process.ProcessName, "the browser process of WebView2");
process.Kill();
}
await bed.WaitUntilAsync(() => bed.Lines.Any("Browser di Febe ripartito: WebView2 "), TimeSpan.FromSeconds(90), "la ripartenza del browser", ct);
TestContext.WriteLine(bed.Lines.Text);
Assert.IsTrue(bed.Lines.Any("WebView2: processo terminato (BrowserProcessExited)."));
Assert.IsTrue(bed.Browser.IsAvailable);
Assert.AreNotEqual(pid, bed.Browser.Host.BrowserProcessId, "a new browser process");
Assert.AreEqual(1, Volatile.Read(ref reconnected), "the subscriptions of the session moved to the new WebView once");
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
Assert.IsFalse(bed.Lines.Any("non parte"), "the new start worked at once");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheCompositionHostingOfS2StartsAndDrawsThePage()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
await using var bed = await BrowserBed.CreateAsync("composizione", BrowserHosting.Composition);
await bed.StartAsync(ct);
Assert.IsTrue(bed.Lines.Any(", composizione, fuori vista."), bed.Lines.Text);
var cdp = bed.Browser.Cdp;
var clock = new SystemClock();
var seen = await Task.Run(
async () =>
{
await cdp.NavigateAsync(site.Url("/profilo/marta.prova/"), ct);
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
return await cdp.EvaluateAsync("({ visibility: document.visibilityState, width: innerWidth, height: innerHeight })", ct);
},
ct);
TestContext.WriteLine("La pagina vede: " + seen.GetRawText());
Assert.AreEqual("visible", seen.GetProperty("visibility").GetString());
Assert.AreEqual(1280, seen.GetProperty("width").GetInt32());
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(cdp, 60, ct), ct);
Assert.IsGreaterThan(5_000, jpeg.Length, "a real frame");
}
}