using System.Net;
using System.Text.Json;
using Febe.Core.Collection;
using Febe.Core.Engine;
using Febe.Sonda;
using Febe.Tests.Collection;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Api;
using Febe.Web.Demo;
namespace Febe.Tests.Web;
///
/// The demo of the second part (spec §10.6): every page works with coherent fake data and the scenes normale,
/// sessione, fermo, scollegato and errore; /importa?passo=3 has a realistic review; there are duplicates to decide.
///
[TestClass]
public sealed class DemoPart2Tests
{
private static TempFolder? s_temp;
private static DemoHost? s_demo;
private static HttpClient? s_client;
private static HttpClient Client => s_client ?? throw new InvalidOperationException("demo not started");
[ClassInitialize]
public static async Task StartDemoAsync(TestContext context)
{
s_temp = new TempFolder("demo2");
s_demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, s_temp.Path));
s_client = new HttpClient { BaseAddress = s_demo.Address, Timeout = TimeSpan.FromSeconds(60) };
}
[ClassCleanup]
public static async Task StopDemoAsync()
{
s_client?.Dispose();
if (s_demo is not null)
{
await s_demo.DisposeAsync();
}
s_temp?.Dispose();
}
private static async Task GetAsync(string path)
{
using var response = await Client.GetAsync(path);
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
[TestMethod]
public async Task TheConnectionFollowsTheScene()
{
Assert.AreEqual("connected", (await GetAsync("/api/connection?scena=normale")).Str("state"));
Assert.AreEqual("tuo.profilo", (await GetAsync("/api/connection?scena=sessione")).Str("username"));
var login = await GetAsync("/api/connection?scena=scollegato");
Assert.AreEqual("notConnected", login.Str("state"));
StringAssert.Contains(login.Str("currentUrl"), "/accounts/login/");
Assert.AreEqual("verificationRequired", (await GetAsync("/api/connection?scena=fermo")).Str("state"));
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/connection/finish?scena=scollegato");
request.Headers.Add("Origin", s_demo!.Address.GetLeftPart(UriPartial.Authority));
using var response = await Client.SendAsync(request);
var finish = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
Assert.IsFalse(finish.Bool("connected"), "no real browser in the demo: it says so");
StringAssert.StartsWith(finish.Str("message"), "Dimostrazione");
}
[TestMethod]
public async Task TheSceneErroreShowsOnlyTheMissingPassword()
{
var problems = (await GetAsync("/api/capabilities?scena=errore")).Items("problems").ToList();
Assert.HasCount(1, problems);
Assert.AreEqual("password-mancante", problems[0].Str("code"));
StringAssert.Contains(problems[0].Str("remedy"), "FEBE_PASSWORD");
Assert.AreEqual(0, (await GetAsync("/api/capabilities?scena=normale")).GetProperty("problems").GetArrayLength());
Assert.AreEqual("Off", (await GetAsync("/api/engine?scena=errore")).GetProperty("snapshot").Str("mode"));
}
[TestMethod]
public async Task TheImportReviewIsReadyWithEveryKindOfRow()
{
var overview = await GetAsync("/api/import");
var run = overview.Items("runs").Single(r => r.Str("state") == "reviewing");
var review = await GetAsync($"/api/import/{run.Long("id")}/review");
var outcomes = review.GetProperty("outcomes");
Assert.IsGreaterThan(0, outcomes.Int("new"));
Assert.IsGreaterThan(0, outcomes.Int("alreadyInLibrary"));
Assert.IsGreaterThan(0, outcomes.Int("probableDuplicates"));
Assert.IsGreaterThan(0, outcomes.Int("unrecognized"));
Assert.IsGreaterThan(0, review.Int("recognized"), "names in Febe's own scheme give date and code");
var folders = review.Items("folders").ToList();
Assert.IsTrue(folders.Any(f => f.Bool("blocked")), "a folder without account name");
Assert.IsTrue(folders.Any(f => f.GetProperty("target").Str("kind") == "existing"));
Assert.IsTrue(folders.Any(f => f.GetProperty("target").Str("kind") == "newArchiveAccount"));
Assert.IsNotNull(review.GetProperty("plan").Str("leftOutLabel"));
var duplicates = await GetAsync($"/api/import/{run.Long("id")}/duplicates?all=true");
Assert.IsTrue(duplicates.Items("cases").All(c => c.Str("decision") == "pending"), "nothing is chosen in advance");
}
[TestMethod]
public async Task DuplicatesAfterADownloadWaitInTheReview()
{
Assert.AreEqual(3, (await GetAsync("/api/duplicates/count")).Int("download"));
var page = await GetAsync("/api/duplicates");
Assert.HasCount(3, page.Items("cases").ToList());
foreach (var c in page.Items("cases"))
{
Assert.AreEqual(c.GetProperty("existing").Str("username"), c.GetProperty("candidate").Str("username"), "a download pair is inside one account");
using var image = await Client.GetAsync(c.GetProperty("candidate").Str("image"));
Assert.AreEqual(HttpStatusCode.OK, image.StatusCode, "the thumbnail of the downloaded copy exists");
}
}
[TestMethod]
public async Task TheBrowserPreviewAndTheStopsFollowTheScene()
{
var session = await GetAsync("/api/browser/preview?scena=sessione");
Assert.IsTrue(session.Bool("hasFrame"));
using (var frame = await Client.GetAsync(session.Str("frame") + "&scena=sessione"))
{
Assert.AreEqual(HttpStatusCode.OK, frame.StatusCode);
Assert.AreEqual("image/jpeg", frame.Content.Headers.ContentType?.MediaType);
}
Assert.IsFalse((await GetAsync("/api/browser/preview?scena=normale")).Bool("hasFrame"), "between sessions the browser rests on a blank page");
var stopped = (await GetAsync("/api/engine/incidents?scena=fermo")).Items("items").ToList();
Assert.IsTrue(stopped.Any(i => i.Bool("open") && i.Str("level") == "challenge"));
var normal = (await GetAsync("/api/engine/incidents?scena=normale")).Items("items").ToList();
Assert.IsTrue(normal.All(i => !i.Bool("open")));
}
[TestMethod]
public async Task TheDiagnosticReportFollowsTheSceneAndNamesNobody()
{
var finished = s_demo!.World.Today.Count;
Assert.IsGreaterThan(0, finished, "the demo day has sessions");
var names = (await s_demo.Storage.Accounts.ListAsync()).Select(a => a.Username).ToList();
names.AddRange(["marta.demo", "giulia.corre.demo", "tuo.profilo"]);
var vocabulary = ReportLeaks.Vocabulary(SiteMap.LoadInstagram());
var sensitive = names.SelectMany(SensitiveTokens.Tokenize).Where(t => !vocabulary.Contains(t)).ToHashSet(StringComparer.Ordinal);
Assert.IsGreaterThan(20, sensitive.Count);
async Task ReportAsync(string scene)
{
using var response = await Client.GetAsync($"{ActivityApi.DiagnosticsPath}?scena={scene}");
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{scene}: {text}");
Assert.AreEqual("attachment", response.Content.Headers.ContentDisposition?.DispositionType);
Assert.AreEqual("no-store", response.Headers.CacheControl?.ToString());
ReportLeaks.AssertClean(text, names, sensitive, ReportLeaks.FieldKeys([]));
return JsonDocument.Parse(text).RootElement.Clone();
}
var normal = await ReportAsync("normale");
Assert.AreEqual("windows", normal.Str("edizione"), "the demo looks like the desktop by default");
var sessions = normal.Items("sessioni").ToList();
Assert.HasCount(finished, sessions);
Assert.IsTrue(sessions.All(s => s.Str("outcome") == nameof(Febe.Core.Domain.SessionOutcome.Completed) && !s.Bool("inProgress")));
Assert.IsTrue(sessions.All(s => s.Items("responses").Any() && s.Items("recipes").Any()));
Assert.AreEqual(0, sessions.Sum(s => s.Items("signals").Count()));
Assert.HasCount(1, normal.Items("fuoriSessione").ToList());
var running = (await ReportAsync("sessione")).Items("sessioni").ToList();
Assert.HasCount(finished + 1, running);
Assert.IsTrue(running[^1].Bool("inProgress"), "the session in progress comes last");
var stopped = (await ReportAsync("fermo")).Items("sessioni").ToList();
Assert.HasCount(finished, stopped);
Assert.AreEqual(nameof(SessionStopCause.BreakerOpen), stopped[^1].Str("stopCause"));
Assert.AreEqual(DemoDiagnosticSource.ChallengeCode, stopped[^1].Items("signals").Single().Str("code"));
Assert.IsTrue(stopped.Take(stopped.Count - 1).All(s => s.Str("stopCause") != nameof(SessionStopCause.BreakerOpen)));
foreach (var scene in new[] { "scollegato", "errore" })
{
var empty = await ReportAsync(scene);
Assert.AreEqual(0, empty.GetProperty("sessioni").GetArrayLength(), scene);
Assert.AreEqual(0, empty.GetProperty("fuoriSessione").GetArrayLength(), scene);
}
Assert.AreEqual("docker", (await ReportAsync("normale&veste=docker")).Str("edizione"));
}
[TestMethod]
public async Task EverySettingsPageHasItsData()
{
Assert.AreEqual("prudent", (await GetAsync("/api/settings/limits")).Str("profile"));
var general = await GetAsync("/api/settings/general?veste=desktop");
Assert.IsFalse(general.Bool("foldersReadOnly"));
Assert.IsTrue(general.Bool("canChangeDataFolder"));
Assert.IsTrue(general.GetProperty("autostart").ValueKind is JsonValueKind.True or JsonValueKind.False, "«Avvio» on the desktop look");
var docker = await GetAsync("/api/settings/general?veste=docker");
Assert.IsTrue(docker.Bool("foldersReadOnly"));
Assert.AreEqual(JsonValueKind.Null, docker.GetProperty("autostart").ValueKind);
Assert.AreEqual("marta.demo", general.GetProperty("preview").Str("accountFolder"), "the preview of mockup 08");
await GetAsync("/api/settings/notifications");
await GetAsync("/api/settings/data");
Assert.AreEqual("Windows", (await GetAsync("/api/about?veste=desktop")).Str("edition"));
}
}