using System.Net;
using Febe.Core.Abstractions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Desktop;
///
/// The browser that showed nothing (Gitea issue #52), in the shared composition with the fake window «Browser di Febe»:
/// opened from the empty rest page it goes to a page of its own, «Apri il browser» of a disconnection opens the login,
/// leaving a page of Febe leaves the window as it is, and the test site's automatic login raises no false alarm.
/// Never Instagram: the fake browser answers by itself.
///
[TestClass]
public sealed class BrowserStartPageTests
{
private const string Login = "https://www.instagram.com/accounts/login/";
private const string Home = "https://www.instagram.com/";
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task UsaIlBrowserFromTheRestPageOpensTheLoginOrTheHomeAndAnyOtherPageStays()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
// Not connected: never a white window, the login page.
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Login, browser.FakeCdp.Url);
Assert.AreEqual(1, browser.Shown, "the window came to the front");
browser.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
// Connected: the site's home.
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Home, browser.FakeCdp.Url);
// A page he opened stays as it is.
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
var navigations = Navigations(browser);
await BeginAsync(bed, openLogin: false);
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url);
Assert.AreEqual(navigations, Navigations(browser), "no navigation of his page");
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.IsTrue(status.GetProperty("userIsDriving").GetBoolean());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ABrowserThatDoesNotAnswerYetIsWaitedForAndThenOpensTheLogin()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
// Just restarted (after «Scollega», issue #67): the browser does not say its page yet. Febe asks again and waits.
browser.FakeCdp.Silent = true;
var asked = browser.FakeCdp.SilentAnswers;
var begin = BeginAsync(bed, openLogin: false);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.SilentAnswers >= asked + 3, TimeSpan.FromSeconds(5), "le domande ripetute al browser che non risponde");
Assert.IsFalse(begin.IsCompleted, "still waiting for the browser");
Assert.DoesNotContain(Login, browser.FakeCdp.Visited);
// It answers, on the empty rest page: the login page, never a white window (issue #52).
browser.FakeCdp.Silent = false;
await begin.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.AreEqual(Login, browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ABrowserSilentBeyondTheWaitCountsAsAtRestAndOpensTheLogin()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.AddressWait = TimeSpan.FromMilliseconds(400);
browser.FakeCdp.Silent = true;
var watch = System.Diagnostics.Stopwatch.StartNew();
await BeginAsync(bed, openLogin: false);
watch.Stop();
Assert.IsGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(350), watch.Elapsed, "it waited for the browser first");
Assert.AreEqual(Login, browser.FakeCdp.Url, "still silent: the rest page, and the login opens");
Assert.AreEqual(1, browser.FakeCdp.Visited.Count(v => v == Login));
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ABrowserThatAnswersLateWithAPageOfAlbertosLeavesItAlone()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
var navigations = Navigations(browser);
browser.FakeCdp.Silent = true;
var asked = browser.FakeCdp.SilentAnswers;
var begin = BeginAsync(bed, openLogin: false);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.SilentAnswers >= asked + 2, TimeSpan.FromSeconds(5), "le domande ripetute al browser che non risponde");
browser.FakeCdp.Silent = false;
await begin.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url);
Assert.AreEqual(navigations, Navigations(browser), "no navigation of his page");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheWaitForASilentBrowserEndsWithTheRequest()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
var navigations = Navigations(browser);
browser.FakeCdp.Silent = true;
var asked = browser.FakeCdp.SilentAnswers;
using var request = new CancellationTokenSource();
var begin = connection.BeginUserDrivingAsync(openLogin: false, request.Token);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.SilentAnswers >= asked + 2, TimeSpan.FromSeconds(5), "le domande ripetute al browser che non risponde");
await request.CancelAsync();
await Assert.ThrowsAsync(() => begin.WaitAsync(TimeSpan.FromSeconds(10), ct));
Assert.AreEqual(navigations, Navigations(browser), "nothing opened after the request went away");
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
// The commands of the connection are free again: the next request, with the browser answering, opens the login.
browser.FakeCdp.Silent = false;
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Login, browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ApriIlBrowserBringsTheWindowWithItsStartPageAndTheLoginAfterADisconnection()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
// Connected, at rest: «Apri il browser» (Attività) opens the home, the window in front.
await LoginAsync(bed);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
var shown = browser.Shown;
var result = await bed.JsonAsync(HttpMethod.Post, "/api/browser/show");
StringAssert.Contains(result.GetProperty("message").GetString(), "primo piano");
Assert.AreEqual(Home, browser.FakeCdp.Url);
Assert.AreEqual(shown + 1, browser.Shown);
Assert.IsTrue(browser.UserIsDriving, "the window on screen holds the engine still");
// Closed with its X: out of view, the engine puts the page to rest.
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo la chiusura");
// The session goes while nobody looks: a disconnection. The red strip's «Apri il browser» asks for the login.
browser.FakeCdp.LoggedIn = false;
await bed.App.Connection!.RefreshAsync(ct);
var breaker = bed.App.Engine!.Services.Breaker;
await breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Disconnected, breaker.State.Status);
Assert.AreEqual(Login, bed.App.Connection.StartPageUrl, "disconnected: the start page is the login");
using (var show = await bed.SendAsync(HttpMethod.Post, "/api/browser/show", """{"openLogin":true}"""))
{
Assert.AreEqual(HttpStatusCode.OK, show.StatusCode, await show.Content.ReadAsStringAsync(ct));
}
Assert.AreEqual(Login, browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingThePageOfFebeLeavesTheWindowOnScreenButAnnullaPutsItAway()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
await LoginAsync(bed);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Home, browser.FakeCdp.Url);
var hidden = browser.Hidden;
// Another page of Febe, the tab closed or reloaded: the page's hold ends, the window stays where it is.
using (var left = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel", """{"pageLeft":true}"""))
{
Assert.AreEqual(HttpStatusCode.NoContent, left.StatusCode);
}
await Task.Delay(TimeSpan.FromSeconds(1), ct);
Assert.AreEqual(hidden, browser.Hidden, "not put out of view");
Assert.AreEqual(Home, browser.FakeCdp.Url, "not put to rest");
Assert.IsTrue(browser.UserIsDriving, "on screen, the window still holds the engine");
Assert.IsTrue(bed.App.Engine!.Services.Runtime.UserIsDriving);
// «Annulla» from the page is still «Annulla»: out of view and at rest.
await BeginAsync(bed, openLogin: false);
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
Assert.AreEqual(hidden + 1, browser.Hidden);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo «Annulla»");
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task HoFinitoWithoutTheLoginSaysTheSessionIsNotThere()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
await BeginAsync(bed, openLogin: true);
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsFalse(finish.GetProperty("connected").GetBoolean());
StringAssert.Contains(finish.GetProperty("message").GetString(), "non trova la sessione");
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task TheTestSitesAutomaticLoginIsNoDisconnectionAtTheNextStart()
{
var ct = TestContext.CancellationToken;
const string site = "http://127.0.0.1:8481";
string[] args = ["--sito-di-prova", site, "--accesso-di-prova"];
using var temp = new TempFolder("accesso-di-prova");
var locations = new MemoryLocationStore();
FakeDesktopShell Shell() => new() { OnCreated = b => b.FakeCdp.LogsInOnVisit = site };
await using (var bed = await DesktopTestBed.StartAsync(args, Shell(), temp, locations))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
Assert.IsTrue(bed.App.Connection!.IsConnected, "logged in by the automatic login");
await bed.StopAsync();
}
// The next start: the new browser has no session yet (the test site forgot it); the automatic login opens it again.
await using (var bed = await DesktopTestBed.StartAsync(args, Shell(), temp, locations))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var breaker = bed.App.Engine!.Services.Breaker;
await breaker.FlushAsync();
Assert.IsTrue(bed.App.Connection!.IsConnected);
Assert.AreEqual(BreakerStatus.Closed, breaker.State.Status, "not a disconnection: the session the login was about to open");
Assert.IsEmpty(await bed.App.Database.Incidents.ListOpenAsync(ct));
await bed.StopAsync();
}
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task PaginaInizialeWaitsForThePageTurnAndActsOnlyWhileAlbertoIsAtTheBrowser()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// Nobody at the browser: the page is the engine's, the button does nothing.
var navigations = Navigations(browser);
await connection.OpenStartPageAsync(ct);
Assert.AreEqual(navigations, Navigations(browser));
// At the browser, on a page of his: the start page — but only once a step of the profile search let go of the page.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
var turns = bed.App.Engine!.Services.PageTurns;
var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
var home = connection.OpenStartPageAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina");
Assert.IsFalse(home.IsCompleted, "the search step still has the page");
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url);
turn.Dispose();
await home.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.AreEqual(Login, browser.FakeCdp.Url, "not connected: the login page");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task PaginaInizialeIsForgottenWhenAlbertoLetGoOfTheBrowserWhileItWaited()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
var turns = bed.App.Engine!.Services.PageTurns;
// The window on screen (its lease), a step of the profile search on the page: «Pagina iniziale» waits for its turn.
var window = browser.UserDriving.Begin();
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
var home = connection.OpenStartPageAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina");
// Alberto closes the window meanwhile: the page is the engine's again, and the press is forgotten (rules 7 and 8).
window.Dispose();
Assert.IsFalse(browser.UserIsDriving);
turn.Dispose();
await home.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.DoesNotContain(Login, browser.FakeCdp.Visited, "no navigation of Alberto's without his lease");
Assert.DoesNotContain(Home, browser.FakeCdp.Visited);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task PaginaInizialeEndsWithTheLeaseOfWhoPressedIt()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
var turns = bed.App.Engine!.Services.PageTurns;
// Someone else still drives (Febe's page with «Usa il browser»), but the window that pressed the button closed.
using var other = browser.UserDriving.Begin();
using var pressedBy = new CancellationTokenSource();
var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
var home = connection.OpenStartPageAsync(pressedBy.Token);
await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina");
await pressedBy.CancelAsync();
await home.WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.IsFalse(turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), "no longer in the queue");
turn.Dispose();
Assert.DoesNotContain(Login, browser.FakeCdp.Visited);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task PaginaInizialeNeverTakesThePageFromUnderASearchStep()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageTurnWait = TimeSpan.FromMilliseconds(300);
var turns = bed.App.Engine!.Services.PageTurns;
using var window = browser.UserDriving.Begin();
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
using var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
await connection.OpenStartPageAsync(ct).WaitAsync(TimeSpan.FromSeconds(10), ct);
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url, "the step keeps its page");
Assert.DoesNotContain(Login, browser.FakeCdp.Visited);
}
private static int Navigations(FakeBrowser browser) => browser.FakeCdp.Methods.Count(m => m == "Page.navigate");
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin)
{
using var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", openLogin ? """{"openLogin":true}""" : """{"openLogin":false}""");
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
private static async Task LoginAsync(DesktopTestBed bed)
{
await BeginAsync(bed, openLogin: true);
bed.Browser!.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString());
}
}