E1: schema dell'esportazione, migrazione 0003, archivi ed ExportSettings (#58)
La tappa E1 della 0.3.0 prepara il database per le copie esterne senza cambiare comportamento: nulla in interfaccia, motore o API usa ancora ciò che segue. - Migrazione 0003: export_destination, export_account, export_copy, export_run, export_item, video_analysis e media_conversion (risposta di Alberto del 26 novembre: i convertiti per la libreria in una tabella a parte, media non cambia), con i vincoli e gli indici di §8.3. - Archivi IExportStore, IVideoAnalysisStore e IMediaConversionStore in IFebeStorage; ExportSettings sulle cinque chiavi esportazione.*. - AccountStore.DeleteAsync spegne «Automatica» delle cartelle dell'account e vi scrive il suo nome prima di cancellarlo (finché non ci sono destinazioni non fa nulla). - Prove: aggiornamento dei database delle versioni 1 e 2 con foreign_key_check pulito, database più nuovo rifiutato e lasciato intatto, vincoli, archivi, piani delle ricerche, impostazioni e documenti. - SPECIFICA §4.10, §8.3 e §15, decisioni.md e stato.md aggiornati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dc92cabe5c
commit
ea4666d49b
23 files changed
+3756
-7
No files matched your search
@@ -0,0 +1,603 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Data;
|
||||
using Febe.Data.Stores;
|
||||
using Febe.Tests.Support;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using static Febe.Tests.Data.ExportWorld;
|
||||
|
||||
namespace Febe.Tests.Data;
|
||||
|
||||
/// <summary>The constraints of migration 0003 (spec §4.10, §8.3), written with raw SQL so the CHECKs answer alone.</summary>
|
||||
[TestClass]
|
||||
public sealed class ExportConstraintTests
|
||||
{
|
||||
private static readonly string[] ExportTables =
|
||||
["export_destination", "export_account", "export_copy", "export_run", "export_item", "video_analysis", "media_conversion"];
|
||||
|
||||
private static readonly string Sha63 = Make.Sha(1)[1..];
|
||||
private static readonly string Sha65 = Make.Sha(1) + "0";
|
||||
|
||||
[TestMethod]
|
||||
public async Task UnknownValuesAreRejectedInEveryTable()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var run = await InsertAsync(db, "export_run", w.RunRow());
|
||||
await InsertAsync(db, "export_item", w.ItemRow(run));
|
||||
await InsertAsync(db, "export_account", new Dictionary<string, object?> { ["account_id"] = w.Luca, ["enabled"] = 1L });
|
||||
await InsertAsync(db, "video_analysis", AnalysisRow());
|
||||
await InsertAsync(db, "media_conversion", w.ConversionRow());
|
||||
await InsertAsync(db, "export_copy", w.CopyRow());
|
||||
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Tutti")), "ambito sconosciuto");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("photo_format", "Mp4")), "formato video per le foto");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("video_format", "Jpg")), "formato foto per i video");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("content_types", -1L)), "tipi negativi");
|
||||
await RejectedAsync(db, "export_account", new Dictionary<string, object?> { ["account_id"] = w.Marta, ["enabled"] = 2L }, "interruttore non booleano");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Gone"), ("relative_path", "x/1.jpg")), "stato della copia");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Intero"), ("relative_path", "x/2.jpg")), "variante");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("format", "Gif"), ("variant", "Converted"), ("copy_sha256", Make.Sha(2)), ("relative_path", "x/3.jpg")), "formato");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("origin", "Copied"), ("account_id", w.Luca), ("media_id", w.LucaMedia), ("relative_path", "x/4.jpg")), "origine");
|
||||
await RejectedAsync(db, "export_run", w.RunRow(("kind", "Export")), "tipo di lavoro");
|
||||
await RejectedAsync(db, "export_run", w.RunRow(("origin", "Auto")), "origine del lavoro");
|
||||
await RejectedAsync(db, "export_run", w.RunRow(("state", "Done")), "stato del lavoro");
|
||||
await RejectedAsync(db, "export_item", w.ItemRow(run, ("state", "Done"), ("media_id", w.LucaMedia)), "stato del file");
|
||||
await RejectedAsync(db, "export_item", w.ItemRow(run, ("variant", "Intero"), ("media_id", w.LucaMedia)), "variante del file");
|
||||
await RejectedAsync(db, "export_item", w.ItemRow(run, ("format", "Gif"), ("variant", "Converted"), ("media_id", w.LucaMedia)), "formato del file");
|
||||
await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "Fermo"), ("sha256", Make.Sha(6))), "esito");
|
||||
await RejectedAsync(db, "video_analysis", AnalysisRow(("algorithm", 0L), ("sha256", Make.Sha(6))), "algoritmo 0");
|
||||
await RejectedAsync(db, "media_conversion", w.ConversionRow(("format", "Original"), ("media_id", w.LucaMedia)), "un convertito ha un altro formato");
|
||||
await RejectedAsync(
|
||||
db,
|
||||
"media_conversion",
|
||||
w.ConversionRow(("state", "Done"), ("media_id", w.LucaMedia), ("relative_path", "taggati/a.jpg.jpg"), ("bytes", 1L), ("sha256", Make.Sha(2)), ("converted_at", 0L)),
|
||||
"stato della conversione");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Sha256MustHave64Characters()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var run = await InsertAsync(db, "export_run", w.RunRow());
|
||||
|
||||
foreach (var bad in new[] { Sha63, Sha65 })
|
||||
{
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("source_sha256", bad), ("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)), "source_sha256");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Jpg"), ("copy_sha256", bad)), "copy_sha256");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("superseded_by_sha256", bad)), "superseded_by_sha256");
|
||||
await RejectedAsync(db, "export_item", w.ItemRow(run, ("source_sha256", bad)), "export_item.source_sha256");
|
||||
await RejectedAsync(db, "video_analysis", AnalysisRow(("sha256", bad)), "video_analysis.sha256");
|
||||
await RejectedAsync(db, "media_conversion", w.ConversionRow(("source_sha256", bad)), "media_conversion.source_sha256");
|
||||
await RejectedAsync(db, "media_conversion", w.ConversionRow(("sha256", bad)), "media_conversion.sha256");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task VariantAndFormatGoTogether()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var run = await InsertAsync(db, "export_run", w.RunRow());
|
||||
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("format", "Jpg")), "intero in JPG");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("copy_sha256", Make.Sha(2))), "convertito in Originale");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Mp4"), ("frame_at_ms", 0L), ("copy_sha256", Make.Sha(2))), "fotogramma in MP4");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Jpg"), ("copy_sha256", Make.Sha(2))), "fotogramma senza istante");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("frame_at_ms", 0L)), "intero con un istante");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("copy_sha256", Make.Sha(2))), "intero con uno SHA-256 diverso dall'originale");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Jpg")), "convertito uguale all'originale: è un intero");
|
||||
await RejectedAsync(db, "export_item", w.ItemRow(run, ("format", "Jpg")), "file intero in JPG");
|
||||
await RejectedAsync(db, "export_item", w.ItemRow(run, ("variant", "Frame"), ("format", "Png")), "file fotogramma senza istante");
|
||||
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Jpg"), ("copy_sha256", Make.Sha(2)), ("relative_path", "marta.demo/a.jpg")));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Png"), ("frame_at_ms", 1000L), ("copy_sha256", Make.Sha(3)), ("relative_path", "marta.demo/a_t0m01s000.png")));
|
||||
await InsertAsync(db, "export_item", w.ItemRow(run, ("variant", "Frame"), ("format", "WebpLossless"), ("frame_at_ms", 0L)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EveryStateButFailedHadAFile()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("relative_path", null)), "copiato senza percorso");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("bytes", null)), "copiato senza byte");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("copy_sha256", null)), "copiato senza SHA-256 della copia");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("relative_path", null)), "tolto senza percorso");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("relative_path", "")), "percorso vuoto");
|
||||
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SupersededNeedsTheFileThatTookItsPlace()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Superseded")), "superato senza il file nuovo");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("superseded_by_sha256", Make.Sha(9))), "copiato con il file nuovo");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("superseded_by_sha256", Make.Sha(9))), "non riuscito con il file nuovo");
|
||||
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Superseded"), ("superseded_by_sha256", Make.Sha(1)), ("relative_path", "marta.demo/c.jpg")), "superata dal suo stesso originale");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("superseded_by_sha256", Make.Sha(1))), "tolta e segnata con il suo stesso originale");
|
||||
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Removed"), ("superseded_by_sha256", Make.Sha(9))));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("state", "Superseded"), ("superseded_by_sha256", Make.Sha(9)), ("relative_path", "marta.demo/b.jpg")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OneCurrentConversionPerFileAndFormat()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var first = await InsertAsync(db, "media_conversion", w.ConversionRow());
|
||||
|
||||
await RejectedAsync(db, "media_conversion", w.ConversionRow(), "due conversioni in JPG in coda per lo stesso file");
|
||||
await RejectedAsync(db, "media_conversion", w.ConversionRow(("state", "Failed")), "una non riuscita accanto a una in coda");
|
||||
await RejectedAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2)), "una fatta accanto a una in coda");
|
||||
await InsertAsync(db, "media_conversion", w.ConversionRow(("format", "Png")));
|
||||
await InsertAsync(db, "media_conversion", w.ConversionRow(("media_id", w.LucaMedia)));
|
||||
|
||||
await ExecuteAsync(db, "UPDATE media_conversion SET state = 'Removed', relative_path = 'post/a.jpg.jpg', bytes = 1, sha256 = @h, converted_at = 0 WHERE id = @id", ("@id", first), ("@h", Make.Sha(2)));
|
||||
var second = await InsertAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(3)));
|
||||
await ExecuteAsync(db, "UPDATE media_conversion SET state = 'Superseded' WHERE id = @id", ("@id", second));
|
||||
await InsertAsync(db, "media_conversion", w.ConversionRow());
|
||||
|
||||
await RejectedAsync(db, "media_conversion", Converted(w, "WebpLossless", Make.Sha(1)), "un convertito uguale al suo originale");
|
||||
await InsertAsync(db, "media_conversion", Converted(w, "WebpLossless", Make.Sha(4)));
|
||||
}
|
||||
|
||||
private static Dictionary<string, object?> Converted(ExportWorld w, string format, string sha256) =>
|
||||
w.ConversionRow(("format", format), ("state", "Converted"), ("relative_path", $"post/a.jpg.{format}"), ("bytes", 1L), ("sha256", sha256), ("converted_at", 0L));
|
||||
|
||||
[TestMethod]
|
||||
public async Task DestinationsKeepTheirRules()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("removed_at", null)), "una seconda cartella generale in uso");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("account_id", w.Marta)), "la cartella generale non ha account");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("removed_account_username", "marta.demo")), "la cartella generale non ha nome d'account");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("root_path", null)), "senza cartella");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("root_path", "")), "cartella vuota");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("content_types", null)), "senza tipi");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Account"), ("account_id", w.Marta), ("removed_at", null)), "una seconda cartella in uso per un account");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("scope", "Account")), "una cartella d'account senza account né nome");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("removed_at", null), ("scope", "Account"), ("account_id", w.Luca), ("automatic_since", 5L)), "«Solo i nuovi» senza «Automatica»");
|
||||
await RejectedAsync(db, "export_destination", DestinationRow(("automatic", 1L)), "una destinazione ritirata non è automatica");
|
||||
|
||||
await ExecuteAsync(db, "UPDATE export_destination SET removed_at = 1 WHERE id = @id", ("@id", w.General));
|
||||
await InsertAsync(db, "export_destination", DestinationRow(("removed_at", null)));
|
||||
await ExecuteAsync(db, "UPDATE export_destination SET removed_at = 1 WHERE id = @id", ("@id", w.Own));
|
||||
await InsertAsync(db, "export_destination", DestinationRow(("scope", "Account"), ("account_id", w.Marta), ("removed_at", null), ("automatic", 1L), ("automatic_since", 5L)));
|
||||
|
||||
(string, object?)[] orphan = [("scope", "Account"), ("removed_account_username", "vecchio.demo"), ("removed_at", null)];
|
||||
await RejectedAsync(db, "export_destination", DestinationRow([.. orphan, ("automatic", 1L)]), "una cartella senza il suo account non è automatica");
|
||||
await InsertAsync(db, "export_destination", DestinationRow(orphan));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OneCurrentCopyPerIdentity()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var first = await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/1.jpg")));
|
||||
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/2.jpg")), "la stessa identità copiata due volte");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("state", "Failed"), ("relative_path", null), ("bytes", null), ("copy_sha256", null)), "non riuscita accanto a una copiata");
|
||||
|
||||
await ExecuteAsync(db, "UPDATE export_copy SET state = 'Removed' WHERE id = @id", ("@id", first));
|
||||
var second = await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/2.jpg")));
|
||||
await ExecuteAsync(db, "UPDATE export_copy SET state = 'Superseded', superseded_by_sha256 = @h WHERE id = @id", ("@id", second), ("@h", Make.Sha(9)));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/3.jpg")));
|
||||
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("media_id", w.LucaMedia), ("relative_path", "luca.demo/1.jpg")));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Converted"), ("format", "Png"), ("copy_sha256", Make.Sha(2)), ("relative_path", "marta.demo/1.png")));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Jpg"), ("frame_at_ms", 0L), ("copy_sha256", Make.Sha(3)), ("relative_path", "marta.demo/f0.jpg")));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("variant", "Frame"), ("format", "Jpg"), ("frame_at_ms", 1000L), ("copy_sha256", Make.Sha(4)), ("relative_path", "marta.demo/f1.jpg")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task APathIsNeverRecordedTwice()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var first = await InsertAsync(db, "export_copy", w.CopyRow(("relative_path", "marta.demo/x.jpg")));
|
||||
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("relative_path", "marta.demo/x.jpg")), "due copie sullo stesso file");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("relative_path", "Marta.Demo/X.JPG")), "lo stesso file su Windows, maiuscole diverse");
|
||||
await RejectedAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("state", "Superseded"), ("superseded_by_sha256", Make.Sha(9)), ("relative_path", "marta.demo/x.jpg")), "superata sullo stesso file");
|
||||
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("destination_id", w.Own), ("relative_path", "marta.demo/x.jpg")));
|
||||
await ExecuteAsync(db, "UPDATE export_copy SET state = 'Removed' WHERE id = @id", ("@id", first));
|
||||
await InsertAsync(db, "export_copy", w.CopyRow(("account_id", w.Luca), ("relative_path", "marta.demo/x.jpg")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecordsCannotBeDeletedFromUnderTheirCopies()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
await InsertAsync(db, "export_copy", w.CopyRow());
|
||||
await InsertAsync(db, "export_run", w.RunRow(("destination_id", w.Own)));
|
||||
var conversion = await InsertAsync(db, "media_conversion", w.ConversionRow());
|
||||
|
||||
var withCopy = await Assert.ThrowsExactlyAsync<SqliteException>(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.General)));
|
||||
Assert.AreEqual(19, withCopy.SqliteErrorCode, "una destinazione con copie si ritira, non si cancella");
|
||||
var withRun = await Assert.ThrowsExactlyAsync<SqliteException>(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.Own)));
|
||||
Assert.AreEqual(19, withRun.SqliteErrorCode, "una destinazione con lavori si ritira, non si cancella");
|
||||
|
||||
var entry = await Assert.ThrowsExactlyAsync<SqliteException>(() => db.Entries.RemoveAsync(w.MartaEntry));
|
||||
Assert.AreEqual(19, entry.SqliteErrorCode, "un file con un convertito registrato non si cancella");
|
||||
Assert.IsNotNull(await db.Entries.GetAsync(w.MartaEntry));
|
||||
Assert.IsNotNull(await db.Media.GetAsync(w.MartaMedia));
|
||||
Assert.IsNotNull(await db.Conversions.GetAsync(conversion));
|
||||
|
||||
var account = await Assert.ThrowsExactlyAsync<SqliteException>(() => db.Accounts.DeleteAsync(w.Marta));
|
||||
Assert.AreEqual(19, account.SqliteErrorCode, "anche attraverso la rimozione dell'account");
|
||||
Assert.IsNotNull(await db.Accounts.GetAsync(w.Marta));
|
||||
Assert.IsNotNull(await db.Conversions.GetAsync(conversion));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EntryRemovalKeepsCopiesBySha256()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0 });
|
||||
await db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1) }]);
|
||||
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Moving, Make.T0));
|
||||
|
||||
await db.Entries.RemoveAsync(w.MartaEntry);
|
||||
|
||||
var kept = await db.Exports.GetCopyAsync(copy.Id);
|
||||
Assert.IsNotNull(kept);
|
||||
Assert.IsNull(kept.MediaId);
|
||||
Assert.AreEqual(Make.Sha(1), kept.SourceSha256);
|
||||
Assert.AreEqual(w.Marta, kept.AccountId);
|
||||
Assert.Contains(kept, await db.Exports.ListCopiesBySha256Async(Make.Sha(1)));
|
||||
var item = (await db.Exports.ListItemsAsync(new() { RunId = run.Id })).Single();
|
||||
Assert.IsNull(item.MediaId);
|
||||
Assert.AreEqual(Make.Sha(1), item.SourceSha256);
|
||||
Assert.IsNotNull(await db.VideoAnalyses.GetAsync(Make.Sha(1)));
|
||||
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AccountRemovalKeepsItsDestination()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1));
|
||||
var current = await db.Exports.AddDestinationAsync(Destination(ExportScope.Account, w.Marta, @"H:\Marta") with { Automatic = true, AutomaticSince = Make.T0.AddDays(2) });
|
||||
await db.Exports.SetAccountExportEnabledAsync(w.Marta, true);
|
||||
var martaCopy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
var lucaCopy = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia));
|
||||
|
||||
await db.Accounts.DeleteAsync(w.Marta);
|
||||
await db.Accounts.DeleteAsync(w.Luca);
|
||||
|
||||
foreach (var id in new[] { w.Own, current.Id })
|
||||
{
|
||||
var destination = (await db.Exports.GetDestinationAsync(id))!;
|
||||
Assert.IsNull(destination.AccountId);
|
||||
Assert.AreEqual("marta.demo", destination.RemovedAccountUsername);
|
||||
Assert.IsTrue(destination.IsOrphan);
|
||||
}
|
||||
|
||||
var disabled = (await db.Exports.GetDestinationAsync(current.Id))!;
|
||||
Assert.IsNull(disabled.RemovedAt, "la cartella in uso resta in uso, senza account");
|
||||
Assert.IsFalse(disabled.Automatic, "rimuovere l'account la disattiva");
|
||||
Assert.IsNull(disabled.AutomaticSince, "e dimentica «Solo i nuovi»");
|
||||
Assert.IsFalse((await db.Exports.ListDestinationsAsync()).Any(d => d.Automatic));
|
||||
Assert.IsNull(await db.Exports.GetAccountExportEnabledAsync(w.Marta));
|
||||
Assert.AreEqual(0L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_account"));
|
||||
var general = (await db.Exports.GetGeneralDestinationAsync())!;
|
||||
Assert.AreEqual(w.General, general.Id);
|
||||
Assert.IsNull(general.AccountId);
|
||||
Assert.IsNull(general.RemovedAccountUsername);
|
||||
|
||||
// Two orphan copies with the same identity but for the account (now NULL): both kept.
|
||||
var copies = await db.Exports.ListCopiesBySha256Async(Make.Sha(1));
|
||||
CollectionAssert.AreEquivalent(new[] { martaCopy.Id, lucaCopy.Id }, copies.Select(c => c.Id).ToArray());
|
||||
Assert.IsTrue(copies.All(c => c.AccountId is null && c.MediaId is null && c.Identity is null));
|
||||
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RawAccountDeleteWithoutUserNameFails()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<SqliteException>(() => ExecuteAsync(db, "DELETE FROM account WHERE id = @id", ("@id", w.Marta)));
|
||||
|
||||
Assert.AreEqual(19, error.SqliteErrorCode, "il CHECK vale anche sull'azione SET NULL");
|
||||
Assert.IsNotNull(await db.Accounts.GetAsync(w.Marta));
|
||||
Assert.AreEqual(w.Marta, (await db.Exports.GetDestinationAsync(w.Own))!.AccountId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RemovedAccountComesBack()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var ownCopy = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own));
|
||||
var generalCopy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
await db.Exports.UpdateDestinationAsync((await db.Exports.GetDestinationAsync(w.Own))! with { Automatic = true, AutomaticSince = Make.T0.AddDays(1) });
|
||||
await db.Accounts.DeleteAsync(w.Marta);
|
||||
|
||||
var orphan = (await db.Exports.GetDestinationAsync(w.Own))!;
|
||||
Assert.IsFalse(orphan.Automatic, "rimuovere l'account la disattiva");
|
||||
Assert.IsNull(orphan.AutomaticSince);
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(orphan with { Automatic = true }), "senza account non si accende");
|
||||
var again = await db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
|
||||
await db.Exports.AttachDestinationAsync(w.Own, again.Id);
|
||||
|
||||
var own = (await db.Exports.GetDestinationAsync(w.Own))!;
|
||||
Assert.AreEqual(again.Id, own.AccountId);
|
||||
Assert.IsNull(own.RemovedAccountUsername);
|
||||
Assert.IsFalse(own.Automatic, "ridata all'account, «Automatica» resta spenta: riaccenderla chiede di nuovo");
|
||||
Assert.IsNull(own.AutomaticSince, "il vecchio «Solo i nuovi» non torna");
|
||||
await db.Exports.UpdateDestinationAsync(own with { Automatic = true, AutomaticSince = Make.T0.AddDays(3) });
|
||||
Assert.AreEqual(Make.T0.AddDays(3), (await db.Exports.GetDestinationAsync(w.Own))!.AutomaticSince);
|
||||
Assert.AreEqual(own.Id, (await db.Exports.GetAccountDestinationAsync(again.Id))!.Id);
|
||||
Assert.AreEqual(again.Id, (await db.Exports.GetCopyAsync(ownCopy.Id))!.AccountId);
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(generalCopy.Id))!.AccountId, "le copie di altre destinazioni restano orfane finché non si adottano");
|
||||
|
||||
var relinked = await db.Exports.RelinkOrphanCopyAsync(generalCopy.Id, again.Id, null, Make.T0.AddDays(2));
|
||||
Assert.AreEqual(again.Id, relinked.AccountId);
|
||||
Assert.AreEqual(Make.T0.AddDays(2), relinked.StateChangedAt);
|
||||
Assert.AreEqual(generalCopy.Id, (await db.Exports.FindCopyByPathAsync(w.General, "marta.demo/a.jpg"))!.Id);
|
||||
Assert.AreEqual(1L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_copy WHERE destination_id = @d AND relative_path = 'marta.demo/a.jpg'", ("@d", w.General)));
|
||||
Assert.AreEqual(0L, await ForeignKeyProblemsAsync(db));
|
||||
|
||||
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => db.Exports.AttachDestinationAsync(w.Own, again.Id));
|
||||
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => db.Exports.AttachDestinationAsync(w.General, again.Id));
|
||||
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => db.Exports.RelinkOrphanCopyAsync(generalCopy.Id, again.Id, null, Make.T0));
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.RelinkOrphanCopyAsync(9999, again.Id, null, Make.T0));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DestinationRetirementKeepsRecords()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
var root = temp.Combine("copie");
|
||||
Directory.CreateDirectory(Path.Combine(root, "marta.demo"));
|
||||
var file = Path.Combine(root, "marta.demo", "a.jpg");
|
||||
await File.WriteAllBytesAsync(file, [1, 2, 3]);
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db, root);
|
||||
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0, State = ExportRunState.Completed });
|
||||
await db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1), State = ExportItemState.Copied, CopyId = copy.Id }]);
|
||||
|
||||
await db.Exports.RetireDestinationAsync(w.General, Make.T0.AddDays(1));
|
||||
|
||||
Assert.IsNull(await db.Exports.GetGeneralDestinationAsync());
|
||||
Assert.AreEqual(Make.T0.AddDays(1), (await db.Exports.GetDestinationAsync(w.General))!.RemovedAt);
|
||||
Assert.IsNotNull(await db.Exports.GetCopyAsync(copy.Id));
|
||||
Assert.IsNotNull(await db.Exports.GetRunAsync(run.Id));
|
||||
Assert.HasCount(1, await db.Exports.ListItemsAsync(new() { RunId = run.Id }));
|
||||
Assert.IsTrue(File.Exists(file), "togliere una destinazione non tocca i file già copiati");
|
||||
var next = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, temp.Combine("altre")));
|
||||
Assert.AreEqual(next.Id, (await db.Exports.GetGeneralDestinationAsync())!.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every foreign key of the new tables has an index usable for <c>child = ?</c>: the plan of that lookup is a SEARCH,
|
||||
/// never a SCAN (an index merely starting with the column is not enough when it is partial on another condition).
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task ExportForeignKeysHaveAnIndex()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var checkedKeys = 0;
|
||||
foreach (var table in ExportTables)
|
||||
{
|
||||
var columns = await db.ReadAsync(
|
||||
c =>
|
||||
{
|
||||
using var r = c.Command($"SELECT \"from\" FROM pragma_foreign_key_list('{table}')").ExecuteReader();
|
||||
var list = new List<string>();
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add(r.GetString(0));
|
||||
}
|
||||
|
||||
return list;
|
||||
},
|
||||
default);
|
||||
foreach (var column in columns)
|
||||
{
|
||||
var plan = await PlanAsync(db, $"SELECT 1 FROM {table} WHERE {column} = 1");
|
||||
Assert.Contains("SEARCH", plan, $"{table}.{column}: {plan}");
|
||||
Assert.DoesNotContain("SCAN", plan, $"{table}.{column}: {plan}");
|
||||
checkedKeys++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual(11, checkedKeys, "le chiavi esterne delle tabelle nuove");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The lookups of the stores read their index, with and without ANALYZE statistics: a SEARCH, no SCAN and no
|
||||
/// temporary B-tree (but the ORDER BY of the handful of rows of a SHA-256). Index names only where the choice is the point.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task ExportLookupsUseTheirIndex()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
await FillAsync(db, w);
|
||||
|
||||
// Without statistics the planner's choice is the point for the «Copie» set shape and the latest row of an identity.
|
||||
var setShape = await PlanAsync(
|
||||
db,
|
||||
"""
|
||||
SELECT m.entry_id FROM export_copy c JOIN media m ON m.sha256 = c.source_sha256
|
||||
JOIN entry x ON x.id = m.entry_id AND x.account_id = c.account_id
|
||||
WHERE c.destination_id = @d AND c.state = 'Copied'
|
||||
""",
|
||||
("@d", w.General));
|
||||
Assert.Contains("USING COVERING INDEX ix_export_copy_destination (destination_id=? AND state=?)", setShape, setShape);
|
||||
var latest = await PlanAsync(db, ExportStore.LatestCopySql, Identity(w));
|
||||
Assert.Contains("ix_export_copy_sha256", latest, latest);
|
||||
Assert.DoesNotContain("TEMP B-TREE", latest, latest);
|
||||
|
||||
await CheckLookupsAsync(db, w, "senza ANALYZE");
|
||||
await db.WriteAsync(x => x.Command("ANALYZE").ExecuteNonQuery(), default);
|
||||
await CheckLookupsAsync(db, w, "con ANALYZE");
|
||||
}
|
||||
|
||||
private static async Task CheckLookupsAsync(FebeDatabase db, ExportWorld w, string when)
|
||||
{
|
||||
var run = await ScalarAsync(db, "SELECT MIN(id) FROM export_run");
|
||||
var lookups = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[]
|
||||
{
|
||||
("FindCurrentCopyAsync", ExportStore.CurrentCopySql, Identity(w), false),
|
||||
("FindLatestCopyAsync", ExportStore.LatestCopySql, Identity(w), false),
|
||||
("FindCopyByPathAsync", ExportStore.CopyByPathSql, [("@d", w.General), ("@p", "marta.demo/17.jpg")], false),
|
||||
("ListCopiesBySha256Async", ExportStore.CopiesBySha256Sql, [("@h", Make.Sha(17))], true),
|
||||
("ListCopiesAsync", ExportStore.CopiesOfDestinationSql(false), [("@d", w.General), ("@after", 0L), ("@limit", 500L)], false),
|
||||
("ListCopiesAsync (stato)", ExportStore.CopiesOfDestinationSql(true), [("@d", w.General), ("@s", "Copied"), ("@after", 0L), ("@limit", 500L)], false),
|
||||
("CountCopiesAsync", ExportStore.CountCopiesSql, [("@d", w.General)], false),
|
||||
("ListUnfinishedRunsAsync", ExportStore.UnfinishedRunsSql, [], false),
|
||||
("ListItemsAsync", ExportStore.ItemsOfRunSql(false), [("@r", run), ("@after", 0L), ("@limit", 500L)], false),
|
||||
("ListItemsAsync (stato)", ExportStore.ItemsOfRunSql(true), [("@r", run), ("@s", "Pending"), ("@after", 0L), ("@limit", 500L)], false),
|
||||
("ListPendingAsync", MediaConversionStore.PendingSql, [("@after", 0L), ("@limit", 500L)], false),
|
||||
};
|
||||
var problems = new List<string>();
|
||||
foreach (var (name, sql, parameters, sortAllowed) in lookups)
|
||||
{
|
||||
var plan = await PlanAsync(db, sql, parameters);
|
||||
var withoutAllowedSort = sortAllowed ? plan.Replace("USE TEMP B-TREE FOR ORDER BY", string.Empty, StringComparison.Ordinal) : plan;
|
||||
if (!plan.Contains("SEARCH", StringComparison.Ordinal) || plan.Contains("SCAN", StringComparison.Ordinal)
|
||||
|| withoutAllowedSort.Contains("TEMP B-TREE", StringComparison.Ordinal))
|
||||
{
|
||||
problems.Add($"{name}: {plan}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, $"{when}: {string.Join(" || ", problems)}");
|
||||
}
|
||||
|
||||
private static (string, object?)[] Identity(ExportWorld w) =>
|
||||
[("@d", w.General), ("@h", Make.Sha(17)), ("@a", w.Marta), ("@v", "Whole"), ("@f", "Original"), ("@fr", -1L)];
|
||||
|
||||
/// <summary>About 1,000 copies over three destinations and two accounts, three jobs with their items, 300 finished jobs, and a queue of conversions.</summary>
|
||||
private static Task FillAsync(FebeDatabase db, ExportWorld w) =>
|
||||
db.WriteAsync(
|
||||
x =>
|
||||
{
|
||||
var destinations = new[] { w.General, w.Own, InsertDestination(x, w.Luca) };
|
||||
var copied = x.Command("""
|
||||
INSERT INTO export_copy (destination_id, account_id, source_sha256, variant, format, state, superseded_by_sha256,
|
||||
relative_path, bytes, copy_sha256, copied_at)
|
||||
VALUES (@d, @a, @h, 'Whole', 'Original', @s, @by, @p, 10, @h, 0)
|
||||
""");
|
||||
var failed = x.Command("""
|
||||
INSERT INTO export_copy (destination_id, account_id, source_sha256, variant, format, state, copied_at)
|
||||
VALUES (@d, @a, @h, 'Whole', 'Original', 'Failed', 0)
|
||||
""");
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
var destination = destinations[i % 3];
|
||||
var account = i % 2 == 0 ? w.Marta : w.Luca;
|
||||
var state = (i % 10) switch { 7 => "Removed", 8 => "Superseded", _ => "Copied" };
|
||||
if (i % 10 == 9)
|
||||
{
|
||||
failed.With("@d", destination).With("@a", account).With("@h", Make.Sha(i)).ExecuteNonQuery();
|
||||
continue;
|
||||
}
|
||||
|
||||
copied.With("@d", destination).With("@a", account).With("@h", Make.Sha(i)).With("@s", state)
|
||||
.With("@by", state == "Superseded" ? Make.Sha(5000 + i) : null)
|
||||
.With("@p", $"{(account == w.Marta ? "marta.demo" : "luca.demo")}/{i}.jpg").ExecuteNonQuery();
|
||||
}
|
||||
|
||||
var run = x.Command("INSERT INTO export_run (destination_id, kind, origin, state, started_at) VALUES (@d, 'Copy', 'Manual', @s, 0)");
|
||||
var item = x.Command("""
|
||||
INSERT INTO export_item (run_id, media_id, account_id, source_sha256, variant, format, frame_at_ms, state)
|
||||
VALUES (@r, NULL, @a, @h, 'Frame', 'Jpg', @f, @s)
|
||||
""");
|
||||
foreach (var state in new[] { "Completed", "Running", "Interrupted" })
|
||||
{
|
||||
run.With("@d", w.General).With("@s", state).ExecuteNonQuery();
|
||||
var runId = x.LastInsertRowId();
|
||||
for (var i = 0; i < 200; i++)
|
||||
{
|
||||
item.With("@r", runId).With("@a", w.Marta).With("@h", Make.Sha(i)).With("@f", (long)i * 1000).With("@s", i % 3 == 0 ? "Pending" : "Copied").ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
// The finished jobs of months of use: the unfinished ones are a handful among many.
|
||||
for (var i = 0; i < 300; i++)
|
||||
{
|
||||
run.With("@d", w.General).With("@s", i % 5 == 0 ? "Cancelled" : "Completed").ExecuteNonQuery();
|
||||
}
|
||||
|
||||
var entry = x.Command("INSERT INTO entry (account_id, kind, published_at, state, provenance, discovered_at) VALUES (@a, 'Post', 0, 'Downloaded', 'Imported', 0)");
|
||||
var media = x.Command("INSERT INTO media (entry_id, position, kind, state, sha256) VALUES (@e, 1, 'Photo', 'Imported', @h)");
|
||||
var conversion = x.Command("INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at) VALUES (@m, @f, @s, @h, 0)");
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
entry.With("@a", w.Marta).ExecuteNonQuery();
|
||||
media.With("@e", x.LastInsertRowId()).With("@h", Make.Sha(9000 + i)).ExecuteNonQuery();
|
||||
var mediaId = x.LastInsertRowId();
|
||||
foreach (var format in new[] { "Jpg", "Png" })
|
||||
{
|
||||
conversion.With("@m", mediaId).With("@f", format).With("@s", i % 4 == 0 ? "Pending" : "Failed").With("@h", Make.Sha(9000 + i)).ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
},
|
||||
default);
|
||||
|
||||
private static long InsertDestination(WriteContext x, long account)
|
||||
{
|
||||
x.Command("INSERT INTO export_destination (scope, account_id, root_path, content_types, created_at) VALUES ('Account', @a, 'K:/Luca', 63, 0)")
|
||||
.With("@a", account).ExecuteNonQuery();
|
||||
return x.LastInsertRowId();
|
||||
}
|
||||
|
||||
private static Task<string> PlanAsync(FebeDatabase db, string sql, params (string Name, object? Value)[] parameters) =>
|
||||
db.ReadAsync(
|
||||
c =>
|
||||
{
|
||||
var command = c.Command("EXPLAIN QUERY PLAN " + sql);
|
||||
foreach (var (name, value) in parameters)
|
||||
{
|
||||
command.With(name, value);
|
||||
}
|
||||
|
||||
using var r = command.ExecuteReader();
|
||||
var lines = new List<string>();
|
||||
while (r.Read())
|
||||
{
|
||||
lines.Add(r.GetString(3));
|
||||
}
|
||||
|
||||
return string.Join(" | ", lines);
|
||||
},
|
||||
default);
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Support;
|
||||
using static Febe.Tests.Data.ExportWorld;
|
||||
|
||||
namespace Febe.Tests.Data;
|
||||
|
||||
/// <summary>Round trips of the export, still-video and conversion stores on a real database (times at ms, UTC).</summary>
|
||||
[TestClass]
|
||||
public sealed class ExportStoreTests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task StorageExposesTheThreeStores()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
IFebeStorage storage = db;
|
||||
|
||||
Assert.IsNotNull(storage.Exports);
|
||||
Assert.IsNotNull(storage.VideoAnalyses);
|
||||
Assert.IsNotNull(storage.Conversions);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DestinationsRoundTrip()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var since = Make.T0.AddDays(3).AddMilliseconds(123);
|
||||
|
||||
var luca = await db.Exports.AddDestinationAsync(Destination(ExportScope.Account, w.Luca, @"\\nas\copie\luca") with
|
||||
{
|
||||
Label = "Disco di rete",
|
||||
ContentTypes = ContentTypes.PostPhotos | ContentTypes.Stories | ContentTypes.ProfilePicture,
|
||||
PhotoFormat = ExportFormat.WebpLossless,
|
||||
VideoFormat = ExportFormat.Mp4,
|
||||
NamingScheme = "{anno}/{codice}",
|
||||
HighlightNamingScheme = "{raccolta}/{numero}",
|
||||
ProfileNamingScheme = "profilo/{data}",
|
||||
Automatic = true,
|
||||
AutomaticSince = since,
|
||||
});
|
||||
|
||||
var read = (await db.Exports.GetDestinationAsync(luca.Id))!;
|
||||
Assert.AreEqual(luca, read);
|
||||
Assert.AreEqual(since, read.AutomaticSince);
|
||||
Assert.AreEqual(luca.Id, (await db.Exports.GetAccountDestinationAsync(w.Luca))!.Id);
|
||||
Assert.AreEqual(w.General, (await db.Exports.GetGeneralDestinationAsync())!.Id);
|
||||
var general = (await db.Exports.GetDestinationAsync(w.General))!;
|
||||
Assert.IsNull(general.PhotoFormat, "«Come le impostazioni generali»");
|
||||
Assert.IsNull(general.NamingScheme, "«Come la libreria»");
|
||||
Assert.IsFalse(general.Automatic, "«Automatica» spenta per impostazione predefinita");
|
||||
|
||||
var paused = read with { Automatic = false, AutomaticSince = null, PausedAt = Make.T0.AddDays(4), LastError = "Disco non raggiungibile", Label = null, VideoFormat = null };
|
||||
await db.Exports.UpdateDestinationAsync(paused);
|
||||
Assert.AreEqual(paused, await db.Exports.GetDestinationAsync(luca.Id));
|
||||
|
||||
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(5));
|
||||
CollectionAssert.AreEqual(new[] { w.General, luca.Id }, (await db.Exports.ListDestinationsAsync()).Select(d => d.Id).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { w.General, w.Own, luca.Id }, (await db.Exports.ListDestinationsAsync(includeRetired: true)).Select(d => d.Id).ToArray());
|
||||
Assert.IsNull(await db.Exports.GetAccountDestinationAsync(w.Marta));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DestinationsKeepTheirFolderScopeAndAccount()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var own = (await db.Exports.GetDestinationAsync(w.Own))!;
|
||||
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateDestinationAsync(own with { Id = 9999 }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { RootPath = @"Z:\Altra" }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { AccountId = w.Luca }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { Scope = ExportScope.General, AccountId = null }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { PhotoFormat = ExportFormat.Mp4 }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(own with { AutomaticSince = Make.T0 }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, @"Z:\a") with { RemovedAt = Make.T0 }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.Account, null, @"Z:\a")));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.General, w.Marta, @"Z:\a")));
|
||||
|
||||
await db.Exports.UpdateDestinationAsync(own with { Automatic = true });
|
||||
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1));
|
||||
var retired = (await db.Exports.GetDestinationAsync(w.Own))!;
|
||||
Assert.IsTrue(retired.IsRetired);
|
||||
Assert.IsFalse(retired.Automatic, "una destinazione ritirata non è più automatica");
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateDestinationAsync(retired));
|
||||
await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(9));
|
||||
Assert.AreEqual(Make.T0.AddDays(1), (await db.Exports.GetDestinationAsync(w.Own))!.RemovedAt, "ritirarla di nuovo non cambia nulla");
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.RetireDestinationAsync(9999, Make.T0));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheAccountSwitchRoundTrips()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
|
||||
Assert.IsNull(await db.Exports.GetAccountExportEnabledAsync(w.Marta), "nessuna scelta registrata");
|
||||
await db.Exports.SetAccountExportEnabledAsync(w.Marta, true);
|
||||
Assert.IsTrue(await db.Exports.GetAccountExportEnabledAsync(w.Marta));
|
||||
await db.Exports.SetAccountExportEnabledAsync(w.Marta, false);
|
||||
Assert.IsFalse(await db.Exports.GetAccountExportEnabledAsync(w.Marta));
|
||||
Assert.IsNull(await db.Exports.GetAccountExportEnabledAsync(w.Luca));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CopiesRoundTripAndKeepTheirIdentity()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
|
||||
var frame = await db.Exports.AddCopyAsync(w.WholeCopy(@"marta.demo\2026\a_t0m01s500.png") with
|
||||
{
|
||||
Variant = ExportVariant.Frame,
|
||||
Format = ExportFormat.Png,
|
||||
FrameAt = TimeSpan.FromMilliseconds(1500),
|
||||
CopySha256 = Make.Sha(2).ToUpperInvariant(),
|
||||
Origin = ExportCopyOrigin.Adopted,
|
||||
SourceSha256 = Make.Sha(1).ToUpperInvariant(),
|
||||
});
|
||||
var read = (await db.Exports.GetCopyAsync(frame.Id))!;
|
||||
Assert.AreEqual(frame, read);
|
||||
Assert.AreEqual("marta.demo/2026/a_t0m01s500.png", read.RelativePath, "separatore '/'");
|
||||
Assert.AreEqual(Make.Sha(1), read.SourceSha256, "SHA-256 in minuscolo");
|
||||
Assert.AreEqual(Make.Sha(2), read.CopySha256);
|
||||
Assert.AreEqual(new ExportCopyIdentity(w.General, w.Marta, Make.Sha(1), ExportVariant.Frame, ExportFormat.Png, TimeSpan.FromMilliseconds(1500)), read.Identity);
|
||||
|
||||
var failed = read with { State = ExportCopyState.Failed, RelativePath = null, Bytes = null, CopySha256 = null, LastError = "Spazio esaurito", StateChangedAt = Make.T0.AddHours(2) };
|
||||
await db.Exports.UpdateCopyAsync(failed);
|
||||
Assert.AreEqual(failed, await db.Exports.GetCopyAsync(frame.Id));
|
||||
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddCopyAsync(w.WholeCopy("x.jpg") with { AccountId = null }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddCopyAsync(w.WholeCopy("x.jpg") with { SourceSha256 = "abc" }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddCopyAsync(w.WholeCopy("x.jpg") with { Format = ExportFormat.Jpg }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { AccountId = w.Luca }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { FrameAt = TimeSpan.Zero }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { Format = ExportFormat.Jpg }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { SourceSha256 = Make.Sha(3) }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateCopyAsync(failed with { DestinationId = w.Own }));
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateCopyAsync(failed with { Id = 9999 }));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CurrentAndLatestCopyOfAnIdentity()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var identity = new ExportCopyIdentity(w.General, w.Marta, Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, null);
|
||||
|
||||
Assert.IsNull(await db.Exports.FindCurrentCopyAsync(identity));
|
||||
Assert.IsNull(await db.Exports.FindLatestCopyAsync(identity));
|
||||
|
||||
var first = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
Assert.AreEqual(first.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
|
||||
await db.Exports.UpdateCopyAsync(first with { State = ExportCopyState.Removed, StateChangedAt = Make.T0.AddDays(1) });
|
||||
Assert.IsNull(await db.Exports.FindCurrentCopyAsync(identity), "«Tolto» non è una copia corrente");
|
||||
Assert.AreEqual(ExportCopyState.Removed, (await db.Exports.FindLatestCopyAsync(identity))!.State, "Tolto: mai accodato da solo");
|
||||
|
||||
var again = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (2).jpg")); // «Copia di nuovo»
|
||||
Assert.AreEqual(again.Id, (await db.Exports.FindLatestCopyAsync(identity))!.Id);
|
||||
Assert.AreEqual(again.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
|
||||
|
||||
var frameZero = new ExportCopyIdentity(w.General, w.Marta, Make.Sha(1), ExportVariant.Frame, ExportFormat.Jpg, TimeSpan.Zero);
|
||||
var atZero = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a_f0.jpg") with { Variant = ExportVariant.Frame, Format = ExportFormat.Jpg, FrameAt = TimeSpan.Zero, CopySha256 = Make.Sha(4) });
|
||||
Assert.AreEqual(atZero.Id, (await db.Exports.FindCurrentCopyAsync(frameZero))!.Id);
|
||||
Assert.IsNull(await db.Exports.FindCurrentCopyAsync(frameZero with { FrameAt = null }), "nessun istante e l'istante 0 sono identità diverse");
|
||||
Assert.IsNull(await db.Exports.FindCurrentCopyAsync(identity with { AccountId = w.Luca }));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CopiesAreFoundBySha256AndByPath()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var general = await db.Exports.AddCopyAsync(w.WholeCopy("Marta.Demo/Caffè.jpg"));
|
||||
var own = await db.Exports.AddCopyAsync(w.WholeCopy("caffè.jpg", destination: w.Own));
|
||||
var luca = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/caffè.jpg", account: w.Luca, media: w.LucaMedia));
|
||||
await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/altro.jpg") with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2) });
|
||||
|
||||
CollectionAssert.AreEqual(new[] { luca.Id, own.Id, general.Id }, (await db.Exports.ListCopiesBySha256Async(Make.Sha(1).ToUpperInvariant())).Select(c => c.Id).ToArray());
|
||||
|
||||
Assert.AreEqual(general.Id, (await db.Exports.FindCopyByPathAsync(w.General, "marta.demo/CAFFÈ.JPG".Replace("È", "è", StringComparison.Ordinal)))!.Id, "maiuscole ASCII diverse");
|
||||
Assert.AreEqual(general.Id, (await db.Exports.FindCopyByPathAsync(w.General, @"marta.demo\Caffe" + "\u0300" + ".jpg"))!.Id, "'\\' e forma NFD");
|
||||
Assert.IsNull(await db.Exports.FindCopyByPathAsync(w.Own, "Marta.Demo/Caffè.jpg"));
|
||||
await db.Exports.UpdateCopyAsync(general with { State = ExportCopyState.Removed });
|
||||
Assert.IsNull(await db.Exports.FindCopyByPathAsync(w.General, "Marta.Demo/Caffè.jpg"), "un percorso «Tolto» è di nuovo libero");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CopiesOfADestinationArePagedAndCounted()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var ids = new List<long>();
|
||||
for (var i = 0; i < 7; i++)
|
||||
{
|
||||
var copy = await db.Exports.AddCopyAsync(w.WholeCopy($"marta.demo/{i}.jpg") with { SourceSha256 = Make.Sha(100 + i), CopySha256 = Make.Sha(100 + i) });
|
||||
ids.Add(copy.Id);
|
||||
if (i % 3 == 0)
|
||||
{
|
||||
await db.Exports.UpdateCopyAsync(copy with { State = ExportCopyState.Removed });
|
||||
}
|
||||
}
|
||||
|
||||
await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own));
|
||||
|
||||
var pages = new List<long>();
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await db.Exports.ListCopiesAsync(w.General, afterId: after, limit: 3);
|
||||
if (page.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
pages.AddRange(page.Select(c => c.Id));
|
||||
after = page[^1].Id;
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(ids, pages);
|
||||
CollectionAssert.AreEqual(new[] { ids[0], ids[3], ids[6] }, (await db.Exports.ListCopiesAsync(w.General, ExportCopyState.Removed)).Select(c => c.Id).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { ids[4], ids[5] }, (await db.Exports.ListCopiesAsync(w.General, ExportCopyState.Copied, afterId: ids[3])).Select(c => c.Id).ToArray());
|
||||
|
||||
var counts = await db.Exports.CountCopiesAsync(w.General);
|
||||
Assert.HasCount(Enum.GetValues<ExportCopyState>().Length, counts);
|
||||
Assert.AreEqual(4, counts[ExportCopyState.Copied]);
|
||||
Assert.AreEqual(3, counts[ExportCopyState.Removed]);
|
||||
Assert.AreEqual(0, counts[ExportCopyState.Superseded]);
|
||||
Assert.AreEqual(0, counts[ExportCopyState.Failed]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SupersedingFollowsTheFileOfTheAccount()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var (a, b, c) = (Make.Sha(1), Make.Sha(2), Make.Sha(3));
|
||||
var copied = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
var removed = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own) with { State = ExportCopyState.Removed });
|
||||
var converted = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.png") with { Variant = ExportVariant.Converted, Format = ExportFormat.Png, CopySha256 = Make.Sha(4) });
|
||||
var luca = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia));
|
||||
|
||||
Assert.AreEqual(3, await db.Exports.SupersedeCopiesAsync(w.Marta, a.ToUpperInvariant(), b, Make.T0.AddDays(1)));
|
||||
|
||||
var first = (await db.Exports.GetCopyAsync(copied.Id))!;
|
||||
Assert.AreEqual(ExportCopyState.Superseded, first.State);
|
||||
Assert.AreEqual(b, first.SupersededBySha256);
|
||||
Assert.AreEqual(Make.T0.AddDays(1), first.StateChangedAt);
|
||||
Assert.AreEqual(ExportCopyState.Superseded, (await db.Exports.GetCopyAsync(converted.Id))!.State);
|
||||
var stamped = (await db.Exports.GetCopyAsync(removed.Id))!;
|
||||
Assert.AreEqual(ExportCopyState.Removed, stamped.State, "un «Tolto» resta tolto");
|
||||
Assert.AreEqual(b, stamped.SupersededBySha256);
|
||||
var other = (await db.Exports.GetCopyAsync(luca.Id))!;
|
||||
Assert.AreEqual(ExportCopyState.Copied, other.State, "le copie di un altro account non cambiano");
|
||||
Assert.IsNull(other.SupersededBySha256);
|
||||
CollectionAssert.AreEquivalent(new[] { copied.Id, removed.Id, converted.Id }, (await db.Exports.ListCopiesBySha256Async(b)).Select(x => x.Id).ToArray());
|
||||
|
||||
Assert.AreEqual(3, await db.Exports.SupersedeCopiesAsync(w.Marta, b, c, Make.T0.AddDays(2)));
|
||||
CollectionAssert.AreEquivalent(new[] { copied.Id, removed.Id, converted.Id }, (await db.Exports.ListCopiesBySha256Async(c)).Select(x => x.Id).ToArray());
|
||||
Assert.IsEmpty(await db.Exports.ListCopiesBySha256Async(b));
|
||||
Assert.AreEqual(Make.T0.AddDays(1), (await db.Exports.GetCopyAsync(copied.Id))!.StateChangedAt, "spostare in avanti non è un cambio di stato");
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.SupersedeCopiesAsync(w.Marta, c, c, Make.T0));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The library file goes back to an earlier one (A→B→A, or A→B→C→A: «Tieni il più grande» compares pixels or bytes
|
||||
/// and is not transitive; a rebuild keeps the file on disk): the copy matches again and is never superseded by itself.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task SupersedingBackToTheOriginalRevivesTheCopy()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var (a, b, c) = (Make.Sha(1), Make.Sha(2), Make.Sha(3));
|
||||
var identity = new ExportCopyIdentity(w.General, w.Marta, a, ExportVariant.Whole, ExportFormat.Original, null);
|
||||
var copied = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
var removed = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own) with { State = ExportCopyState.Removed });
|
||||
|
||||
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(1)));
|
||||
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, b, a, Make.T0.AddDays(2)));
|
||||
|
||||
var back = (await db.Exports.GetCopyAsync(copied.Id))!;
|
||||
Assert.AreEqual(ExportCopyState.Copied, back.State, "la copia è di nuovo uguale al file della libreria");
|
||||
Assert.IsNull(back.SupersededBySha256);
|
||||
Assert.AreEqual(Make.T0.AddDays(2), back.StateChangedAt);
|
||||
Assert.AreEqual(copied.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
|
||||
var stillRemoved = (await db.Exports.GetCopyAsync(removed.Id))!;
|
||||
Assert.AreEqual(ExportCopyState.Removed, stillRemoved.State, "un «Tolto» resta tolto");
|
||||
Assert.IsNull(stillRemoved.SupersededBySha256);
|
||||
Assert.IsEmpty(await db.Exports.ListCopiesBySha256Async(b));
|
||||
|
||||
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(3)));
|
||||
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, b, c, Make.T0.AddDays(4)));
|
||||
Assert.AreEqual(2, await db.Exports.SupersedeCopiesAsync(w.Marta, c, a, Make.T0.AddDays(5)));
|
||||
Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(copied.Id))!.State, "A→B→C→A");
|
||||
Assert.IsNull((await db.Exports.GetCopyAsync(removed.Id))!.SupersededBySha256);
|
||||
Assert.AreEqual(0L, await ScalarAsync(db, "SELECT COUNT(*) FROM export_copy WHERE superseded_by_sha256 = source_sha256"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SupersedingBackKeepsTheCurrentCopyOfTheIdentity()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var (a, b) = (Make.Sha(1), Make.Sha(2));
|
||||
var identity = new ExportCopyIdentity(w.General, w.Marta, a, ExportVariant.Whole, ExportFormat.Original, null);
|
||||
|
||||
// Two Superseded rows of one identity: only the newest can come back, the unique index allows one current row.
|
||||
var oldest = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(1));
|
||||
var newer = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (2).jpg")); // «Copia di nuovo»
|
||||
await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(2));
|
||||
|
||||
Assert.AreEqual(1, await db.Exports.SupersedeCopiesAsync(w.Marta, b, a, Make.T0.AddDays(3)));
|
||||
Assert.AreEqual(newer.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
|
||||
var history = (await db.Exports.GetCopyAsync(oldest.Id))!;
|
||||
Assert.AreEqual(ExportCopyState.Superseded, history.State, "resta storia, superata dal file di prima");
|
||||
Assert.AreEqual(b, history.SupersededBySha256);
|
||||
|
||||
// A current row made meanwhile (copied again while the library held B): the Superseded row stays history.
|
||||
await db.Exports.SupersedeCopiesAsync(w.Marta, a, b, Make.T0.AddDays(4));
|
||||
var third = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (3).jpg"));
|
||||
Assert.AreEqual(0, await db.Exports.SupersedeCopiesAsync(w.Marta, b, a, Make.T0.AddDays(5)));
|
||||
Assert.AreEqual(third.Id, (await db.Exports.FindCurrentCopyAsync(identity))!.Id);
|
||||
Assert.AreEqual(ExportCopyState.Superseded, (await db.Exports.GetCopyAsync(newer.Id))!.State);
|
||||
Assert.AreEqual(b, (await db.Exports.GetCopyAsync(newer.Id))!.SupersededBySha256);
|
||||
}
|
||||
|
||||
/// <summary>The partial unique indexes of 0003 reach the callers as <see cref="DuplicateRecordException"/>, never as a SQLite error.</summary>
|
||||
[TestMethod]
|
||||
public async Task CollisionsAreDuplicateRecords()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
|
||||
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, @"Z:\Altra")), "ux_export_destination_general");
|
||||
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.AddDestinationAsync(Destination(ExportScope.Account, w.Marta, @"Z:\Marta")), "ux_export_destination_account");
|
||||
Assert.HasCount(2, await db.Exports.ListDestinationsAsync(includeRetired: true));
|
||||
|
||||
var first = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/b.jpg")), "ux_export_copy_identity");
|
||||
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.AddCopyAsync(w.WholeCopy("MARTA.demo/a.jpg", account: w.Luca, media: w.LucaMedia)), "ux_export_copy_path");
|
||||
await db.Exports.UpdateCopyAsync(first with { State = ExportCopyState.Removed });
|
||||
var second = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/b.jpg"));
|
||||
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Exports.UpdateCopyAsync(first), "un «Tolto» non torna copiato accanto alla copia corrente");
|
||||
Assert.AreEqual(ExportCopyState.Removed, (await db.Exports.GetCopyAsync(first.Id))!.State);
|
||||
Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(second.Id))!.State);
|
||||
|
||||
var pending = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.MartaMedia, Format = ExportFormat.Jpg, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0 });
|
||||
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Conversions.AddAsync(pending with { Id = 0 }), "ux_media_conversion_current");
|
||||
var removed = pending with { State = MediaConversionState.Removed, RelativePath = "post/a.jpg.jpg", Bytes = 1, Sha256 = Make.Sha(2), ConvertedAt = Make.T0 };
|
||||
await db.Conversions.UpdateAsync(removed);
|
||||
await db.Conversions.AddAsync(pending with { Id = 0 });
|
||||
await Assert.ThrowsExactlyAsync<DuplicateRecordException>(() => db.Conversions.UpdateAsync(removed with { State = MediaConversionState.Converted }), "ux_media_conversion_current");
|
||||
Assert.AreEqual(MediaConversionState.Removed, (await db.Conversions.GetAsync(pending.Id))!.State);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RunsAndItemsRoundTrip()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
var old = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0, State = ExportRunState.Completed, CompletedAt = Make.T0.AddMinutes(5) });
|
||||
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0.AddDays(1), Origin = ExportRunOrigin.Automatic });
|
||||
var recognize = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.Own, StartedAt = Make.T0.AddDays(2), Kind = ExportRunKind.Recognize, State = ExportRunState.Paused, LastError = "Disco non raggiungibile" });
|
||||
|
||||
Assert.AreEqual(recognize, await db.Exports.GetRunAsync(recognize.Id));
|
||||
CollectionAssert.AreEqual(new[] { recognize.Id, run.Id, old.Id }, (await db.Exports.ListRunsAsync()).Select(r => r.Id).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { run.Id, recognize.Id }, (await db.Exports.ListUnfinishedRunsAsync()).Select(r => r.Id).ToArray());
|
||||
var interrupted = run with { State = ExportRunState.Interrupted };
|
||||
await db.Exports.UpdateRunAsync(interrupted);
|
||||
Assert.AreEqual(interrupted, await db.Exports.GetRunAsync(run.Id));
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateRunAsync(run with { Id = 9999 }));
|
||||
|
||||
ExportItem[] items =
|
||||
[
|
||||
new() { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1) },
|
||||
new() { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1), Variant = ExportVariant.Converted, Format = ExportFormat.Jpg },
|
||||
new() { RunId = run.Id, MediaId = w.MartaMedia, AccountId = w.Marta, SourceSha256 = Make.Sha(1), Variant = ExportVariant.Frame, Format = ExportFormat.Png, FrameAt = TimeSpan.FromSeconds(2) },
|
||||
new() { RunId = run.Id, MediaId = w.LucaMedia, AccountId = w.Luca, SourceSha256 = Make.Sha(1) },
|
||||
];
|
||||
await db.Exports.AddItemsAsync(items);
|
||||
await db.Exports.AddItemsAsync(items); // resume: nothing twice
|
||||
await db.Exports.AddItemsAsync([items[0] with { RunId = old.Id }]);
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddItemsAsync([items[0] with { AccountId = null }]));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.AddItemsAsync([items[0] with { MediaId = null }]), "senza file non si riconoscerebbe alla ripresa");
|
||||
|
||||
var listed = await db.Exports.ListItemsAsync(new() { RunId = run.Id });
|
||||
Assert.HasCount(4, listed);
|
||||
Assert.AreEqual(items[2] with { Id = listed[2].Id }, listed[2]);
|
||||
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
|
||||
var done = listed[0] with { State = ExportItemState.Copied, RelativePath = @"marta.demo\a.jpg", CopyId = copy.Id };
|
||||
var skipped = listed[3] with { State = ExportItemState.Skipped, Note = "AnimatedImage" };
|
||||
await db.Exports.UpdateItemsAsync([done, skipped]);
|
||||
Assert.AreEqual(done with { RelativePath = "marta.demo/a.jpg" }, await db.Exports.GetItemAsync(done.Id));
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateItemsAsync([done with { Id = 9999 }]));
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Exports.UpdateItemsAsync([done with { RunId = old.Id }]));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateItemsAsync([done with { MediaId = w.LucaMedia }]));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateItemsAsync([done with { Variant = ExportVariant.Converted, Format = ExportFormat.Png }]));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Exports.UpdateItemsAsync([listed[2] with { FrameAt = TimeSpan.FromSeconds(3) }]));
|
||||
Assert.AreEqual(done with { RelativePath = "marta.demo/a.jpg" }, await db.Exports.GetItemAsync(done.Id), "l'identità del file resta");
|
||||
|
||||
CollectionAssert.AreEqual(new[] { listed[1].Id, listed[2].Id }, (await db.Exports.ListItemsAsync(new() { RunId = run.Id, State = ExportItemState.Pending })).Select(i => i.Id).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { listed[2].Id, listed[3].Id }, (await db.Exports.ListItemsAsync(new() { RunId = run.Id, AfterId = listed[1].Id, Limit = 5 })).Select(i => i.Id).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { listed[0].Id }, (await db.Exports.ListItemsAsync(new() { RunId = run.Id, Limit = 1 })).Select(i => i.Id).ToArray());
|
||||
|
||||
var summary = await db.Exports.GetRunSummaryAsync(run.Id);
|
||||
Assert.AreEqual(4, summary.Total);
|
||||
Assert.HasCount(Enum.GetValues<ExportItemState>().Length, summary.ByState);
|
||||
Assert.AreEqual(2, summary.ByState[ExportItemState.Pending]);
|
||||
Assert.AreEqual(1, summary.ByState[ExportItemState.Copied]);
|
||||
Assert.AreEqual(1, summary.ByState[ExportItemState.Skipped]);
|
||||
Assert.AreEqual(0, summary.ByState[ExportItemState.Failed]);
|
||||
|
||||
await db.Exports.DeleteRunAsync(run.Id);
|
||||
Assert.IsNull(await db.Exports.GetRunAsync(run.Id));
|
||||
Assert.IsEmpty(await db.Exports.ListItemsAsync(new() { RunId = run.Id }));
|
||||
Assert.HasCount(1, await db.Exports.ListItemsAsync(new() { RunId = old.Id }), "gli altri lavori restano");
|
||||
Assert.IsNotNull(await db.Exports.GetCopyAsync(copy.Id), "le copie restano");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task VideoAnalysesKeepTheHighestAlgorithm()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
|
||||
Assert.IsNull(await db.VideoAnalyses.GetAsync(Make.Sha(1)));
|
||||
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1).ToUpperInvariant(), 1, VideoAnalysisOutcome.Still, Make.T0));
|
||||
Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0), await db.VideoAnalyses.GetAsync(Make.Sha(1)));
|
||||
|
||||
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Moving, Make.T0.AddDays(1)));
|
||||
Assert.AreEqual(2, (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Algorithm, "vale l'algoritmo più alto");
|
||||
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0.AddDays(2)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Outcome);
|
||||
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3)));
|
||||
Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3)), await db.VideoAnalyses.GetAsync(Make.Sha(1)), "lo stesso algoritmo si sostituisce");
|
||||
Assert.AreEqual(2L, await ScalarAsync(db, "SELECT COUNT(*) FROM video_analysis"));
|
||||
|
||||
for (var i = 10; i < 710; i++)
|
||||
{
|
||||
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(i), 1, i % 2 == 0 ? VideoAnalysisOutcome.Still : VideoAnalysisOutcome.Moving, Make.T0));
|
||||
}
|
||||
|
||||
var keys = Enumerable.Range(0, 800).Select(Make.Sha).ToList();
|
||||
var many = await db.VideoAnalyses.GetManyAsync(keys);
|
||||
Assert.HasCount(701, many);
|
||||
Assert.AreEqual(2, many[Make.Sha(1)].Algorithm);
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, many[Make.Sha(709)].Outcome);
|
||||
await Assert.ThrowsExactlyAsync<ArgumentOutOfRangeException>(() => db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 0, VideoAnalysisOutcome.Still, Make.T0)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ConversionsRoundTrip()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var w = await CreateAsync(db);
|
||||
|
||||
var pending = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.MartaMedia, Format = ExportFormat.Jpg, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0 });
|
||||
Assert.AreEqual(pending, await db.Conversions.GetAsync(pending.Id));
|
||||
Assert.AreEqual(MediaConversionState.Pending, pending.State);
|
||||
|
||||
var converted = pending with
|
||||
{
|
||||
State = MediaConversionState.Converted,
|
||||
RelativePath = "post/a.jpg.jpg",
|
||||
Bytes = 900,
|
||||
Sha256 = Make.Sha(2).ToUpperInvariant(),
|
||||
ConvertedAt = Make.T0.AddMinutes(1),
|
||||
StateChangedAt = Make.T0.AddMinutes(1),
|
||||
};
|
||||
await db.Conversions.UpdateAsync(converted);
|
||||
Assert.AreEqual(converted with { Sha256 = Make.Sha(2) }, await db.Conversions.GetAsync(pending.Id));
|
||||
CollectionAssert.AreEqual(new[] { pending.Id }, (await db.Conversions.FindBySha256Async(Make.Sha(2))).Select(c => c.Id).ToArray());
|
||||
|
||||
var removed = converted with { State = MediaConversionState.Removed, StateChangedAt = Make.T0.AddDays(1) };
|
||||
await db.Conversions.UpdateAsync(removed);
|
||||
Assert.AreEqual(MediaConversionState.Removed, (await db.Conversions.GetAsync(pending.Id))!.State);
|
||||
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Conversions.UpdateAsync(converted with { RelativePath = null }));
|
||||
await Assert.ThrowsExactlyAsync<ArgumentException>(() => db.Conversions.AddAsync(pending with { Format = ExportFormat.Original }));
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Conversions.UpdateAsync(converted with { Id = 9999 }));
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => db.Conversions.UpdateAsync(converted with { Format = ExportFormat.Png }));
|
||||
|
||||
var png = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.MartaMedia, Format = ExportFormat.Png, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0 });
|
||||
var again = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.MartaMedia, Format = ExportFormat.Jpg, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0.AddDays(2) });
|
||||
var luca = await db.Conversions.AddAsync(new MediaConversion { MediaId = w.LucaMedia, Format = ExportFormat.WebpLossless, SourceSha256 = Make.Sha(1), CreatedAt = Make.T0 });
|
||||
CollectionAssert.AreEqual(new[] { pending.Id, png.Id, again.Id }, (await db.Conversions.ListByMediaAsync(w.MartaMedia)).Select(c => c.Id).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { png.Id, again.Id, luca.Id }, (await db.Conversions.ListPendingAsync()).Select(c => c.Id).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { again.Id }, (await db.Conversions.ListPendingAsync(afterId: png.Id, limit: 1)).Select(c => c.Id).ToArray());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Support;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Febe.Tests.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Two accounts with the same post (a post of marta.demo, a tagged post of luca.demo, same SHA-256), the general
|
||||
/// folder and the own folder of marta.demo: the starting point of the export tests.
|
||||
/// </summary>
|
||||
internal sealed record ExportWorld(long Marta, long Luca, long MartaEntry, long MartaMedia, long LucaEntry, long LucaMedia, long General, long Own)
|
||||
{
|
||||
public static async Task<ExportWorld> CreateAsync(FebeDatabase db, string generalRoot = @"E:\Copie")
|
||||
{
|
||||
var marta = await db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
|
||||
var luca = await db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
|
||||
var post = await db.Entries.AddAsync(Make.Entry(marta.Id, "555", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(1), "post/a.jpg")]);
|
||||
var tagged = await db.Entries.AddAsync(Make.Entry(luca.Id, "555", Make.T0, EntryKind.Tagged), [Make.Stored(Make.Photo(), Make.Sha(1), "taggati/a.jpg")]);
|
||||
var general = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, generalRoot));
|
||||
var own = await db.Exports.AddDestinationAsync(Destination(ExportScope.Account, marta.Id, @"F:\Marta"));
|
||||
return new ExportWorld(marta.Id, luca.Id, post.Stored.Entry.Id, post.Stored.Media[0].Id, tagged.Stored.Entry.Id, tagged.Stored.Media[0].Id, general.Id, own.Id);
|
||||
}
|
||||
|
||||
public static ExportDestination Destination(ExportScope scope, long? accountId, string root) => new()
|
||||
{
|
||||
Scope = scope,
|
||||
AccountId = accountId,
|
||||
RootPath = root,
|
||||
ContentTypes = ContentTypes.All,
|
||||
CreatedAt = Make.T0,
|
||||
};
|
||||
|
||||
/// <summary>A whole copy of the shared photo for marta.demo in the general folder, at <paramref name="path"/>.</summary>
|
||||
public ExportCopy WholeCopy(string path, long? destination = null, long? account = null, long? media = null) => new()
|
||||
{
|
||||
DestinationId = destination ?? General,
|
||||
AccountId = account ?? Marta,
|
||||
MediaId = media ?? MartaMedia,
|
||||
SourceSha256 = Make.Sha(1),
|
||||
Variant = ExportVariant.Whole,
|
||||
State = ExportCopyState.Copied,
|
||||
RelativePath = path,
|
||||
Bytes = 1000,
|
||||
CopySha256 = Make.Sha(1),
|
||||
CopiedAt = Make.T0.AddHours(1),
|
||||
};
|
||||
|
||||
/// <summary>A raw row of export_copy (the whole copy above), with changes.</summary>
|
||||
public Dictionary<string, object?> CopyRow(params (string Column, object? Value)[] changes) => Row(
|
||||
new()
|
||||
{
|
||||
["destination_id"] = General,
|
||||
["account_id"] = Marta,
|
||||
["media_id"] = MartaMedia,
|
||||
["source_sha256"] = Make.Sha(1),
|
||||
["variant"] = "Whole",
|
||||
["format"] = "Original",
|
||||
["frame_at_ms"] = null,
|
||||
["state"] = "Copied",
|
||||
["superseded_by_sha256"] = null,
|
||||
["origin"] = "Written",
|
||||
["relative_path"] = "marta.demo/a.jpg",
|
||||
["bytes"] = 1000L,
|
||||
["copy_sha256"] = Make.Sha(1),
|
||||
["copied_at"] = 0L,
|
||||
},
|
||||
changes);
|
||||
|
||||
/// <summary>A raw row of export_destination: a retired general folder, with changes.</summary>
|
||||
public static Dictionary<string, object?> DestinationRow(params (string Column, object? Value)[] changes) => Row(
|
||||
new()
|
||||
{
|
||||
["scope"] = "General",
|
||||
["account_id"] = null,
|
||||
["removed_account_username"] = null,
|
||||
["root_path"] = @"G:\Altra",
|
||||
["content_types"] = 63L,
|
||||
["photo_format"] = null,
|
||||
["video_format"] = null,
|
||||
["automatic"] = 0L,
|
||||
["automatic_since"] = null,
|
||||
["created_at"] = 0L,
|
||||
["removed_at"] = 1L,
|
||||
},
|
||||
changes);
|
||||
|
||||
public Dictionary<string, object?> RunRow(params (string Column, object? Value)[] changes) => Row(
|
||||
new() { ["destination_id"] = General, ["kind"] = "Copy", ["origin"] = "Manual", ["state"] = "Running", ["started_at"] = 0L },
|
||||
changes);
|
||||
|
||||
public Dictionary<string, object?> ItemRow(long runId, params (string Column, object? Value)[] changes) => Row(
|
||||
new()
|
||||
{
|
||||
["run_id"] = runId,
|
||||
["media_id"] = MartaMedia,
|
||||
["account_id"] = Marta,
|
||||
["source_sha256"] = Make.Sha(1),
|
||||
["variant"] = "Whole",
|
||||
["format"] = "Original",
|
||||
["frame_at_ms"] = null,
|
||||
["state"] = "Pending",
|
||||
},
|
||||
changes);
|
||||
|
||||
public static Dictionary<string, object?> AnalysisRow(params (string Column, object? Value)[] changes) => Row(
|
||||
new() { ["sha256"] = Make.Sha(5), ["algorithm"] = 1L, ["outcome"] = "Still", ["analyzed_at"] = 0L },
|
||||
changes);
|
||||
|
||||
public Dictionary<string, object?> ConversionRow(params (string Column, object? Value)[] changes) => Row(
|
||||
new() { ["media_id"] = MartaMedia, ["format"] = "Jpg", ["state"] = "Pending", ["source_sha256"] = Make.Sha(1), ["created_at"] = 0L },
|
||||
changes);
|
||||
|
||||
/// <summary>Inserts a raw row and returns its rowid.</summary>
|
||||
public static Task<long> InsertAsync(FebeDatabase db, string table, IReadOnlyDictionary<string, object?> row) =>
|
||||
db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var c = w.Command($"INSERT INTO {table} ({string.Join(", ", row.Keys)}) VALUES ({string.Join(", ", row.Keys.Select(k => "@" + k))})");
|
||||
foreach (var (column, value) in row)
|
||||
{
|
||||
c.With("@" + column, value);
|
||||
}
|
||||
|
||||
c.ExecuteNonQuery();
|
||||
return w.LastInsertRowId();
|
||||
},
|
||||
default);
|
||||
|
||||
/// <summary>The row breaks a constraint (SQLITE_CONSTRAINT) and is not written.</summary>
|
||||
public static async Task RejectedAsync(FebeDatabase db, string table, IReadOnlyDictionary<string, object?> row, string because)
|
||||
{
|
||||
var error = await Assert.ThrowsExactlyAsync<SqliteException>(() => InsertAsync(db, table, row), because);
|
||||
Assert.AreEqual(19, error.SqliteErrorCode, because);
|
||||
}
|
||||
|
||||
public static Task<int> ExecuteAsync(FebeDatabase db, string sql, params (string Name, object? Value)[] parameters) =>
|
||||
db.WriteAsync(
|
||||
w =>
|
||||
{
|
||||
var c = w.Command(sql);
|
||||
foreach (var (name, value) in parameters)
|
||||
{
|
||||
c.With(name, value);
|
||||
}
|
||||
|
||||
return c.ExecuteNonQuery();
|
||||
},
|
||||
default);
|
||||
|
||||
public static Task<long> ScalarAsync(FebeDatabase db, string sql, params (string Name, object? Value)[] parameters) =>
|
||||
db.ReadAsync(
|
||||
c =>
|
||||
{
|
||||
var command = c.Command(sql);
|
||||
foreach (var (name, value) in parameters)
|
||||
{
|
||||
command.With(name, value);
|
||||
}
|
||||
|
||||
return command.ScalarInt64();
|
||||
},
|
||||
default);
|
||||
|
||||
public static Task<long> ForeignKeyProblemsAsync(FebeDatabase db) => ScalarAsync(db, "SELECT COUNT(*) FROM pragma_foreign_key_check");
|
||||
|
||||
private static Dictionary<string, object?> Row(Dictionary<string, object?> row, (string Column, object? Value)[] changes)
|
||||
{
|
||||
foreach (var (column, value) in changes)
|
||||
{
|
||||
row[column] = value;
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,19 @@ public sealed class MigrationTests
|
||||
[
|
||||
"setting", "account", "entry", "media", "highlight", "highlight_entry", "duplicate_pair", "task", "action_log",
|
||||
"session", "incident", "event", "following", "import_run", "import_file",
|
||||
"export_destination", "export_account", "export_copy", "export_run", "export_item", "video_analysis", "media_conversion",
|
||||
];
|
||||
|
||||
/// <summary>The tables of schema version 1, which migrations 2 and 3 never rewrite.</summary>
|
||||
private static readonly string[] Version1Tables =
|
||||
[
|
||||
"setting", "account", "entry", "media", "highlight", "highlight_entry", "duplicate_pair", "task", "action_log",
|
||||
"session", "incident", "event", "following", "import_run", "import_file",
|
||||
];
|
||||
|
||||
private static readonly string[] ExportTables =
|
||||
["export_destination", "export_account", "export_copy", "export_run", "export_item", "video_analysis", "media_conversion"];
|
||||
|
||||
[TestMethod]
|
||||
public void EmbeddedMigrationsAreNumberedFromOne()
|
||||
{
|
||||
@@ -24,6 +35,8 @@ public sealed class MigrationTests
|
||||
}
|
||||
|
||||
Assert.AreEqual("schema", migrations[0].Name);
|
||||
Assert.AreEqual("ordine_scaricamento", migrations[1].Name);
|
||||
Assert.AreEqual("esportazione", migrations[2].Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -145,6 +158,234 @@ public sealed class MigrationTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DatabaseAtVersion1IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(1);
|
||||
|
||||
[TestMethod]
|
||||
public async Task DatabaseAtVersion2IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(2);
|
||||
|
||||
[TestMethod]
|
||||
public void MigrationThreeChangesNoExistingTable()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
var path = temp.Combine("dati", FebeDatabase.FileName);
|
||||
var all = MigrationRunner.LoadEmbedded();
|
||||
Close(FebeDatabase.Open(path, all.Take(2).ToList()));
|
||||
var before = SchemaOf(path, Version1Tables);
|
||||
var shapesBefore = TableShapes(path, Version1Tables);
|
||||
|
||||
Close(FebeDatabase.Open(path, all));
|
||||
|
||||
CollectionAssert.AreEqual(before, SchemaOf(path, Version1Tables), "la migrazione 3 non tocca tabelle né indici esistenti");
|
||||
CollectionAssert.AreEqual(shapesBefore, TableShapes(path, Version1Tables), "colonne e indici delle tabelle esistenti restano gli stessi");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DatabaseOneVersionNewerIsRefusedAndLeftUntouched()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
var path = temp.Combine("dati", FebeDatabase.FileName);
|
||||
await using (var db = await TestDatabase.OpenAsync(temp))
|
||||
{
|
||||
await db.Settings.SetAsync("prova", "1");
|
||||
}
|
||||
|
||||
var next = MigrationRunner.LoadEmbedded().Count + 1;
|
||||
SetUserVersion(path, next);
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<DatabaseMigrationException>(() => FebeDatabase.OpenFileAsync(path));
|
||||
|
||||
Assert.Contains("più recente", error.Message);
|
||||
Assert.AreEqual((long)next, GetUserVersion(path));
|
||||
CollectionAssert.AreEqual(bytes, File.ReadAllBytes(path), "Febe non scrive nel database più recente");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A database left at an older version with data in every table is brought to the latest version: references
|
||||
/// clean, data unchanged, export tables empty, no export setting written.
|
||||
/// </summary>
|
||||
private static async Task UpgradeKeepsEverything(int fromVersion)
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
var path = temp.Combine("dati", FebeDatabase.FileName);
|
||||
var all = MigrationRunner.LoadEmbedded();
|
||||
Close(FebeDatabase.Open(path, all.Take(fromVersion).ToList()));
|
||||
Fill(path, fromVersion);
|
||||
var columns = ColumnsOf(path, Version1Tables);
|
||||
var before = Snapshot(path, columns);
|
||||
|
||||
await using (var db = FebeDatabase.Open(path, all))
|
||||
{
|
||||
Assert.AreEqual(all.Count, db.SchemaVersion);
|
||||
Assert.AreEqual(3, db.SchemaVersion);
|
||||
}
|
||||
|
||||
using var connection = Connect(path);
|
||||
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM pragma_foreign_key_check").ScalarInt64(), "foreign_key_check pulito");
|
||||
Assert.AreEqual("ok", connection.Command("PRAGMA integrity_check").ExecuteScalar());
|
||||
CollectionAssert.AreEqual(before, Snapshot(path, columns), "i dati di prima restano uguali");
|
||||
foreach (var table in ExportTables)
|
||||
{
|
||||
Assert.AreEqual(0L, connection.Command($"SELECT COUNT(*) FROM {table}").ScalarInt64(), $"{table} nasce vuota");
|
||||
}
|
||||
|
||||
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM setting WHERE key LIKE 'esportazione.%'").ScalarInt64());
|
||||
if (fromVersion >= 2)
|
||||
{
|
||||
Assert.AreEqual("storie,post", connection.Command("SELECT download_order FROM account WHERE username = 'marta.demo'").ExecuteScalar());
|
||||
Assert.AreEqual(1L, connection.Command("SELECT COUNT(*) FROM entry WHERE is_reel = 1").ScalarInt64());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Raw rows in every table of version 1 (and the columns of version 2), written without the stores.</summary>
|
||||
private static void Fill(string path, int version)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
|
||||
var sha = Make.Sha(7);
|
||||
var other = Make.Sha(8);
|
||||
connection.Command($"""
|
||||
INSERT INTO setting (key, value) VALUES ('libreria.schema', 'a/b'), ('motore.profilo', 'Prudent');
|
||||
INSERT INTO account (id, instagram_id, username, state, frequency, content_types, history_depth, backfill_posts_per_day, added_at)
|
||||
VALUES (1, '100', 'marta.demo', 'Active', 'Normal', 63, 'Everything', 50, 1000),
|
||||
(2, '200', 'luca.demo', 'Active', 'Normal', 63, 'Everything', 50, 1000);
|
||||
INSERT INTO entry (id, account_id, kind, instagram_id, published_at, state, provenance, discovered_at)
|
||||
VALUES (1, 1, 'Post', '555', 2000, 'Downloaded', 'Downloaded', 2000),
|
||||
(2, 2, 'Tagged', '555', 2000, 'Downloaded', 'Downloaded', 2000),
|
||||
(3, 1, 'Story', '777', 3000, 'Downloaded', 'Downloaded', 3000);
|
||||
INSERT INTO media (id, entry_id, position, kind, state, relative_path, bytes, sha256, downloaded_at)
|
||||
VALUES (1, 1, 1, 'Photo', 'Downloaded', 'post/a.jpg', 10, '{sha}', 2100),
|
||||
(2, 2, 1, 'Photo', 'Downloaded', 'taggati/a.jpg', 10, '{sha}', 2100),
|
||||
(3, 3, 1, 'Video', 'Downloaded', 'storie/b.mp4', 20, '{other}', 3100);
|
||||
INSERT INTO highlight (id, account_id, instagram_id, title, discovered_at) VALUES (1, 1, 'h1', 'Estate', 3000);
|
||||
INSERT INTO highlight_entry (highlight_id, entry_id, position) VALUES (1, 3, 1);
|
||||
INSERT INTO task (kind, account_id, due_at, state, created_at) VALUES ('Profile', 1, 4000, 'Pending', 4000);
|
||||
INSERT INTO import_run (id, source_path, mode, state, started_at) VALUES (1, 'C:/vecchie', 'Copy', 'Completed', 5000);
|
||||
INSERT INTO import_file (id, run_id, relative_path, folder, outcome, matched_media_id, decision, state)
|
||||
VALUES (1, 1, 'marta/a.jpg', 'marta', 'ProbableDuplicate', 1, 'None', 'Analyzed');
|
||||
INSERT INTO duplicate_pair (origin, reason, existing_media_id, candidate_import_file_id, decision, created_at)
|
||||
VALUES ('Import', 'PerceptualHash', 1, 1, 'Pending', 5000);
|
||||
INSERT INTO session (id, started_at, ended_at, action_count, outcome, summary) VALUES (1, 6000, 6500, 3, 'Completed', 'tre azioni');
|
||||
INSERT INTO action_log (at, category, account_id, session_id, amount) VALUES (6100, 'Profile', 1, 1, 1);
|
||||
INSERT INTO incident (at, level, signal, url, session_id, note) VALUES (6200, 'Pause', 'Http429', '/p/x', 1, 'prova');
|
||||
INSERT INTO event (at, severity, code, message, account_id, session_id) VALUES (6300, 'Info', 'Downloaded', 'scaricato', 1, 1);
|
||||
INSERT INTO "following" (instagram_id, username, display_name, is_private, position, read_at) VALUES ('300', 'anna.demo', 'Anna', 0, 1, 6400);
|
||||
""").ExecuteNonQuery();
|
||||
if (version >= 2)
|
||||
{
|
||||
connection.Command("UPDATE account SET download_order = 'storie,post' WHERE id = 1; UPDATE entry SET is_reel = 1 WHERE id = 1;").ExecuteNonQuery();
|
||||
}
|
||||
|
||||
Assert.AreEqual(0L, connection.Command("SELECT COUNT(*) FROM pragma_foreign_key_check").ScalarInt64());
|
||||
foreach (var table in Version1Tables)
|
||||
{
|
||||
Assert.IsGreaterThan(0L, connection.Command($"SELECT COUNT(*) FROM \"{table}\"").ScalarInt64(), $"{table} ha dati prima dell'aggiornamento");
|
||||
}
|
||||
}
|
||||
|
||||
private static SqliteConnection Connect(string path)
|
||||
{
|
||||
var connection = new SqliteConnection($"Data Source={path};Pooling=False");
|
||||
connection.Open();
|
||||
return connection;
|
||||
}
|
||||
|
||||
private static void Close(FebeDatabase db) => db.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
|
||||
/// <summary>The columns of the tables now, so a later snapshot reads the same ones.</summary>
|
||||
private static Dictionary<string, string[]> ColumnsOf(string path, IEnumerable<string> tables)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
var columns = new Dictionary<string, string[]>(StringComparer.Ordinal);
|
||||
foreach (var table in tables)
|
||||
{
|
||||
using var r = connection.Command($"SELECT name FROM pragma_table_info('{table}') ORDER BY cid").ExecuteReader();
|
||||
var names = new List<string>();
|
||||
while (r.Read())
|
||||
{
|
||||
names.Add(r.GetString(0));
|
||||
}
|
||||
|
||||
columns[table] = [.. names];
|
||||
}
|
||||
|
||||
return columns;
|
||||
}
|
||||
|
||||
/// <summary>Every row of the tables (the given columns), as text, in a stable order.</summary>
|
||||
private static List<string> Snapshot(string path, Dictionary<string, string[]> columns)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
var rows = new List<string>();
|
||||
foreach (var (table, names) in columns)
|
||||
{
|
||||
using var r = connection.Command($"SELECT {string.Join(", ", names.Select(n => $"\"{n}\""))} FROM \"{table}\"").ExecuteReader();
|
||||
var tableRows = new List<string>();
|
||||
while (r.Read())
|
||||
{
|
||||
var values = new string[r.FieldCount];
|
||||
for (var i = 0; i < r.FieldCount; i++)
|
||||
{
|
||||
values[i] = r.GetName(i) + "=" + (r.IsDBNull(i) ? "NULL" : Convert.ToString(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
tableRows.Add(table + ": " + string.Join(", ", values));
|
||||
}
|
||||
|
||||
tableRows.Sort(StringComparer.Ordinal);
|
||||
rows.AddRange(tableRows);
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>The SQL of the tables and of their indexes and triggers.</summary>
|
||||
private static List<string> SchemaOf(string path, IEnumerable<string> tables)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
var list = new List<string>();
|
||||
using var command = connection.Command("SELECT type || ' ' || name || ': ' || ifnull(sql, '') FROM sqlite_master WHERE tbl_name = @t ORDER BY type, name");
|
||||
foreach (var table in tables)
|
||||
{
|
||||
command.With("@t", table);
|
||||
using var r = command.ExecuteReader();
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add(r.GetString(0));
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Columns (pragma_table_info) and indexes (pragma_index_list) of the tables.</summary>
|
||||
private static List<string> TableShapes(string path, IEnumerable<string> tables)
|
||||
{
|
||||
using var connection = Connect(path);
|
||||
var list = new List<string>();
|
||||
foreach (var table in tables)
|
||||
{
|
||||
using (var r = connection.Command($"SELECT cid, name, type, \"notnull\", ifnull(dflt_value, ''), pk FROM pragma_table_info('{table}') ORDER BY cid").ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add($"{table} column {r.GetInt64(0)} {r.GetString(1)} {r.GetString(2)} {r.GetInt64(3)} {r.GetString(4)} {r.GetInt64(5)}");
|
||||
}
|
||||
}
|
||||
|
||||
using (var r = connection.Command($"SELECT name, \"unique\", origin, partial FROM pragma_index_list('{table}') ORDER BY name").ExecuteReader())
|
||||
{
|
||||
while (r.Read())
|
||||
{
|
||||
list.Add($"{table} index {r.GetString(0)} {r.GetInt64(1)} {r.GetString(2)} {r.GetInt64(3)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static void SetUserVersion(string path, int version)
|
||||
{
|
||||
using var connection = new SqliteConnection($"Data Source={path};Pooling=False");
|
||||
|
||||
@@ -164,6 +164,10 @@ public sealed partial class SpecificationConsistencyTests
|
||||
["D1 ha la migrazione 0002", "| **D1 Dashboard e ordine** |", new[] { "migrazione `0002`", "`account.download_order`", "`entry.is_reel`", "`ix_entry_discovered`", "`ix_media_entry_files`" }],
|
||||
["E1 prende la migrazione 0003", "| **E1 Schema** |", new[] { "migrazione `0003`", "la `0002` è di d1" }],
|
||||
["le tabelle dell'esportazione vanno nella 0003", "| `export_destination`", new[] { "migrazione `0003`" }],
|
||||
["le tabelle dell'esportazione sono costruite nella 0003", "| `export_destination`", new[] { "`export_account`", "`media_conversion`", "rimuovere un account la lascia senza account", "la ritira", "la tabella `media` non cambia", "`esportazione.stesso-post`" }],
|
||||
["la conversione per la libreria si registra in media_conversion", "- **per la libreria**", new[] { "`media_conversion`", "migrazione `0003`", "26 novembre 2026", "la tabella `media` non cambia" }],
|
||||
["E1 ha anche export_account e media_conversion", "| **E1 Schema** |", new[] { "`export_account`", "`media_conversion`", "`exportsettings`", "versioni 1 e 2" }],
|
||||
["i vincoli della 0003 sono nello schema", "- Dalla migrazione `0003` (tappa E1)", new[] { "`ux_export_copy_identity`", "`ux_export_copy_path`", "`ix_export_copy_sha256`", "`ix_export_copy_destination`", "on delete restrict", "ogni colonna di chiave esterna" }],
|
||||
["gli indici di D1 sono nello schema", "- Indici su (account, data di pubblicazione)", new[] { "`0002`", "`ix_entry_discovered`", "`ix_media_entry_files`" }],
|
||||
["le dipendenze dicono chi ha la 0002", "Dipendenze: C1", new[] { "la migrazione `0002` è di d1", "e1 prende la `0003`" }],
|
||||
["l'icona della Dashboard è layout-dashboard", "| Navigazione |", new[] { "`layout-dashboard`", "`layout-grid`" }],
|
||||
@@ -225,6 +229,14 @@ public sealed partial class SpecificationConsistencyTests
|
||||
|
||||
private static string Read(params string[] parts) => File.ReadAllText(Path.Combine([Root(), .. parts]));
|
||||
|
||||
/// <summary>The export tables of §8.3 are built by tappa E1: the row no longer says they are only planned.</summary>
|
||||
[TestMethod]
|
||||
public void TheExportTablesAreNoLongerOnlyPlanned()
|
||||
{
|
||||
var line = Read("docs", "SPECIFICA.md").Split('\n').First(l => l.StartsWith("| `export_destination`", StringComparison.Ordinal));
|
||||
Assert.DoesNotContain("**Previste**", line, "§8.3: le tabelle della 0003 sono costruite");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DynamicData(nameof(SettledPoints))]
|
||||
public void TheSpecificationSettlesThePoint(string point, string start, string[] phrases)
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Export;
|
||||
|
||||
/// <summary>The settings of Impostazioni → Esportazione in the <c>setting</c> table (spec §4.10).</summary>
|
||||
[TestClass]
|
||||
public sealed class ExportSettingsTests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task AnEmptyTableGivesTheDefaults()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
|
||||
var settings = await ExportSettings.LoadAsync(db.Settings);
|
||||
|
||||
Assert.AreEqual(ExportSettings.Default, settings);
|
||||
Assert.AreEqual(ExportFormat.Original, settings.PhotoFormat);
|
||||
Assert.AreEqual(ExportFormat.Original, settings.VideoFormat);
|
||||
Assert.AreEqual(ExportFormat.Original, settings.LibraryPhotoFormat);
|
||||
Assert.AreEqual(ExportFormat.Original, settings.LibraryVideoFormat);
|
||||
Assert.AreEqual(SamePostCopies.OnePerAccount, settings.SamePost, "«Una copia per account» per impostazione predefinita");
|
||||
Assert.IsFalse(settings.ConvertsCopies, "conversione per le copie spenta");
|
||||
Assert.IsFalse(settings.ConvertsLibrary, "conversione per la libreria spenta");
|
||||
Assert.AreEqual("92", ExportSettings.JpegQuality.ToString(System.Globalization.CultureInfo.InvariantCulture), "JPG a qualità 92, fissa");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SaveThenLoadRoundTripsAndWritesOnlyTheExportKeys()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var chosen = new ExportSettings(ExportFormat.Jpg, ExportFormat.Mp4, ExportFormat.WebpLossless, ExportFormat.Mp4, SamePostCopies.OneOnly);
|
||||
|
||||
await chosen.SaveAsync(db.Settings);
|
||||
|
||||
Assert.AreEqual(chosen, await ExportSettings.LoadAsync(db.Settings));
|
||||
Assert.IsTrue(chosen.ConvertsCopies);
|
||||
Assert.IsTrue(chosen.ConvertsLibrary);
|
||||
var stored = await db.Settings.GetAllAsync();
|
||||
CollectionAssert.AreEquivalent(ExportSettingKeys.All.ToArray(), stored.Keys.ToArray());
|
||||
Assert.IsTrue(ExportSettingKeys.All.All(k => k.StartsWith("esportazione.", StringComparison.Ordinal)));
|
||||
Assert.AreEqual("WebpLossless", stored[ExportSettingKeys.LibraryPhotoFormat]);
|
||||
Assert.AreEqual("OneOnly", stored[ExportSettingKeys.SamePost]);
|
||||
|
||||
var photosOnly = new ExportSettings(PhotoFormat: ExportFormat.Png);
|
||||
Assert.IsTrue(photosOnly.ConvertsCopies);
|
||||
Assert.IsFalse(photosOnly.ConvertsLibrary);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(ExportSettingKeys.PhotoFormat, "")]
|
||||
[DataRow(ExportSettingKeys.PhotoFormat, "jpg")]
|
||||
[DataRow(ExportSettingKeys.PhotoFormat, "2")]
|
||||
[DataRow(ExportSettingKeys.PhotoFormat, "Jpg, Png")]
|
||||
[DataRow(ExportSettingKeys.PhotoFormat, "Mp4")]
|
||||
[DataRow(ExportSettingKeys.VideoFormat, "Png")]
|
||||
[DataRow(ExportSettingKeys.VideoFormat, "mp4")]
|
||||
[DataRow(ExportSettingKeys.LibraryPhotoFormat, "Mp4")]
|
||||
[DataRow(ExportSettingKeys.LibraryPhotoFormat, "1")]
|
||||
[DataRow(ExportSettingKeys.LibraryVideoFormat, "Jpg")]
|
||||
[DataRow(ExportSettingKeys.SamePost, "OneEach")]
|
||||
[DataRow(ExportSettingKeys.SamePost, "1")]
|
||||
[DataRow(ExportSettingKeys.SamePost, "oneonly")]
|
||||
public void AnInvalidValueFallsBackForItsKeyOnly(string key, string value)
|
||||
{
|
||||
var values = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
[ExportSettingKeys.PhotoFormat] = "Png",
|
||||
[ExportSettingKeys.VideoFormat] = "Mp4",
|
||||
[ExportSettingKeys.LibraryPhotoFormat] = "Jpg",
|
||||
[ExportSettingKeys.LibraryVideoFormat] = "Mp4",
|
||||
[ExportSettingKeys.SamePost] = "OneOnly",
|
||||
};
|
||||
var valid = ExportSettings.From(values);
|
||||
values[key] = value;
|
||||
|
||||
var read = ExportSettings.From(values);
|
||||
|
||||
var expected = key switch
|
||||
{
|
||||
ExportSettingKeys.PhotoFormat => valid with { PhotoFormat = ExportFormat.Original },
|
||||
ExportSettingKeys.VideoFormat => valid with { VideoFormat = ExportFormat.Original },
|
||||
ExportSettingKeys.LibraryPhotoFormat => valid with { LibraryPhotoFormat = ExportFormat.Original },
|
||||
ExportSettingKeys.LibraryVideoFormat => valid with { LibraryVideoFormat = ExportFormat.Original },
|
||||
_ => valid with { SamePost = SamePostCopies.OnePerAccount },
|
||||
};
|
||||
Assert.AreEqual(expected, read);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OpeningADatabaseWritesNoExportKey()
|
||||
{
|
||||
using var temp = new TempFolder();
|
||||
await using (var fresh = await TestDatabase.OpenAsync(temp, "nuovo"))
|
||||
{
|
||||
Assert.IsFalse((await fresh.Settings.GetAllAsync()).Keys.Any(k => k.StartsWith("esportazione.", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
var path = temp.Combine("vecchio", FebeDatabase.FileName);
|
||||
var all = MigrationRunner.LoadEmbedded();
|
||||
await FebeDatabase.Open(path, all.Take(1).ToList()).DisposeAsync();
|
||||
await using var migrated = FebeDatabase.Open(path, all);
|
||||
Assert.AreEqual(all.Count, migrated.SchemaVersion);
|
||||
Assert.IsFalse((await migrated.Settings.GetAllAsync()).Keys.Any(k => k.StartsWith("esportazione.", StringComparison.Ordinal)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user