Il prodotto prende il nome del repository, come chiesto per allineare la struttura agli altri progetti: soluzione Mimante.slnx, progetti src/Mimante, tests/Mimante.Tests e tools/Mimante.Schermate, spazi dei nomi Mimante.*, immagine alby96/mimante, modello docker/unraid/mimante.xml, compose in docker/, documenti in minuscolo (stato.md, architettura.md, come-funziona.md, schermate/), versioni dei pacchetti in Directory.Packages.props. Versione 2.0.0. Non cambiano database, tabelle, variabili d'ambiente, /config, chiave della sessione e riferimenti del sito: bidoo.default.json è identico e i nomi logici delle risorse incorporate restano quelli che le migrazioni cercano. divSaldoBidBottom è l'id di Bidoo. Compatibilità: il cookie dell'interfaccia diventa mimante_sessione (un accesso in più per browser dopo l'aggiornamento); le preferenze del browser passano da bidbot.* a mimante.* con una copia una tantum. Corretto anche il tema della pagina d'accesso, che leggeva il valore salvato senza togliere le virgolette del JSON. Tolto il codice non compilato: il riferimento del riscatto (lo sostituisce il riscatto nuovo) e il formato SQLite della versione desktop (ora la issue #31); sono leggibili al tag v1.2.0. Nuovi docs/processo.md, docs/decisioni.md, docs/docker.md (con i passi per sostituire il container su Unraid) e ADR 0014. Il Dockerfile copia Directory.Packages.props e .dockerignore esclude dati/. Build con gli avvisi come errori; 288 test verdi, i 14 sul database saltati perché Docker Desktop su questo PC non parte: girano nella CI con il suo PostgreSQL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
315 lines
12 KiB
C#
315 lines
12 KiB
C#
using System.Text.Json;
|
||
using Mimante.Config;
|
||
using Mimante.Logging;
|
||
using Mimante.Settings;
|
||
using Mimante.Web;
|
||
using Xunit;
|
||
|
||
namespace Mimante.Tests;
|
||
|
||
/// <summary>Niente simboli né emoji nei registri (portati dal legacy).</summary>
|
||
public class LogTextTests
|
||
{
|
||
[Theory]
|
||
[InlineData("✓ Convenienza OK → tutto ok — bene… ≤ 3 × 2 €", "Convenienza OK -> tutto ok - bene... <= 3 x 2 EUR")]
|
||
[InlineData("🔥 avvio motore ⚡", "avvio motore")]
|
||
[InlineData("riga uno\r\nriga due\tfine", "riga uno riga due fine")]
|
||
[InlineData("«virgolette» e “altre”", "\"virgolette\" e \"altre\"")]
|
||
[InlineData("", "")]
|
||
public void Il_testo_esce_in_chiaro(string dentro, string fuori)
|
||
{
|
||
Assert.Equal(fuori, LogText.Clean(dentro));
|
||
}
|
||
|
||
[Fact]
|
||
public void Il_registro_applicativo_tiene_il_tag_e_rispetta_il_livello()
|
||
{
|
||
var log = new AppLog(null) { MinLevel = LogLevel.Info, Capacity = 50 };
|
||
LogEntry? seen = null;
|
||
log.Entry += e => seen = e;
|
||
|
||
log.Debug("PUNTATA", "non si vede");
|
||
Assert.Null(seen);
|
||
|
||
log.Info("puntata", "Buono → 4,12 €");
|
||
Assert.NotNull(seen);
|
||
Assert.Equal("PUNTATA", seen!.Tag);
|
||
Assert.Equal("[PUNTATA] Buono -> 4,12 EUR", seen.Text);
|
||
Assert.Single(log.Snapshot());
|
||
}
|
||
|
||
[Fact]
|
||
public void L_anello_in_memoria_ha_un_tetto()
|
||
{
|
||
var log = new AppLog(null) { Capacity = 60 };
|
||
for (var i = 0; i < 200; i++) log.Info("X", $"riga {i}");
|
||
var rows = log.Snapshot();
|
||
Assert.Equal(60, rows.Count);
|
||
Assert.Equal("riga 199", rows[^1].Message);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Il_file_giornaliero_riceve_le_righe()
|
||
{
|
||
using var dir = new TempDir();
|
||
var file = new FileLog(dir.Path);
|
||
var log = new AppLog(file);
|
||
log.Info("AVVIO", "prova");
|
||
await file.DisposeAsync();
|
||
|
||
var text = File.ReadAllText(file.PathFor("app", DateTime.Now));
|
||
Assert.Contains("[AVVIO] prova", text);
|
||
}
|
||
}
|
||
|
||
public class EnvConfigTests
|
||
{
|
||
[Theory]
|
||
[InlineData("192.168.30.23", "192.168.30.23", null)]
|
||
[InlineData("192.168.30.23:5433", "192.168.30.23", 5433)]
|
||
[InlineData("postgres:5432", "postgres", 5432)]
|
||
[InlineData("[::1]:5432", "::1", 5432)]
|
||
[InlineData(" ", "", null)]
|
||
public void DB_HOST_accetta_anche_la_porta(string raw, string host, int? port)
|
||
{
|
||
var (h, p) = EnvConfig.SplitHost(raw);
|
||
Assert.Equal(host, h);
|
||
Assert.Equal(port, p);
|
||
}
|
||
|
||
[Fact]
|
||
public void Predefiniti_e_porta_separata()
|
||
{
|
||
var env = new Dictionary<string, string?> { ["DB_HOST"] = "db", ["DB_PORT"] = "6000", ["DB_PASSWORD"] = "x" };
|
||
var cfg = EnvConfig.Read(k => env.GetValueOrDefault(k), Array.Empty<string>());
|
||
Assert.Equal("db", cfg.DbHost);
|
||
Assert.Equal(6000, cfg.DbPort);
|
||
Assert.Equal("admin", cfg.DbUser);
|
||
Assert.Equal("autobidder", cfg.DbName);
|
||
Assert.Equal(8080, cfg.HttpPort);
|
||
Assert.False(cfg.HasUiPassword);
|
||
Assert.Equal("/config", cfg.ConfigDir);
|
||
Assert.DoesNotContain("x", cfg.ToDbConfig().Describe());
|
||
}
|
||
}
|
||
|
||
/// <summary>Avvio senza variabili: schermata d'errore, niente database (ConfigErrorTests della specifica).</summary>
|
||
public class ConfigErrorTests
|
||
{
|
||
[Fact]
|
||
public async Task Senza_variabili_il_rapporto_dice_cosa_manca()
|
||
{
|
||
using var dir = new TempDir();
|
||
var env = EnvConfig.Read(_ => null, new[] { "--config", dir.Path });
|
||
var (report, db) = await StartupCheck.RunAsync(env, new ConfigPaths(dir.Path), 1, CancellationToken.None);
|
||
|
||
Assert.Null(db);
|
||
Assert.False(report.AllOk);
|
||
Assert.Contains(report.Items, i => i.Key == "db_host" && !i.Ok);
|
||
Assert.Contains(report.Items, i => i.Key == "db_password" && !i.Ok);
|
||
Assert.Contains(report.Items, i => i.Key == "ui_password" && !i.Ok);
|
||
Assert.Contains(report.Items, i => i.Key == "config" && i.Ok);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Database_irraggiungibile_da_un_errore_leggibile()
|
||
{
|
||
using var dir = new TempDir();
|
||
var vars = new Dictionary<string, string?> { ["DB_HOST"] = "127.0.0.1:1", ["DB_PASSWORD"] = "segreta", ["UI_PASSWORD"] = "x" };
|
||
var env = EnvConfig.Read(k => vars.GetValueOrDefault(k), new[] { "--config", dir.Path });
|
||
var (report, db) = await StartupCheck.RunAsync(env, new ConfigPaths(dir.Path), 1, CancellationToken.None);
|
||
|
||
Assert.Null(db);
|
||
var item = Assert.Single(report.Items, i => i.Key == "database");
|
||
Assert.False(item.Ok);
|
||
Assert.StartsWith("Npgsql:", item.Error);
|
||
Assert.DoesNotContain("segreta", item.Error + item.Detail);
|
||
|
||
var html = Pages.ConfigError("1.0.0", report, 30);
|
||
Assert.Contains("Mimante non può partire", html);
|
||
Assert.Contains("Riprova adesso", html);
|
||
Assert.DoesNotContain("segreta", html);
|
||
}
|
||
}
|
||
|
||
public class UiAuthTests
|
||
{
|
||
private static UiAuth Make(string password = "giusta") => new(password, new byte[32]);
|
||
|
||
[Fact]
|
||
public void Solo_la_password_giusta_passa()
|
||
{
|
||
var auth = Make();
|
||
Assert.True(auth.CheckPassword("giusta"));
|
||
Assert.False(auth.CheckPassword("Giusta"));
|
||
Assert.False(auth.CheckPassword(""));
|
||
Assert.False(auth.CheckPassword(null));
|
||
}
|
||
|
||
[Fact]
|
||
public void Il_cookie_vale_30_giorni_e_poi_scade()
|
||
{
|
||
var auth = Make();
|
||
var now = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero);
|
||
var token = auth.IssueToken(now);
|
||
|
||
Assert.True(auth.Validate(token, now.AddDays(29)).Valid);
|
||
Assert.False(auth.Validate(token, now.AddDays(31)).Valid);
|
||
Assert.True(auth.Validate(token, now.AddDays(2)).ShouldRenew);
|
||
Assert.False(auth.Validate(token, now.AddHours(2)).ShouldRenew);
|
||
}
|
||
|
||
[Fact]
|
||
public void Un_cookie_alterato_o_di_un_altra_password_non_vale()
|
||
{
|
||
var now = DateTimeOffset.UtcNow;
|
||
var token = Make().IssueToken(now);
|
||
|
||
Assert.False(Make("altra").Validate(token, now).Valid);
|
||
Assert.False(Make().Validate(token[..^2] + "AA", now).Valid);
|
||
Assert.False(Make().Validate("spazzatura", now).Valid);
|
||
Assert.False(Make().Validate(null, now).Valid);
|
||
}
|
||
|
||
[Fact]
|
||
public void Dopo_cinque_tentativi_l_attesa_cresce()
|
||
{
|
||
var auth = Make();
|
||
var now = DateTimeOffset.UtcNow;
|
||
for (var i = 0; i < 4; i++) Assert.Equal(TimeSpan.Zero, auth.RecordFailure("1.2.3.4", now));
|
||
|
||
Assert.Equal(TimeSpan.FromSeconds(2), auth.RecordFailure("1.2.3.4", now));
|
||
Assert.Equal(TimeSpan.FromSeconds(4), auth.RecordFailure("1.2.3.4", now));
|
||
Assert.Equal(TimeSpan.FromSeconds(8), auth.RecordFailure("1.2.3.4", now));
|
||
Assert.True(auth.LockedFor("1.2.3.4", now) > TimeSpan.Zero);
|
||
Assert.Equal(TimeSpan.Zero, auth.LockedFor("5.6.7.8", now));
|
||
|
||
auth.RecordSuccess("1.2.3.4");
|
||
Assert.Equal(TimeSpan.Zero, auth.LockedFor("1.2.3.4", now));
|
||
}
|
||
|
||
[Fact]
|
||
public void La_chiave_si_crea_una_volta_e_si_rilegge()
|
||
{
|
||
using var dir = new TempDir();
|
||
var file = Path.Combine(dir.Path, "sessione", "interfaccia.key");
|
||
var a = UiAuth.LoadOrCreateKey(file);
|
||
var b = UiAuth.LoadOrCreateKey(file);
|
||
Assert.Equal(32, a.Length);
|
||
Assert.Equal(a, b);
|
||
}
|
||
}
|
||
|
||
/// <summary>Impostazioni: valori di fabbrica, migrazione, puntate virtuali, segreti (SettingsMigrationTests).</summary>
|
||
public class SettingsTests
|
||
{
|
||
private static Dictionary<string, JsonElement> Patch(string json) =>
|
||
JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json)!;
|
||
|
||
[Fact]
|
||
public void I_paletti_di_fabbrica_sono_tutti_a_zero()
|
||
{
|
||
var s = new AppSettings();
|
||
Assert.Equal(0, s.DefaultMaxPrice);
|
||
Assert.Equal(0, s.MaxBidsPerAuction);
|
||
Assert.Equal(0, s.MinimumRemainingBids);
|
||
Assert.Equal(0, s.DailyBudgetEuro);
|
||
Assert.False(s.QuietHoursEnabled);
|
||
Assert.True(s.ShadowDecisionsInWatch);
|
||
Assert.Equal(100, s.LeadMinMs);
|
||
Assert.Equal(250, s.DefaultBidBeforeDeadlineMs);
|
||
Assert.Equal(300, s.LearningMinAuctions);
|
||
Assert.Equal(50, s.DataCapGb);
|
||
Assert.Equal("Osserva", s.AutoAddNewAuctionState);
|
||
}
|
||
|
||
[Fact]
|
||
public void La_migrazione_porta_i_modi_in_italiano()
|
||
{
|
||
var s = new AppSettings { SettingsSchemaVersion = 0, AutoAddNewAuctionState = "Watch", DefaultNewAuctionState = "Active" };
|
||
Assert.True(SettingsStore.Migrate(s));
|
||
Assert.Equal("Osserva", s.AutoAddNewAuctionState);
|
||
Assert.Equal("Attiva", s.DefaultNewAuctionState);
|
||
Assert.False(SettingsStore.Migrate(s));
|
||
}
|
||
|
||
[Fact]
|
||
public void La_migrazione_stringe_l_anticipo_solo_se_era_quello_di_fabbrica()
|
||
{
|
||
var old = new AppSettings { SettingsSchemaVersion = 1, LeadMinMs = 300, DefaultBidBeforeDeadlineMs = 500, ShadowDecisionsInWatch = false, MaxRequestsPerSecond = 40 };
|
||
Assert.True(SettingsStore.Migrate(old));
|
||
Assert.Equal(100, old.LeadMinMs);
|
||
Assert.Equal(250, old.DefaultBidBeforeDeadlineMs);
|
||
Assert.True(old.ShadowDecisionsInWatch);
|
||
Assert.Equal(0, old.MaxRequestsPerSecond);
|
||
|
||
// Un valore scritto dall'utente resta com'era.
|
||
var mine = new AppSettings { SettingsSchemaVersion = 1, LeadMinMs = 180, DefaultBidBeforeDeadlineMs = 400, MaxRequestsPerSecond = 25 };
|
||
SettingsStore.Migrate(mine);
|
||
Assert.Equal(180, mine.LeadMinMs);
|
||
Assert.Equal(400, mine.DefaultBidBeforeDeadlineMs);
|
||
Assert.Equal(25, mine.MaxRequestsPerSecond);
|
||
}
|
||
|
||
[Fact]
|
||
public void I_valori_fuori_scala_si_riportano_nei_limiti()
|
||
{
|
||
var s = SettingsStore.Normalize(new AppSettings { LeadMinMs = 10, LeadMaxMs = 5, QuietHoursStart = 25, DataCapGb = 0, PollCriticalMs = 1 });
|
||
Assert.Equal(100, s.LeadMinMs);
|
||
Assert.Equal(100, s.LeadMaxMs);
|
||
Assert.Equal(1, s.QuietHoursStart);
|
||
Assert.Equal(1, s.DataCapGb);
|
||
Assert.Equal(50, s.PollCriticalMs);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Il_salvataggio_vale_subito_e_si_scrive_nel_registro()
|
||
{
|
||
var log = new AppLog(null);
|
||
var store = new SettingsStore(null, log);
|
||
var result = await store.SaveAsync(Patch("""{"DailyBudgetEuro": 15, "MaxBidsPerAuction": 25}"""));
|
||
|
||
Assert.True(result.Ok);
|
||
Assert.Equal(15, store.Current.DailyBudgetEuro);
|
||
Assert.Equal(2, result.Changes.Count);
|
||
Assert.Contains(log.Snapshot(), e => e.Tag == "IMPOSTAZIONI" && e.Message.StartsWith("DailyBudgetEuro: 0 -> 15"));
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Le_puntate_virtuali_si_spengono_senza_conferme_e_la_vecchia_modalita_non_esiste_piu()
|
||
{
|
||
var store = new SettingsStore(null, null);
|
||
|
||
var off = await store.SaveAsync(Patch("""{"ShadowDecisionsInWatch": false}"""));
|
||
Assert.True(off.Ok);
|
||
Assert.False(store.Current.ShadowDecisionsInWatch);
|
||
|
||
// DAL VIVO non c'è più: le aste in Attiva puntano e basta.
|
||
Assert.False((await store.SaveAsync(Patch("""{"LiveBiddingEnabled": true}"""))).Ok);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task I_segreti_non_finiscono_nel_registro_e_tornano_mascherati()
|
||
{
|
||
var log = new AppLog(null);
|
||
var store = new SettingsStore(null, log);
|
||
await store.SaveAsync(Patch("""{"TelegramBotToken": "123:segretissimo"}"""));
|
||
|
||
Assert.DoesNotContain(log.Snapshot(), e => e.Message.Contains("segretissimo"));
|
||
Assert.Equal(SettingsStore.MaskedSecret, SettingsStore.ForDisplay(store.Current)["TelegramBotToken"]);
|
||
|
||
// Il valore mascherato che torna dall'interfaccia lascia il segreto com'era.
|
||
await store.SaveAsync(Patch("""{"TelegramBotToken": "********", "TelegramChatId": "42"}"""));
|
||
Assert.Equal("123:segretissimo", store.Current.TelegramBotToken);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Una_chiave_sconosciuta_o_un_tipo_sbagliato_non_si_salvano()
|
||
{
|
||
var store = new SettingsStore(null, null);
|
||
Assert.False((await store.SaveAsync(Patch("""{"NonEsiste": 1}"""))).Ok);
|
||
Assert.False((await store.SaveAsync(Patch("""{"DailyBudgetEuro": "tanto"}"""))).Ok);
|
||
Assert.Equal(0, store.Current.DailyBudgetEuro);
|
||
}
|
||
}
|