La dimostrazione mostra le copie automatiche senza avviare il lavoratore: «Studio Lumen» è automatica con «Solo i nuovi» dall'inizio dei suoi file più recenti non copiati; un lavoro automatico del motore vero (su un orologio spostato indietro) ne ha copiati alcuni e un lavoro automatico interrotto tiene esattamente il resto. «Riconosci le copie già presenti» gira davvero in «Studio Lumen» (una copia riconosciuta, un file diverso): in «Disco USB» avrebbe allungato ogni avvio della dimostrazione di 47 s. Le prove della dimostrazione controllano questi dati e che un lavoratore di prova riprenda solo il lavoro interrotto. Le prove dell'interfaccia (nella CI) coprono la domanda «Solo i nuovi», la nota allo spegnimento, l'etichetta «Automatica dal …», «Riconosci» con il suo lavoro nella Dashboard, la pausa con i file che aspettano e la conferma di «Usa la cartella generale». Schermata nuova 32, rifatte 15, 16, 17 e 21, con le differenze dai mockup in differenze.md e una riga in decisioni.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
429 lines
26 KiB
C#
429 lines
26 KiB
C#
using System.IO.Compression;
|
|
using System.Net;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Export;
|
|
using Febe.Core.Library;
|
|
using Febe.Core.Storage;
|
|
using Febe.Tests.Support;
|
|
using Febe.Tests.Web.Support;
|
|
using Febe.Web.Demo;
|
|
using Febe.Web.Export;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace Febe.Tests.Web;
|
|
|
|
/// <summary>
|
|
/// The copies of the demo (spec §10.6, tappa E2) tell one story everywhere: the block «Copie esterne» of each account
|
|
/// counts what the «Copie» filter finds and what the tiles mark; every job has its files; a copy «Copiato» is a real
|
|
/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there. Tappa E3:
|
|
/// a copy converted to PNG, a frame of a video and two conversions of the library, which the demo never runs.
|
|
/// </summary>
|
|
[TestClass]
|
|
public sealed class DemoExportTests
|
|
{
|
|
public TestContext TestContext { get; set; } = null!;
|
|
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task TheDemoExportDataIsCoherent()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
using var temp = new TempFolder("demo-export-coerente");
|
|
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path), ct);
|
|
using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) };
|
|
|
|
async Task<JsonElement> GetAsync(string path)
|
|
{
|
|
using var response = await client.GetAsync(path, ct);
|
|
var text = await response.Content.ReadAsStringAsync(ct);
|
|
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
|
|
return JsonDocument.Parse(text).RootElement.Clone();
|
|
}
|
|
|
|
// Every tile of a query, following the cursors.
|
|
async Task<List<JsonElement>> AllTilesAsync(string query)
|
|
{
|
|
var tiles = new List<JsonElement>();
|
|
string? cursor = null;
|
|
for (var page = 0; page < 100; page++)
|
|
{
|
|
var answer = await GetAsync($"/api/library?{query}&limit=1000" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor)));
|
|
tiles.AddRange(answer.Items("tiles"));
|
|
if (answer.GetProperty("older").ValueKind == JsonValueKind.Null)
|
|
{
|
|
return tiles;
|
|
}
|
|
|
|
cursor = answer.Str("older");
|
|
}
|
|
|
|
Assert.Fail($"too many pages for {query}");
|
|
return tiles;
|
|
}
|
|
|
|
// The copies and their files.
|
|
var destinations = await demo.Storage.Exports.ListDestinationsAsync(includeRetired: true, ct);
|
|
Assert.IsGreaterThanOrEqualTo(2, destinations.Count);
|
|
var states = new HashSet<ExportCopyState>();
|
|
var forms = new List<ExportCopy>();
|
|
foreach (var destination in destinations)
|
|
{
|
|
Assert.IsTrue(Directory.Exists(destination.RootPath), destination.RootPath);
|
|
foreach (var copy in await demo.Storage.Exports.ListCopiesAsync(destination.Id, null, 0, 100_000, ct))
|
|
{
|
|
states.Add(copy.State);
|
|
if (copy.State == ExportCopyState.Copied && copy.Variant != ExportVariant.Whole)
|
|
{
|
|
forms.Add(copy);
|
|
}
|
|
|
|
var path = copy.RelativePath is { } relative ? Path.Combine(destination.RootPath, LibraryLayout.ToPlatform(relative)) : null;
|
|
switch (copy.State)
|
|
{
|
|
case ExportCopyState.Copied:
|
|
Assert.IsTrue(File.Exists(path), $"«Copiato» without its file: {path}");
|
|
Assert.AreEqual(copy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path!, ct))), path);
|
|
Assert.AreEqual(copy.Bytes, new FileInfo(path!).Length, path);
|
|
break;
|
|
case ExportCopyState.Removed:
|
|
Assert.IsFalse(path is not null && File.Exists(path), $"«Tolto» with a file: {path}");
|
|
break;
|
|
case ExportCopyState.Superseded:
|
|
Assert.IsTrue(File.Exists(path), $"the old file of «Superato» stays: {path}");
|
|
Assert.AreEqual(copy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path!, ct))), path);
|
|
break;
|
|
case ExportCopyState.Failed:
|
|
Assert.IsFalse(string.IsNullOrEmpty(copy.LastError), "a failure says why");
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
CollectionAssert.AreEquivalent(
|
|
new[] { ExportCopyState.Copied, ExportCopyState.Removed, ExportCopyState.Superseded, ExportCopyState.Failed },
|
|
states.ToArray(),
|
|
"the demo shows every state of a copy");
|
|
Assert.IsFalse(Directory.EnumerateFiles(temp.Path, "*.part", SearchOption.AllDirectories).Any(f => f.Contains("esporta", StringComparison.Ordinal)), "no .part left");
|
|
|
|
// Every job has its files, and a finished one has none pending.
|
|
var runs = await demo.Storage.Exports.ListRecentRunsAsync(100, ct);
|
|
Assert.IsNotEmpty(runs);
|
|
foreach (var run in runs)
|
|
{
|
|
var summary = await demo.Storage.Exports.GetRunSummaryAsync(run.Id, ct);
|
|
Assert.IsGreaterThan(0, summary.Total, $"job {run.Id}");
|
|
if (run.State == ExportRunState.Completed)
|
|
{
|
|
Assert.AreEqual(0, summary.ByState.GetValueOrDefault(ExportItemState.Pending), $"job {run.Id}");
|
|
}
|
|
}
|
|
|
|
// Each account: the card, the filter and the marks count the same files.
|
|
var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList();
|
|
var checkedAccounts = 0;
|
|
foreach (var account in accounts)
|
|
{
|
|
var id = account.Long("id");
|
|
var card = (await GetAsync($"/api/accounts/{id}")).GetProperty("export");
|
|
// The card counts every due file of the account, its profile pictures too, which «Tutto» leaves out.
|
|
async Task<int> FilesAsync(string copies) =>
|
|
(await GetAsync($"/api/library/days?accounts={id}&mode=files&copies={copies}")).Int("files")
|
|
+ (await GetAsync($"/api/library/days?accounts={id}&mode=files&kind=profile&copies={copies}")).Int("files");
|
|
var copied = card.Int("due") - card.Int("notCopied") - card.Int("removedOrSuperseded");
|
|
Assert.AreEqual(card.Int("notCopied"), await FilesAsync("notCopied"), account.Str("username"));
|
|
Assert.AreEqual(card.Int("removedOrSuperseded"), await FilesAsync("removedOrSuperseded"), account.Str("username"));
|
|
Assert.AreEqual(copied, await FilesAsync("copied"), account.Str("username"));
|
|
Assert.IsLessThanOrEqualTo(card.Int("notCopied"), card.Int("failed"), "a failed file is one still to copy");
|
|
|
|
var grouped = await AllTilesAsync($"accounts={id}");
|
|
if (!card.Bool("enabled"))
|
|
{
|
|
Assert.AreEqual(0, card.Int("due"), account.Str("username"));
|
|
Assert.IsTrue(grouped.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "an account that is not exported has no marks");
|
|
continue;
|
|
}
|
|
|
|
var marked = grouped.Where(t => t.Str("copies") == "copied").Select(t => t.Long("id")).ToHashSet();
|
|
var filtered = (await AllTilesAsync($"accounts={id}&copies=copied")).Select(t => t.Long("id")).ToHashSet();
|
|
Assert.IsTrue(marked.SetEquals(filtered), $"{account.Str("username")}: the mark «copiato» is the filter «Copiati»");
|
|
foreach (var partly in grouped.Where(t => t.Str("copies") == "partly"))
|
|
{
|
|
Assert.IsGreaterThan(0, partly.Int("copiesDone"));
|
|
Assert.IsLessThan(partly.Int("copiesDue"), partly.Int("copiesDone"));
|
|
}
|
|
|
|
var fileMarks = (await AllTilesAsync($"accounts={id}&mode=files")).Count(t => t.Str("copies") == "copied")
|
|
+ (await AllTilesAsync($"accounts={id}&mode=files&kind=profile")).Count(t => t.Str("copies") == "copied");
|
|
Assert.AreEqual(copied, fileMarks, $"{account.Str("username")}: one mark per copied file");
|
|
checkedAccounts += card.Int("due") > 0 ? 1 : 0;
|
|
}
|
|
|
|
Assert.IsGreaterThanOrEqualTo(2, checkedAccounts, "the demo has accounts with files to copy");
|
|
|
|
// Tappa E3: the converted copy (by the real engine) and the frame are real files with their SHA-256 (checked above).
|
|
var convertedCopy = forms.SingleOrDefault(c => c.Variant == ExportVariant.Converted);
|
|
Assert.IsNotNull(convertedCopy, "a copy converted to PNG");
|
|
Assert.AreEqual(ExportFormat.Png, convertedCopy.Format);
|
|
StringAssert.EndsWith(convertedCopy.RelativePath, ".png");
|
|
var frameCopy = forms.Single(c => c.Variant == ExportVariant.Frame);
|
|
Assert.AreEqual(TimeSpan.FromMilliseconds(1125), frameCopy.FrameAt, "1.234 s shows the picture shown from 1.125 s");
|
|
StringAssert.EndsWith(frameCopy.RelativePath, "_t0m01s125.png");
|
|
|
|
// The demo video gives frames: the preview of that instant is the frame copied.
|
|
var videoId = frameCopy.MediaId!.Value;
|
|
var info = await GetAsync($"/api/media/{videoId}/frames/info");
|
|
Assert.IsTrue(info.Bool("available"), info.ToString());
|
|
Assert.AreEqual(2000L, info.Long("durationMs"));
|
|
using (var frame = await client.GetAsync($"/api/media/{videoId}/frame?at=1234&format=png&download=1", ct))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.OK, frame.StatusCode);
|
|
Assert.AreEqual("image/png", frame.Content.Headers.ContentType?.MediaType);
|
|
Assert.AreEqual(frameCopy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await frame.Content.ReadAsByteArrayAsync(ct))));
|
|
}
|
|
|
|
var video = await demo.Storage.Media.GetAsync(videoId, ct);
|
|
var viewer = (await GetAsync($"/api/entries/{video!.EntryId}")).Items("media").Single(m => m.Long("id") == videoId);
|
|
Assert.IsTrue(viewer.Bool("framesAvailable"));
|
|
var frameRow = viewer.Items("copies").Single(c => c.Str("variant") == "frame");
|
|
Assert.AreEqual(1125L, frameRow.Long("frameAtMs"));
|
|
Assert.AreEqual("0:01,125", frameRow.Str("frameLabel"));
|
|
|
|
// Two conversions of the library, which the demo never runs: nothing waits and nothing changes.
|
|
var conversion = await GetAsync("/api/export/library-conversion");
|
|
Assert.AreEqual(0, conversion.Int("pending"));
|
|
Assert.AreEqual(1, conversion.Int("converted"));
|
|
Assert.AreEqual(1, conversion.Int("asIs"));
|
|
Assert.AreEqual(0, conversion.Int("failed"));
|
|
var (rowId, file) = demo.World.ConversionFiles.Single();
|
|
var row = await demo.Storage.Conversions.GetAsync(rowId, ct);
|
|
Assert.AreEqual(MediaConversionState.Converted, row!.State);
|
|
using (var converted = await client.GetAsync($"/api/conversions/{rowId}/file", ct))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.OK, converted.StatusCode);
|
|
Assert.AreEqual("image/png", converted.Content.Headers.ContentType?.MediaType);
|
|
Assert.AreEqual(row.Sha256, Convert.ToHexStringLower(SHA256.HashData(await converted.Content.ReadAsByteArrayAsync(ct))));
|
|
}
|
|
|
|
var photo = await demo.Storage.Media.GetAsync(row.MediaId, ct);
|
|
var shown = (await GetAsync($"/api/entries/{photo!.EntryId}")).Items("media").Single(m => m.Long("id") == row.MediaId);
|
|
var shownRow = shown.Items("conversions").Single();
|
|
Assert.AreEqual("converted", shownRow.Str("state"));
|
|
Assert.AreEqual("png", shownRow.Str("format"));
|
|
Assert.IsTrue(shownRow.Bool("available"));
|
|
await Task.Delay(TimeSpan.FromSeconds(1), ct);
|
|
Assert.AreEqual(MediaConversionState.Converted, (await demo.Storage.Conversions.GetAsync(rowId, ct))!.State, "the demo never converts");
|
|
Assert.IsTrue(File.Exists(file));
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task TheDemoGivesFramesAndPlansTheFormats()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
using var temp = new TempFolder("demo-export-formati");
|
|
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path), ct);
|
|
using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) };
|
|
var origin = demo.Address.GetLeftPart(UriPartial.Authority);
|
|
|
|
async Task<JsonElement> SendAsync(HttpMethod method, string path, string? json = null)
|
|
{
|
|
using var request = new HttpRequestMessage(method, path);
|
|
request.Headers.TryAddWithoutValidation("Origin", origin);
|
|
if (json is not null)
|
|
{
|
|
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
|
|
}
|
|
|
|
using var response = await client.SendAsync(request, ct);
|
|
var text = await response.Content.ReadAsStringAsync(ct);
|
|
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
|
|
return JsonDocument.Parse(text).RootElement.Clone();
|
|
}
|
|
|
|
// Entries of @marta.demo with a video cover and with a photo cover (the demo places them by the hour: asked).
|
|
var marta = (await SendAsync(HttpMethod.Get, "/api/accounts")).Items("accounts").Single(a => a.Str("username") == "marta.demo").Long("id");
|
|
var tiles = (await SendAsync(HttpMethod.Get, $"/api/library?accounts={marta}&limit=1000")).Items("tiles").ToList();
|
|
var videos = tiles.Where(t => t.GetProperty("cover").ValueKind == JsonValueKind.Object && t.GetProperty("cover").Str("kind") == "video").Take(2).Select(t => t.Long("id")).ToList();
|
|
var photos = tiles.Where(t => t.GetProperty("cover").ValueKind == JsonValueKind.Object && t.GetProperty("cover").Str("kind") == "photo").Take(3).Select(t => t.Long("id")).ToList();
|
|
Assert.HasCount(2, videos, "the demo has videos of marta.demo");
|
|
Assert.IsNotEmpty(photos, "the demo has photos of marta.demo");
|
|
|
|
// «Fotogrammi…» of a selection: two in all of each video, the photos skipped, a zip named as the copies.
|
|
var selection = $"{{ \"entryIds\": [{string.Join(", ", videos.Concat(photos))}], \"frames\": {{ \"mode\": \"numero\", \"count\": 2, \"format\": \"png\" }} }}";
|
|
var plan = await SendAsync(HttpMethod.Post, "/api/frames/plan", selection);
|
|
Assert.IsGreaterThanOrEqualTo(2, plan.Int("videos"), plan.ToString());
|
|
Assert.IsGreaterThan(0, plan.Int("photosSkipped"), plan.ToString());
|
|
Assert.AreEqual(0, plan.Int("notAvailable"), "every video of the demo gives frames");
|
|
Assert.AreEqual(2 * plan.Int("videos"), plan.Int("frames"));
|
|
StringAssert.Contains(plan.Str("summary"), " si salt", plan.Str("summary"));
|
|
var token = await SendAsync(HttpMethod.Post, "/api/frames/download-token", selection);
|
|
Assert.AreEqual(plan.Int("frames"), token.Int("frames"));
|
|
using (var zip = await client.GetAsync(token.Str("url"), ct))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode);
|
|
using var archive = new ZipArchive(new MemoryStream(await zip.Content.ReadAsByteArrayAsync(ct)), ZipArchiveMode.Read);
|
|
Assert.HasCount(plan.Int("frames"), archive.Entries);
|
|
foreach (var entry in archive.Entries)
|
|
{
|
|
StringAssert.StartsWith(entry.FullName, "marta.demo/", entry.FullName);
|
|
Assert.IsTrue(Regex.IsMatch(entry.FullName, @"_f00[12]\.png$"), entry.FullName);
|
|
using var read = entry.Open();
|
|
var head = new byte[8];
|
|
read.ReadExactly(head);
|
|
CollectionAssert.AreEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, head, entry.FullName);
|
|
}
|
|
}
|
|
|
|
// «Copia in…» of photos not copied yet (a new format is for those): PNG converts the JPG photos of the demo,
|
|
// without loss; JPG copies them byte for byte.
|
|
var notCopied = (await SendAsync(HttpMethod.Get, $"/api/library?accounts={marta}&copies=notCopied&limit=1000")).Items("tiles")
|
|
.Where(t => t.GetProperty("cover").ValueKind == JsonValueKind.Object && t.GetProperty("cover").Str("kind") == "photo").Take(3).Select(t => t.Long("id")).ToList();
|
|
Assert.IsNotEmpty(notCopied, "the demo has photos of marta.demo not copied yet");
|
|
var photoIds = string.Join(", ", notCopied);
|
|
var png = await SendAsync(HttpMethod.Post, "/api/export/plan", $"{{ \"entryIds\": [{photoIds}], \"copyAgain\": false, \"photoFormat\": \"png\" }}");
|
|
Assert.IsGreaterThan(0, png.Int("converted"), png.ToString());
|
|
Assert.IsFalse(png.Bool("lossy"), png.ToString());
|
|
var jpg = await SendAsync(HttpMethod.Post, "/api/export/plan", $"{{ \"entryIds\": [{photoIds}], \"copyAgain\": false, \"photoFormat\": \"jpg\" }}");
|
|
Assert.AreEqual(0, jpg.Int("converted"), jpg.ToString());
|
|
Assert.IsFalse(jpg.Bool("lossy"), "a JPG already JPG is copied as it is, never encoded again");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Tappa E5: «Studio Lumen» is «Automatica» with «Solo i nuovi» since a past instant; an automatic job of the engine
|
|
/// copied part of the new files and a job left «interrotto» holds exactly the rest (what the automatic copies would do
|
|
/// next); a «Riconosci» there recognised one copy, found one different file and wrote nothing. The demo
|
|
/// runs no worker: the overview has no automatic status and counts only Alberto's jobs to resume.
|
|
/// </summary>
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task TheDemoSeedsTheAutomaticCopiesAndARecognition()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
using var temp = new TempFolder("demo-export-automatica");
|
|
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path), ct);
|
|
using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) };
|
|
|
|
async Task<JsonElement> GetAsync(string path)
|
|
{
|
|
using var response = await client.GetAsync(path, ct);
|
|
var text = await response.Content.ReadAsStringAsync(ct);
|
|
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
|
|
return JsonDocument.Parse(text).RootElement.Clone();
|
|
}
|
|
|
|
var now = demo.App.Services.GetRequiredService<IClock>().Now;
|
|
var exports = demo.Storage.Exports;
|
|
var destinations = await exports.ListDestinationsAsync(includeRetired: false, ct);
|
|
var own = destinations.Single(d => d.Scope == ExportScope.Account);
|
|
var general = destinations.Single(d => d.Scope == ExportScope.General);
|
|
Assert.AreEqual(DemoExport.OwnFolder, own.Label);
|
|
Assert.IsTrue(own.Automatic, "«Studio Lumen» is «Automatica»");
|
|
Assert.IsNotNull(own.AutomaticSince, "with «Solo i nuovi»");
|
|
Assert.IsLessThan(now, own.AutomaticSince.Value, "since a past instant");
|
|
Assert.IsFalse(general.Automatic, "«Disco USB» is not");
|
|
|
|
// One automatic job finished (by the engine: real copies of files saved since then), one left «interrotto».
|
|
var runs = await exports.ListRunsAsync(ct);
|
|
var automatic = runs.Where(r => r.Origin == ExportRunOrigin.Automatic).ToList();
|
|
Assert.IsTrue(automatic.All(r => r.DestinationId == own.Id && r.Kind == ExportRunKind.Copy), "only the automatic folder has automatic jobs");
|
|
var finished = automatic.Single(r => r.State == ExportRunState.Completed);
|
|
var stopped = automatic.Single(r => r.State != ExportRunState.Completed);
|
|
Assert.AreEqual(ExportRunState.Interrupted, stopped.State);
|
|
Assert.IsNull(stopped.LastError, "stopped by the last stop: it resumes at any pass");
|
|
Assert.IsGreaterThan(finished.StartedAt, stopped.StartedAt, "the interrupted job is the newer one");
|
|
Assert.IsLessThan(now, finished.StartedAt, "a job of the past");
|
|
var done = await exports.GetRunSummaryAsync(finished.Id, ct);
|
|
Assert.IsGreaterThan(0, done.ByState.GetValueOrDefault(ExportItemState.Copied), "the automatic job copied");
|
|
Assert.AreEqual(done.Total, done.ByState.GetValueOrDefault(ExportItemState.Copied), "only files to write, all written");
|
|
foreach (var item in await exports.ListItemsAsync(new ExportItemQuery { RunId = finished.Id, Limit = 10_000 }, ct))
|
|
{
|
|
var media = await demo.Storage.Media.GetAsync(item.MediaId!.Value, ct);
|
|
Assert.IsGreaterThanOrEqualTo(own.AutomaticSince.Value, media!.DownloadedAt!.Value, "a file saved since «Automatica» went on");
|
|
}
|
|
|
|
var pending = await exports.ListItemsAsync(new ExportItemQuery { RunId = stopped.Id, Limit = 10_000 }, ct);
|
|
Assert.IsNotEmpty(pending);
|
|
Assert.IsTrue(pending.All(i => i.State == ExportItemState.Pending), "nothing of it done yet");
|
|
|
|
// What the automatic copies would do next is exactly that job: the files to copy are its files, in a round too.
|
|
foreach (var round in new[] { false, true })
|
|
{
|
|
var selection = new ExportSelection.Automatic([new(own.Id, own.AutomaticSince)], [], round);
|
|
var candidates = await exports.ListCandidatesAsync(selection, 0, 10_000, ct);
|
|
CollectionAssert.AreEquivalent(
|
|
pending.Select(i => i.SourceSha256).ToArray(),
|
|
candidates.Select(c => c.Sha256).Distinct().ToArray(),
|
|
$"round {round}: the new files not copied yet are those of the interrupted job");
|
|
}
|
|
|
|
// «Riconosci le copie già presenti» in «Studio Lumen»: one recognised, one different, the others not there.
|
|
var recognize = runs.Single(r => r.Kind == ExportRunKind.Recognize);
|
|
Assert.AreEqual((own.Id, ExportRunOrigin.Manual, ExportRunState.Completed), (recognize.DestinationId, recognize.Origin, recognize.State));
|
|
var report = await GetAsync($"/api/export/runs/{recognize.Id}/report");
|
|
Assert.AreEqual(1, report.GetProperty("byState").Int("adopted"), report.ToString());
|
|
Assert.AreEqual(1, report.Int("different"), report.ToString());
|
|
Assert.IsGreaterThan(0, report.Int("notFound"), report.ToString());
|
|
Assert.AreEqual(0, report.GetProperty("byState").Int("copied"), "«Riconosci» writes nothing");
|
|
var adopted = (await exports.ListItemsAsync(new ExportItemQuery { RunId = recognize.Id, State = ExportItemState.Adopted }, ct)).Single();
|
|
var row = await exports.GetCopyAsync(adopted.CopyId!.Value, ct);
|
|
Assert.AreEqual((ExportCopyState.Copied, ExportCopyOrigin.Adopted), (row!.State, row.Origin));
|
|
var events = await demo.Storage.Events.ListAsync(new() { Limit = 500 }, ct);
|
|
Assert.AreEqual(1, events.Count(e => e.Code == ExportText.RecognizeEventCode), "its own event");
|
|
Assert.IsTrue(events.Any(e => e.Code == "esportazione-completata" && e.Message.StartsWith("Copia automatica in Studio Lumen finita", StringComparison.Ordinal)), "the automatic job's event");
|
|
|
|
// The interface: the folder says since when, the lists know the automatic jobs, the demo has no automatic status.
|
|
var overview = await GetAsync("/api/export");
|
|
Assert.AreEqual(JsonValueKind.Null, overview.GetProperty("automatic").ValueKind, "no worker in the demo");
|
|
Assert.AreEqual(1, overview.Int("unfinishedRuns"), "only Alberto's job to resume counts");
|
|
var ownDto = overview.Items("own").Single();
|
|
Assert.IsTrue(ownDto.Bool("automatic"));
|
|
Assert.AreEqual(JsonValueKind.Object, ownDto.GetProperty("automaticSince").ValueKind);
|
|
Assert.IsFalse(overview.GetProperty("general").Bool("automatic"));
|
|
var unfinished = (await GetAsync("/api/export/runs?unfinished=true")).EnumerateArray().ToList();
|
|
Assert.HasCount(2, unfinished);
|
|
Assert.AreEqual("automatic", unfinished.Single(r => r.Long("id") == stopped.Id).Str("origin"));
|
|
var recent = (await GetAsync("/api/export/runs?limit=20")).EnumerateArray().ToList();
|
|
Assert.AreEqual("recognize", recent.Single(r => r.Long("id") == recognize.Id).Str("kind"));
|
|
Assert.AreEqual("automatic", recent.Single(r => r.Long("id") == finished.Id).Str("origin"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// The demo never starts the automatic worker, and has nothing for it but its interrupted job: a worker of the test on
|
|
/// the demo's database resumes that job at its first pass, then finds nothing to copy.
|
|
/// </summary>
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task TheDemoSeedHasNothingToCopyAutomaticallyButItsInterruptedJob()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
using var temp = new TempFolder("demo-export-niente-da-copiare");
|
|
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path), ct);
|
|
var services = demo.App.Services;
|
|
var demoWorker = services.GetRequiredService<AutoExportWorker>();
|
|
Assert.IsFalse(demoWorker.Running, "the demo does not start the worker");
|
|
|
|
var hub = services.GetRequiredService<ExportHub>();
|
|
var worker = new AutoExportWorker(new AutoExportEnvironment
|
|
{
|
|
Storage = demo.Storage,
|
|
Clock = services.GetRequiredService<IClock>(),
|
|
Service = hub.GetAsync,
|
|
Signal = new AutoExportSignal(),
|
|
Gate = services.GetRequiredService<LongWorkGate>(),
|
|
});
|
|
var stopped = (await demo.Storage.Exports.ListUnfinishedRunsAsync(ct)).Single(r => r.Origin == ExportRunOrigin.Automatic);
|
|
|
|
Assert.AreEqual(AutoExportPass.Started, await worker.RunOnceAsync(round: false, ct), "the interrupted job is resumed");
|
|
await (await hub.GetAsync(ct)).WaitAsync(ct);
|
|
Assert.AreEqual(ExportRunState.Completed, (await demo.Storage.Exports.GetRunAsync(stopped.Id, ct))!.State);
|
|
Assert.IsEmpty((await demo.Storage.Exports.ListUnfinishedRunsAsync(ct)).Where(r => r.Origin == ExportRunOrigin.Automatic));
|
|
Assert.AreEqual(AutoExportPass.NothingToDo, await worker.RunOnceAsync(round: false, ct), "then nothing is new");
|
|
Assert.IsFalse(demoWorker.Running);
|
|
}
|
|
}
|