using System.Net; using System.Text; using System.Text.Json; using Febe.Tests.Support; using Febe.Tests.Web.Support; using Febe.Web.Demo; namespace Febe.Tests.Web; /// /// The copies to external folders over the API of the demo (spec §4.10, §10.6, tappa E2): destinations, the account /// card, marks and the «Copie» filter, the viewer's copies, jobs and their report, and the folders of each look. The /// demo's copies were written by the real engine into its temporary «esporta», so every number here comes from rows /// and files that agree. Only reads and plans: nothing here changes the demo. /// [TestClass] public sealed class ExportApiDemoTests { private static TempFolder? s_temp; private static DemoHost? s_demo; private static HttpClient? s_client; private static DemoHost Demo => s_demo ?? throw new InvalidOperationException("demo not started"); private static HttpClient Client => s_client ?? throw new InvalidOperationException("demo not started"); [ClassInitialize] public static async Task StartDemoAsync(TestContext context) { s_temp = new TempFolder("demo-export"); 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(); } [TestMethod] public async Task TheOverviewListsTheDemoFoldersInBothLooks() { var desktop = await GetAsync("/api/export"); Assert.IsFalse(desktop.GetProperty("root").Bool("docker")); Assert.IsTrue(desktop.GetProperty("root").Bool("active")); Assert.IsTrue(desktop.GetProperty("root").Bool("pickFolder")); var general = desktop.GetProperty("general"); Assert.AreEqual("Disco USB", general.Str("label")); Assert.AreEqual("general", general.Str("scope")); Assert.HasCount(6, general.Items("types").ToList()); Assert.IsGreaterThan(0, general.GetProperty("counts").Int("copied")); Assert.AreEqual(1, general.GetProperty("counts").Int("removed")); Assert.AreEqual(1, general.GetProperty("counts").Int("superseded")); Assert.AreEqual(1, general.GetProperty("counts").Int("failed")); var own = desktop.Items("own").Single(); Assert.AreEqual("studio.lumen.demo", own.Str("username")); Assert.AreEqual("Studio Lumen", own.Str("label")); CollectionAssert.AreEquivalent(new[] { "postFoto", "postVideo" }, own.Items("types").Select(t => t.GetString()).ToArray()); Assert.AreEqual(1, desktop.Int("unfinishedRuns"), "the job left interrupted by the demo"); Assert.AreEqual("onePerAccount", desktop.Str("samePost")); var docker = await GetAsync("/api/export?veste=docker"); Assert.IsTrue(docker.GetProperty("root").Bool("docker")); Assert.IsTrue(docker.GetProperty("root").Bool("active")); Assert.IsFalse(docker.GetProperty("root").Bool("pickFolder")); Assert.AreEqual("/esporta", docker.GetProperty("root").Str("root")); Assert.AreEqual("/esporta/Disco USB", docker.GetProperty("general").Str("display")); } [TestMethod] public async Task TheFoldersAreListedInDockerAndPickedOnTheDesktop() { var list = await GetAsync("/api/export/folders?veste=docker"); CollectionAssert.IsSubsetOf(new[] { "Chiavetta", "Disco USB", "Studio Lumen" }, list.Items("folders").Select(f => f.Str("name")).ToArray()); Assert.AreEqual("/esporta", list.Str("display")); Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/export/folders?veste=docker&path=..")).Status); Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/export/folders")).Status, "the desktop uses the picker"); var check = await PostAsync("/api/export/check-folder?veste=docker", new { path = "Chiavetta" }); Assert.IsTrue(check.Bool("accepted"), check.ToString()); Assert.AreEqual("/esporta/Chiavetta", check.Str("display")); Assert.AreEqual(DemoExportDisk.Free, check.Long("freeBytes")); Assert.IsFalse(check.Bool("fat32")); var outside = await SendAsync(HttpMethod.Post, "/api/export/check-folder?veste=docker", new { path = "../fuori" }); Assert.IsTrue(outside.Status == HttpStatusCode.BadRequest || !JsonDocument.Parse(outside.Body).RootElement.Bool("accepted"), outside.Body); var picked = await PostAsync("/api/export/pick-folder", new { destinationId = (long?)null }); Assert.EndsWith("Chiavetta", picked.Str("path")); Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/pick-folder?veste=docker", new { })).Status); } [TestMethod] public async Task TheAccountCardCountsOnlyDueFilesAndTheSwitchOffCountsNothing() { var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); long Id(string username) => accounts.First(a => a.Str("username") == username).Long("id"); var marta = (await GetAsync($"/api/accounts/{Id(DemoExport.CopiedAccount)}")).GetProperty("export"); Assert.IsTrue(marta.Bool("enabled")); Assert.IsFalse(marta.Bool("hasOwnFolder")); Assert.AreEqual("Disco USB", marta.GetProperty("destination").Str("label")); Assert.IsGreaterThan(0, marta.Int("due")); Assert.IsGreaterThan(0, marta.Int("notCopied")); Assert.IsLessThan(marta.Int("due"), marta.Int("notCopied"), "about two thirds are copied"); Assert.IsGreaterThan(0, marta.Int("removedOrSuperseded")); Assert.IsGreaterThan(0, marta.Int("failed")); Assert.IsGreaterThan(marta.Int("notCopied") + marta.Int("removedOrSuperseded") + marta.Int("failed"), marta.Int("due"), "the rest is copied"); var studio = (await GetAsync($"/api/accounts/{Id(DemoExport.OwnFolderAccount)}")).GetProperty("export"); Assert.IsTrue(studio.Bool("hasOwnFolder")); Assert.AreEqual("Studio Lumen", studio.GetProperty("destination").Str("label")); var porto = (await GetAsync($"/api/accounts/{Id(DemoExport.NotExportedAccount)}")).GetProperty("export"); Assert.IsFalse(porto.Bool("enabled")); Assert.AreEqual(0, porto.Int("due")); Assert.AreEqual(0, porto.Int("notCopied")); } [TestMethod] public async Task TheFilterTheMarksAndTheViewerAgree() { var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); var marta = accounts.First(a => a.Str("username") == DemoExport.CopiedAccount).Long("id"); var card = (await GetAsync($"/api/accounts/{marta}")).GetProperty("export"); var days = await GetAsync($"/api/library/days?accounts={marta}&mode=files&copies=removedOrSuperseded"); Assert.IsTrue(days.Bool("hasDestinations")); Assert.AreEqual(card.Int("removedOrSuperseded"), days.Int("files"), "the card and the filter count the same files"); Assert.AreEqual(card.Int("notCopied"), (await GetAsync($"/api/library/days?accounts={marta}&mode=files&copies=notCopied")).Int("files")); var copied = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=copied&limit=600")).Items("tiles").ToList(); Assert.IsNotEmpty(copied); Assert.IsTrue(copied.All(t => t.Str("copies") == "copied"), "every file the filter finds copied carries the mark"); var notCopied = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=notCopied&limit=600")).Items("tiles").ToList(); Assert.IsNotEmpty(notCopied); Assert.IsTrue(notCopied.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "a file not copied has no mark"); Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/library?copies=tutti")).Status); var grouped = (await GetAsync($"/api/library?accounts={marta}&limit=600")).Items("tiles").ToList(); foreach (var partly in grouped.Where(t => t.Str("copies") == "partly")) { Assert.IsLessThan(partly.Int("copiesDue"), partly.Int("copiesDone")); Assert.IsGreaterThan(0, partly.Int("copiesDone")); } // The viewer of a file «Tolto o superato»: its copy, with «Copia di nuovo». var replaced = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=removedOrSuperseded&limit=600")).Items("tiles").ToList(); Assert.HasCount(card.Int("removedOrSuperseded"), replaced); var states = new HashSet(); foreach (var tile in replaced) { var entry = await GetAsync($"/api/entries/{tile.Long("id")}"); Assert.IsTrue(entry.Bool("canCopy")); var file = entry.Items("media").First(m => m.Long("id") == tile.GetProperty("cover").Long("mediaId")); var copy = file.Items("copies").First(c => c.Str("state") is "removed" or "superseded"); Assert.IsTrue(copy.Bool("canCopyAgain"), copy.ToString()); Assert.AreEqual("Disco USB", copy.Str("destination")); Assert.AreEqual("whole", copy.Str("variant")); states.Add(copy.Str("state")); } CollectionAssert.AreEquivalent(new[] { "removed", "superseded" }, states.ToArray()); } [TestMethod] public async Task TheJobsHaveTheirReportAndThePlanSaysWhatWouldBeCopied() { var runs = await GetAsync("/api/export/runs"); var list = runs.EnumerateArray().ToList(); var completed = list.First(r => r.Str("state") == "completed" && r.Str("destination") == "Disco USB"); Assert.IsTrue(list.Any(r => r.Str("state") == "interrupted" && r.Int("done") == 0 && r.Int("total") > 0)); Assert.AreEqual(completed.Int("total"), completed.Int("done")); var report = await GetAsync($"/api/export/runs/{completed.Long("id")}/report"); Assert.IsGreaterThan(0, report.GetProperty("byState").Int("copied")); Assert.AreEqual(0, report.GetProperty("byState").Int("failed")); Assert.IsGreaterThan(0L, report.Long("bytesCopied")); Assert.AreEqual(DemoExport.CopiedAccount, report.Items("accounts").Single().Str("username")); var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); var marta = accounts.First(a => a.Str("username") == DemoExport.CopiedAccount).Long("id"); var card = (await GetAsync($"/api/accounts/{marta}")).GetProperty("export"); var plan = await PostAsync("/api/export/plan", new { accountId = marta }); // One write per picture of the account: the other files with the same picture are «Già copiato». Assert.IsGreaterThan(0, plan.Int("files")); Assert.IsLessThanOrEqualTo(card.Int("notCopied") + card.Int("failed"), plan.Int("files")); Assert.IsGreaterThan(0, plan.Int("alreadyCopied")); Assert.IsGreaterThan(0, plan.Int("removedOrSuperseded"), "skipped unless «Copia di nuovo»"); Assert.IsLessThanOrEqualTo(card.Int("removedOrSuperseded"), plan.Int("removedOrSuperseded")); Assert.AreEqual("Disco USB", plan.Items("destinations").Single().Str("label")); var again = await PostAsync("/api/export/plan", new { accountId = marta, copyAgain = true }); Assert.IsGreaterThan(plan.Int("files"), again.Int("files")); var porto = accounts.First(a => a.Str("username") == DemoExport.NotExportedAccount).Long("id"); var off = await PostAsync("/api/export/plan", new { accountId = porto }); Assert.AreEqual(0, off.Int("files")); Assert.IsGreaterThan(0, off.Int("notExported")); Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta, mediaIds = new[] { 1L } })).Status, "exactly one selection"); Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/plan", new { })).Status); var progress = await GetAsync("/api/export/progress"); Assert.IsFalse(progress.Bool("running")); } [TestMethod] public async Task CommandsWithoutTheOriginOfThePageAreRefused() { using var request = new HttpRequestMessage(HttpMethod.Post, "/api/export/interrupt") { Content = new StringContent("{}", Encoding.UTF8, "application/json") }; request.Headers.Add("Origin", "http://altro.example"); using var response = await Client.SendAsync(request); Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); } private static string Origin => $"{Demo.Address.Scheme}://{Demo.Address.Authority}"; private static async Task GetAsync(string path) { var (status, body) = await SendAsync(HttpMethod.Get, path); Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {body}"); return JsonDocument.Parse(body).RootElement.Clone(); } private static async Task PostAsync(string path, object body) { var (status, text) = await SendAsync(HttpMethod.Post, path, body); Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {text}"); return JsonDocument.Parse(text).RootElement.Clone(); } private static async Task<(HttpStatusCode Status, string Body)> SendAsync(HttpMethod method, string path, object? body = null) { using var request = new HttpRequestMessage(method, path); if (body is not null) { request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); } if (method != HttpMethod.Get) { request.Headers.Add("Origin", Origin); } using var response = await Client.SendAsync(request); return (response.StatusCode, await response.Content.ReadAsStringAsync()); } }