E5: API e interfaccia delle copie automatiche e di «Riconosci»
L'interfaccia di programmazione e le pagine mostrano e usano ciò che i
pacchetti precedenti hanno costruito nel nucleo.
- API: le modifiche delle destinazioni passano da ChangeDestinationAsync
(spegnere «Automatica» ferma subito la sua copia automatica, risposta
52); nuova /api/export/automatic-preview (switchOn, widen, removeOwn,
account) per la domanda «Solo i nuovi / Copia anche gli N» e i file in
più (risposta 55); /destinations/{id}/recognize; /automatic/resume
(«Riprendi ora»); «Interrompi» su una copia automatica dice fino a che
ora le copie automatiche restano ferme (risposta 53); runs?unfinished;
avanzamento con tipo e origine; destinazioni con «dal» e i file che
aspettano una cartella in pausa; stato delle copie automatiche nella
panoramica (null senza il lavoratore, quindi nella dimostrazione);
«da riprendere» conta solo i lavori di Alberto.
- Interfaccia: l'interruttore «Automatica» nella finestra della
destinazione con la domanda all'accensione, i file in più e l'avviso
allo spegnimento; stato della cartella condiviso da Impostazioni e
scheda account (pausa «dal …», file che aspettano, «Riprova»,
«Controlla le copie», «Riconosci le copie già presenti»); Dashboard con
i nomi dei lavori automatici e di riconoscimento, la riga delle copie
automatiche con «Riprendi ora», «Da riprendere» con ogni lavoro non
finito e la copia manuale pronta a ripartire (risposta 48).
- Prove API in ExportApiTests.Automatic.cs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e66e322d35
commit
f8491529ca
12 files changed
+1247
-113
No files matched your search
@@ -0,0 +1,403 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Export.Support;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web.Export;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The automatic copies over the API (tappa E5, §3.1 of its design): the question «Solo i nuovi / Copia anche gli N»
|
||||
/// and the files in more, «Riconosci le copie già presenti», «Automatica» turned off, «Automatica dal …» and the files
|
||||
/// that wait for a folder in pause, the status of the automatic copies, «Da riprendere», «Interrompi» and «Riprendi ora».
|
||||
/// </summary>
|
||||
public sealed partial class ExportApiTests
|
||||
{
|
||||
private static readonly string[] AllTypes = ["postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo"];
|
||||
|
||||
[TestMethod]
|
||||
public async Task AutomaticPreviewCountsTheBacklog()
|
||||
{
|
||||
await using var server = await StartAsync();
|
||||
var marta = await AddPhotosAsync(server, "marta.demo", 3);
|
||||
var luca = await AddPhotosAsync(server, "luca.demo", 2);
|
||||
var (generalId, usb) = await GeneralAsync(server);
|
||||
var nas = server.Temp.Combine("nas");
|
||||
Directory.CreateDirectory(nas);
|
||||
|
||||
// «Automatica» turned on for the general folder: the files of both accounts, none copied yet, as «Copia in…» counts them.
|
||||
var on = await PreviewAsync(server, new { mode = "switchOn", destinationId = generalId, scope = "general", path = usb, types = AllTypes });
|
||||
Assert.AreEqual(5, on.Int("files"), on.ToString());
|
||||
Assert.AreEqual(await PlanFilesAsync(server, marta.Account.Id) + await PlanFilesAsync(server, luca.Account.Id), on.Int("files"));
|
||||
Assert.IsGreaterThan(0L, on.Long("bytes"));
|
||||
StringAssert.StartsWith(on.Str("text"), "Copia anche i 5 già in libreria: circa ");
|
||||
Assert.AreEqual(Free, on.Long("freeBytes"), "the space of the stored folder");
|
||||
|
||||
// A file copied by hand is no longer counted; in another folder (a new destination) nothing is copied yet.
|
||||
await StartAndWaitAsync(server, new { mediaIds = new[] { marta.Entries[0].Media[0].Id } });
|
||||
Assert.AreEqual(4, (await PreviewAsync(server, new { mode = "switchOn", destinationId = generalId, scope = "general", path = usb, types = AllTypes })).Int("files"));
|
||||
var moved = await PreviewAsync(server, new { mode = "switchOn", destinationId = generalId, scope = "general", path = nas, types = AllTypes });
|
||||
Assert.AreEqual(5, moved.Int("files"), "a new folder has no copies");
|
||||
Assert.AreEqual(JsonValueKind.Null, moved.GetProperty("freeBytes").ValueKind);
|
||||
var none = await PreviewAsync(server, new { mode = "switchOn", destinationId = generalId, scope = "general", path = usb, types = new[] { "storie" } });
|
||||
Assert.AreEqual(0, none.Int("files"));
|
||||
Assert.AreEqual("Nessun file già in libreria da copiare qui.", none.Str("text"));
|
||||
|
||||
// A new own folder of luca: his two files, none copied there.
|
||||
var own = await PreviewAsync(server, new { mode = "switchOn", scope = "account", accountId = luca.Account.Id, path = nas, types = AllTypes });
|
||||
Assert.AreEqual(2, own.Int("files"));
|
||||
|
||||
// «Widen»: the general folder automatic with videos only, «Copia anche quelli già in libreria»; adding the photos
|
||||
// adds the four photos not copied (answer 55: no new question).
|
||||
var (put, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb, types: ["postVideo"], automatic: true, onlyNew: false));
|
||||
Assert.AreEqual(HttpStatusCode.OK, put, saved.ToString());
|
||||
var widen = await PreviewAsync(server, new { mode = "widen", destinationId = generalId, types = new[] { "postVideo", "postFoto" } });
|
||||
Assert.AreEqual(4, widen.Int("files"), widen.ToString());
|
||||
Assert.AreEqual("4 file in più si copieranno da soli.", widen.Str("text"));
|
||||
Assert.AreEqual(0, (await PreviewAsync(server, new { mode = "widen", destinationId = generalId, types = new[] { "postVideo" } })).Int("files"), "no type added");
|
||||
|
||||
// «Solo i nuovi» keeps the files saved before the switch out of what is added.
|
||||
server.Clock.Now += TimeSpan.FromMinutes(5);
|
||||
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb, types: ["postVideo"]))).Status);
|
||||
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb, types: ["postVideo"], automatic: true))).Status);
|
||||
Assert.AreEqual(0, (await PreviewAsync(server, new { mode = "widen", destinationId = generalId, types = AllTypes })).Int("files"), "every photo was saved before");
|
||||
server.Clock.Now += TimeSpan.FromMinutes(1);
|
||||
await AddPostAsync(server, luca.Account, "luca.demo-nuovo", 40);
|
||||
Assert.AreEqual(1, (await PreviewAsync(server, new { mode = "widen", destinationId = generalId, types = AllTypes })).Int("files"), "the photo saved after");
|
||||
|
||||
// An own folder taken away while the general folder is automatic (since null): luca's files go there by themselves.
|
||||
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb))).Status);
|
||||
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb, automatic: true, onlyNew: false))).Status);
|
||||
var (ownStatus, ownSaved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(nas, scope: "account", accountId: luca.Account.Id));
|
||||
Assert.AreEqual(HttpStatusCode.OK, ownStatus, ownSaved.ToString());
|
||||
var remove = await PreviewAsync(server, new { mode = "removeOwn", accountId = luca.Account.Id });
|
||||
Assert.AreEqual(3, remove.Int("files"), remove.ToString());
|
||||
Assert.AreEqual("3 file di @luca.demo andranno da soli nella cartella generale.", remove.Str("text"));
|
||||
Assert.AreEqual(0, (await PreviewAsync(server, new { mode = "account", accountId = luca.Account.Id })).Int("files"), "his own folder is not automatic");
|
||||
var martaAccount = await PreviewAsync(server, new { mode = "account", accountId = marta.Account.Id });
|
||||
Assert.AreEqual(2, martaAccount.Int("files"), "marta's files not copied, in the automatic general folder");
|
||||
|
||||
// Once the own folder is gone, the plan of «Copia in…» agrees with what was announced.
|
||||
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{ownSaved.GetProperty("destination").Long("id")}")).Status);
|
||||
Assert.AreEqual(3, await PlanFilesAsync(server, luca.Account.Id));
|
||||
|
||||
// Requests that make no sense are refused in Italian.
|
||||
foreach (var bad in new object[]
|
||||
{
|
||||
new { mode = "boh" },
|
||||
new { mode = "switchOn", scope = "general", path = usb, types = new[] { "nessuno" } },
|
||||
new { mode = "switchOn", scope = "account", path = nas, types = AllTypes },
|
||||
new { mode = "switchOn", scope = "account", accountId = 999_999L, path = nas, types = AllTypes },
|
||||
new { mode = "removeOwn" },
|
||||
})
|
||||
{
|
||||
var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic-preview", bad);
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, status, answer.ToString());
|
||||
Assert.IsNotEmpty(answer.Str("message"));
|
||||
}
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic-preview", new { mode = "widen", destinationId = 999_999L, types = AllTypes })).Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecognizeStartsARun()
|
||||
{
|
||||
await using var server = await StartAsync();
|
||||
var marta = await AddPhotosAsync(server, "marta.demo", 3);
|
||||
var (oldId, usb) = await GeneralAsync(server);
|
||||
await StartAndWaitAsync(server, new { accountId = marta.Account.Id });
|
||||
|
||||
// The copies in another folder, as Alberto could have made them himself: one the same, one missing, one different.
|
||||
var nas = server.Temp.Combine("nas");
|
||||
foreach (var file in Directory.GetFiles(usb, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var target = Path.Combine(nas, Path.GetRelativePath(usb, file));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
File.Copy(file, target);
|
||||
}
|
||||
|
||||
var copies = Directory.GetFiles(nas, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal).ToList();
|
||||
Assert.HasCount(3, copies);
|
||||
File.Delete(copies[1]);
|
||||
await File.WriteAllTextAsync(copies[2], "un altro file");
|
||||
var (put, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{oldId}", Destination(nas));
|
||||
Assert.AreEqual(HttpStatusCode.OK, put, saved.ToString());
|
||||
var nasId = saved.GetProperty("destination").Long("id");
|
||||
Assert.AreNotEqual(oldId, nasId, "a new folder is a new destination");
|
||||
var before = Directory.GetFiles(nas, "*", SearchOption.AllDirectories).ToDictionary(f => f, File.ReadAllBytes);
|
||||
|
||||
var (status, started) = await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{nasId}/recognize");
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, started.ToString());
|
||||
Assert.AreEqual(Febe.Web.Api.ExportApi.RecognizeStartedText, started.Str("message"));
|
||||
var runId = started.Long("runId");
|
||||
await WaitIdleAsync(server);
|
||||
|
||||
var progress = await server.GetJsonAsync("/api/export/progress");
|
||||
Assert.AreEqual(runId, progress.Long("runId"));
|
||||
Assert.AreEqual("recognize", progress.Str("kind"));
|
||||
Assert.AreEqual("manual", progress.Str("origin"));
|
||||
var run = (await server.GetJsonAsync("/api/export/runs")).EnumerateArray().First();
|
||||
Assert.AreEqual(runId, run.Long("id"));
|
||||
Assert.AreEqual("recognize", run.Str("kind"));
|
||||
Assert.AreEqual("completed", run.Str("state"));
|
||||
var report = await server.GetJsonAsync($"/api/export/runs/{runId}/report");
|
||||
Assert.AreEqual(1, report.GetProperty("byState").Int("adopted"), report.ToString());
|
||||
Assert.AreEqual(1, report.Int("notFound"), report.ToString());
|
||||
Assert.AreEqual(1, report.Int("different"), report.ToString());
|
||||
Assert.HasCount(1, report.Items("problems").ToList(), "only the different file needs a look");
|
||||
Assert.AreEqual(1, (await server.GetJsonAsync("/api/export")).GetProperty("general").GetProperty("counts").Int("copied"));
|
||||
|
||||
// Nothing was written, moved or removed in the folder.
|
||||
CollectionAssert.AreEquivalent(before.Keys.ToList(), Directory.GetFiles(nas, "*", SearchOption.AllDirectories));
|
||||
Assert.IsTrue(before.All(f => f.Value.AsSpan().SequenceEqual(File.ReadAllBytes(f.Key))));
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations/999999/recognize")).Status);
|
||||
var (retired, answer) = await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{oldId}/recognize");
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, retired, answer.ToString());
|
||||
Assert.IsNotEmpty(answer.Str("message"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TurningAutomaticOffCancelsItsAutomaticRuns()
|
||||
{
|
||||
await using var server = await StartAsync();
|
||||
await AddPhotosAsync(server, "marta.demo", 1);
|
||||
var usb = server.Temp.Combine("usb");
|
||||
Directory.CreateDirectory(usb);
|
||||
var (created, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, automatic: true, onlyNew: false));
|
||||
Assert.AreEqual(HttpStatusCode.OK, created, saved.ToString());
|
||||
var id = saved.GetProperty("destination").Long("id");
|
||||
Assert.IsTrue(saved.GetProperty("destination").Bool("automatic"));
|
||||
var exports = server.Db.Exports;
|
||||
var automatic = await exports.CreateRunAsync(new ExportRun { DestinationId = id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = server.Clock.Now });
|
||||
var manual = await exports.CreateRunAsync(new ExportRun { DestinationId = id, State = ExportRunState.Interrupted, StartedAt = server.Clock.Now });
|
||||
|
||||
// Turned off (answer 52): the automatic copy of the folder stops for good, the copies made by hand stay Alberto's.
|
||||
var (put, off) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{id}", Destination(usb));
|
||||
Assert.AreEqual(HttpStatusCode.OK, put, off.ToString());
|
||||
Assert.IsFalse(off.GetProperty("destination").Bool("automatic"));
|
||||
var stopped = (await exports.GetRunAsync(automatic.Id))!;
|
||||
Assert.AreEqual(ExportRunState.Cancelled, stopped.State);
|
||||
Assert.AreEqual(ExportText.AutomaticTurnedOff, stopped.LastError);
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await exports.GetRunAsync(manual.Id))!.State);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DestinationDtoExposesAutomaticSinceAndTheFilesThatWait()
|
||||
{
|
||||
await using var server = await StartAsync();
|
||||
var marta = await AddPhotosAsync(server, "marta.demo", 3);
|
||||
var luca = await AddPhotosAsync(server, "luca.demo", 2);
|
||||
var usb = server.Temp.Combine("usb");
|
||||
var nas = server.Temp.Combine("nas");
|
||||
Directory.CreateDirectory(usb);
|
||||
Directory.CreateDirectory(nas);
|
||||
server.Clock.Now += TimeSpan.FromMinutes(1);
|
||||
var (created, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, automatic: true));
|
||||
Assert.AreEqual(HttpStatusCode.OK, created, saved.ToString());
|
||||
var general = saved.GetProperty("destination");
|
||||
var id = general.Long("id");
|
||||
Assert.AreEqual(server.Clock.Now.ToUnixTimeMilliseconds(), general.GetProperty("automaticSince").Long("ms"), "«Solo i nuovi»: from now");
|
||||
Assert.AreEqual(JsonValueKind.Null, general.GetProperty("waiting").ValueKind, "not paused");
|
||||
|
||||
// Off, then on with «Copia anche quelli già in libreria»: no «dal».
|
||||
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{id}", Destination(usb))).Status);
|
||||
Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("general").GetProperty("automaticSince").ValueKind, "off");
|
||||
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{id}", Destination(usb, automatic: true, onlyNew: false))).Status);
|
||||
var all = (await server.GetJsonAsync("/api/export")).GetProperty("general");
|
||||
Assert.IsTrue(all.Bool("automatic"));
|
||||
Assert.AreEqual(JsonValueKind.Null, all.GetProperty("automaticSince").ValueKind, "everything due");
|
||||
|
||||
// In pause: the five files of the two accounts wait for it (one of luca's goes to his own folder once it has one).
|
||||
await server.Db.Exports.SetDestinationPausedAsync(id, server.Clock.Now, "La cartella non risponde.");
|
||||
var paused = (await server.GetJsonAsync("/api/export")).GetProperty("general");
|
||||
Assert.AreEqual(5, paused.Int("waiting"), paused.ToString());
|
||||
Assert.AreEqual("La cartella non risponde.", paused.Str("problem"));
|
||||
|
||||
// The account card shows the same folder, automatic, with what waits.
|
||||
var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export").GetProperty("destination");
|
||||
Assert.IsTrue(card.Bool("automatic"));
|
||||
Assert.AreEqual(5, card.Int("waiting"));
|
||||
|
||||
// A folder without «Automatica», in pause: what its unfinished jobs still have to copy.
|
||||
var (ownStatus, ownSaved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(nas, scope: "account", accountId: luca.Account.Id));
|
||||
Assert.AreEqual(HttpStatusCode.OK, ownStatus, ownSaved.ToString());
|
||||
var ownId = ownSaved.GetProperty("destination").Long("id");
|
||||
var run = await server.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = ownId, State = ExportRunState.Paused, StartedAt = server.Clock.Now });
|
||||
await server.Db.Exports.AddItemsAsync([.. luca.Entries.Select(e => e.Media[0]).Select(m => new ExportItem { RunId = run.Id, MediaId = m.Id, AccountId = luca.Account.Id, SourceSha256 = m.Sha256 })]);
|
||||
await server.Db.Exports.SetDestinationPausedAsync(ownId, server.Clock.Now, "La chiavetta non c'è.");
|
||||
|
||||
// The count of an automatic folder in pause is kept a minute (a disk left unplugged is not counted at each reading).
|
||||
server.Clock.Now += TimeSpan.FromMinutes(2);
|
||||
var overview = await server.GetJsonAsync("/api/export");
|
||||
var ownDto = overview.GetProperty("own").EnumerateArray().Single();
|
||||
Assert.AreEqual(2, ownDto.Int("waiting"), ownDto.ToString());
|
||||
Assert.AreEqual(JsonValueKind.Null, ownDto.GetProperty("automaticSince").ValueKind);
|
||||
Assert.AreEqual(3, overview.GetProperty("general").Int("waiting"), "luca's files now go to his own folder");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UnfinishedRunsCountsManualOnly_RunsListHasEveryUnfinished()
|
||||
{
|
||||
await using var server = await StartAsync();
|
||||
var (id, _) = await GeneralAsync(server);
|
||||
var exports = server.Db.Exports;
|
||||
var manual = await exports.CreateRunAsync(new ExportRun { DestinationId = id, State = ExportRunState.Interrupted, StartedAt = server.Clock.Now });
|
||||
var automatic = await exports.CreateRunAsync(new ExportRun { DestinationId = id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Paused, StartedAt = server.Clock.Now });
|
||||
for (var i = 0; i < 25; i++)
|
||||
{
|
||||
server.Clock.Now += TimeSpan.FromMinutes(1);
|
||||
await exports.CreateRunAsync(new ExportRun { DestinationId = id, State = ExportRunState.Completed, StartedAt = server.Clock.Now, CompletedAt = server.Clock.Now });
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, (await server.GetJsonAsync("/api/export")).Int("unfinishedRuns"), "only Alberto's job: the automatic one resumes by itself");
|
||||
var recent = (await server.GetJsonAsync("/api/export/runs?limit=20")).EnumerateArray().Select(r => r.Long("id")).ToList();
|
||||
Assert.HasCount(20, recent);
|
||||
Assert.IsFalse(recent.Contains(manual.Id) || recent.Contains(automatic.Id), "older than the twenty newest");
|
||||
var unfinished = (await server.GetJsonAsync("/api/export/runs?unfinished=true")).EnumerateArray().ToList();
|
||||
CollectionAssert.AreEqual(new[] { manual.Id, automatic.Id }, unfinished.Select(r => r.Long("id")).ToArray(), "every unfinished job, oldest first");
|
||||
CollectionAssert.AreEqual(new[] { "manual", "automatic" }, unfinished.Select(r => r.Str("origin")).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InterruptOfAnAutomaticJobHoldsTheAutomaticCopiesAndSaysWhen()
|
||||
{
|
||||
var session = new FakeSessionState();
|
||||
var clock = new GatedClock(new ManualClock(Make.T0));
|
||||
await using var server = await StartAsync(session: session, clock: clock);
|
||||
await AddPhotosAsync(server, "marta.demo", 2);
|
||||
var usb = server.Temp.Combine("usb");
|
||||
Directory.CreateDirectory(usb);
|
||||
var (created, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, automatic: true, onlyNew: false));
|
||||
Assert.AreEqual(HttpStatusCode.OK, created, saved.ToString());
|
||||
var id = saved.GetProperty("destination").Long("id");
|
||||
|
||||
// An automatic job that waits for the end of an engine session (the session starts right after it is planned).
|
||||
var service = await server.App.Services.GetRequiredService<ExportHub>().GetAsync();
|
||||
service.AutomaticRunRecorded = _ =>
|
||||
{
|
||||
session.InSession = true;
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
var start = await service.TryStartAutomaticAsync(new ExportSelection.Automatic([new ExportSelection.AutomaticScope(id, null)], [], Round: true));
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
|
||||
var progress = (await WaitForAsync(async () =>
|
||||
{
|
||||
var p = await server.GetJsonAsync("/api/export/progress");
|
||||
return p.Bool("running") && p.Str("phase") == "waitingForSession" ? (JsonElement?)p : null;
|
||||
})).GetValueOrDefault();
|
||||
Assert.AreEqual("automatic", progress.Str("origin"));
|
||||
Assert.AreEqual("copy", progress.Str("kind"));
|
||||
|
||||
// «Interrompi» (answer 53): the automatic copies stop until the next round, at least an hour, and the answer says when.
|
||||
var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/interrupt");
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, answer.ToString());
|
||||
var until = clock.Now + service.AutomaticHoldTime;
|
||||
Assert.AreEqual(until, service.AutomaticHeldUntil);
|
||||
Assert.AreEqual(ExportText.AutomaticInterrupted(until, clock.LocalZone), answer.Str("message"));
|
||||
StringAssert.Contains(answer.Str("message"), "riprende da sola alle");
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await server.Db.Exports.GetRunAsync(start.Runs[0].Id))!.State);
|
||||
|
||||
// «Riprendi ora»: no longer held.
|
||||
var (resumed, resumeAnswer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic/resume");
|
||||
Assert.AreEqual(HttpStatusCode.OK, resumed, resumeAnswer.ToString());
|
||||
Assert.AreEqual("Copie automatiche di nuovo attive.", resumeAnswer.Str("message"));
|
||||
Assert.IsNull(service.AutomaticHeldUntil);
|
||||
|
||||
// A manual job keeps the message of before.
|
||||
session.InSession = false;
|
||||
Assert.AreEqual("Interrotta: quello che è stato copiato resta, e riprendi da qui quando vuoi.", (await server.SendJsonAsync(HttpMethod.Post, "/api/export/interrupt")).Body.Str("message"));
|
||||
Assert.IsNull(service.AutomaticHeldUntil);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OverviewCarriesTheAutomaticStatus()
|
||||
{
|
||||
// Without the worker (the demonstration, a start with problems): no status.
|
||||
await using (var plain = await StartAsync())
|
||||
{
|
||||
Assert.AreEqual(JsonValueKind.Null, (await plain.GetJsonAsync("/api/export")).GetProperty("automatic").ValueKind);
|
||||
}
|
||||
|
||||
var clock = new GatedClock(new ManualClock(Make.T0));
|
||||
var signal = new AutoExportSignal();
|
||||
await using var server = await WebTestServer.StartAsync(
|
||||
new Febe.Web.FebeWebOptions { Edition = Febe.Web.FebeEdition.Desktop, Access = Febe.Web.AccessMode.None },
|
||||
s =>
|
||||
{
|
||||
s.AddSingleton<IExportDisk>(new FakeExportDisk(Free));
|
||||
s.AddSingleton<IClock>(clock);
|
||||
s.AddSingleton(sp => new AutoExportWorker(new AutoExportEnvironment
|
||||
{
|
||||
Storage = sp.GetRequiredService<IFebeStorage>(),
|
||||
Clock = clock,
|
||||
Service = ct => sp.GetRequiredService<ExportHub>().GetAsync(ct),
|
||||
Signal = signal,
|
||||
Gate = sp.GetRequiredService<LongWorkGate>(),
|
||||
}));
|
||||
});
|
||||
var worker = server.App.Services.GetRequiredService<AutoExportWorker>();
|
||||
Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("automatic").ValueKind, "not started yet");
|
||||
|
||||
using var stop = new CancellationTokenSource();
|
||||
var loop = Task.Run(() => worker.RunAsync(stop.Token));
|
||||
try
|
||||
{
|
||||
// The start-up round has run: when the next one is due.
|
||||
var status = (await WaitForAsync(async () =>
|
||||
{
|
||||
var a = (await server.GetJsonAsync("/api/export")).GetProperty("automatic");
|
||||
return a.ValueKind == JsonValueKind.Object && a.GetProperty("lastRound").ValueKind == JsonValueKind.Object ? (JsonElement?)a : null;
|
||||
})).GetValueOrDefault();
|
||||
Assert.IsFalse(status.Bool("anyAutomatic"));
|
||||
Assert.AreEqual((Make.T0 + TimeSpan.FromHours(1)).ToUnixTimeMilliseconds(), status.GetProperty("nextRound").Long("ms"));
|
||||
Assert.AreEqual(Make.T0.ToUnixTimeMilliseconds(), status.GetProperty("lastRound").Long("ms"));
|
||||
Assert.AreEqual(JsonValueKind.Null, status.GetProperty("heldUntil").ValueKind);
|
||||
|
||||
var usb = server.Temp.Combine("usb");
|
||||
Directory.CreateDirectory(usb);
|
||||
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, automatic: true))).Status);
|
||||
Assert.IsTrue((await server.GetJsonAsync("/api/export")).GetProperty("automatic").Bool("anyAutomatic"));
|
||||
|
||||
// Held by «Interrompi» until a time, then «Riprendi ora».
|
||||
var service = await server.App.Services.GetRequiredService<ExportHub>().GetAsync();
|
||||
var until = service.HoldAutomatic(clock.Now + TimeSpan.FromHours(1));
|
||||
Assert.AreEqual(until.ToUnixTimeMilliseconds(), (await server.GetJsonAsync("/api/export")).GetProperty("automatic").GetProperty("heldUntil").Long("ms"));
|
||||
var count = signal.Count;
|
||||
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic/resume")).Status);
|
||||
Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("automatic").GetProperty("heldUntil").ValueKind);
|
||||
Assert.IsGreaterThan(count, signal.Count, "a pass is asked at once");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await stop.CancelAsync();
|
||||
await worker.StopAsync();
|
||||
await loop;
|
||||
}
|
||||
|
||||
Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("automatic").ValueKind, "stopped");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- support
|
||||
|
||||
private static async Task<JsonElement> PreviewAsync(WebTestServer server, object request)
|
||||
{
|
||||
var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic-preview", request);
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, answer.ToString());
|
||||
return answer;
|
||||
}
|
||||
|
||||
/// <summary>The files «Copia in…» would write for an account now.</summary>
|
||||
private static async Task<int> PlanFilesAsync(WebTestServer server, long accountId)
|
||||
{
|
||||
var (status, plan) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, plan.ToString());
|
||||
return plan.Int("files");
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ namespace Febe.Tests.Web;
|
||||
/// real (saved through <see cref="LibraryIngest"/>), destinations are folders of the temporary folder of the test.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ExportApiTests
|
||||
public sealed partial class ExportApiTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
@@ -455,7 +455,7 @@ public sealed class ExportApiTests
|
||||
}
|
||||
});
|
||||
|
||||
private static object Destination(string path, string scope = "general", long? accountId = null, string? label = null, string[]? types = null) => new
|
||||
private static object Destination(string path, string scope = "general", long? accountId = null, string? label = null, string[]? types = null, bool automatic = false, bool onlyNew = true) => new
|
||||
{
|
||||
scope,
|
||||
accountId,
|
||||
@@ -465,6 +465,8 @@ public sealed class ExportApiTests
|
||||
namingScheme = (string?)null,
|
||||
highlightNamingScheme = (string?)null,
|
||||
profileNamingScheme = (string?)null,
|
||||
automatic,
|
||||
onlyNew,
|
||||
};
|
||||
|
||||
/// <summary>The general folder «usb» in the temporary folder of the host.</summary>
|
||||
|
||||
Reference in new issue
Block a user