La revisione del lavoro sulle regole scritte ha trovato due promesse dei documenti che il codice non mantiene. La guida e l'ADR 0018 dicevano che durante il ristudio dell'archivio nessuna asta punta, nemmeno nei tre casi dell'eccezione; ma con l'apprendimento spento BidStrategy.Decide risponde prima del passo del modello, dove si controlla il ristudio, e un'asta in Attiva punta lo stesso entro i paletti. Il comportamento non cambia: guida, ADR 0018, nota all'ADR 0013, CLAUDE.md e il commento di BidStrategy ora dicono che il ristudio ferma «non pronto» e «senza stima» ma non l'apprendimento spento, e che se debba fermare anche questo è una scelta aperta per Alberto. La riga «Variabile ignorata: DB_PORT» arrivava solo nel registro, che dalla schermata d'errore di configurazione non si raggiunge, proprio nel caso in cui conta (DB_HOST senza porta, DB_PORT diversa da 5432, database non trovato): ora il suggerimento di «Database non raggiungibile» comincia con «DB_PORT non si legge più: scrivi la porta in DB_HOST (host:porta)», solo con il nome della variabile, con una prova; guida e ADR 0019 lo dicono. docs/stato.md resta fuori da questo lavoro, come da accordo: si aggiorna dopo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit cd913866ceaa3b8fd847841d2f4efd18a022914b)
394 lines
16 KiB
C#
394 lines
16 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_senza_variabili_tolte()
|
||
{
|
||
var env = new Dictionary<string, string?> { ["DB_HOST"] = "db", ["DB_PASSWORD"] = "x" };
|
||
var cfg = EnvConfig.Read(k => env.GetValueOrDefault(k), Array.Empty<string>());
|
||
Assert.Equal("db", cfg.DbHost);
|
||
Assert.Equal(5432, 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.Empty(cfg.IgnoredVariables);
|
||
Assert.Null(cfg.IgnoredVariablesNotice());
|
||
Assert.DoesNotContain("x", cfg.ToDbConfig().Describe());
|
||
}
|
||
|
||
[Fact]
|
||
public void La_porta_del_database_si_legge_solo_da_DB_HOST()
|
||
{
|
||
var env = new Dictionary<string, string?> { ["DB_HOST"] = "db: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);
|
||
}
|
||
|
||
[Fact]
|
||
public void DB_PORT_e_PORT_si_ignorano_e_l_avviso_non_ha_valori()
|
||
{
|
||
var env = new Dictionary<string, string?> { ["DB_HOST"] = "db", ["DB_PORT"] = "6001", ["PORT"] = "9001", ["DB_PASSWORD"] = "x" };
|
||
var cfg = EnvConfig.Read(k => env.GetValueOrDefault(k), Array.Empty<string>());
|
||
Assert.Equal(5432, cfg.DbPort);
|
||
Assert.Equal(8080, cfg.HttpPort);
|
||
Assert.Equal(new[] { "DB_PORT", "PORT" }, cfg.IgnoredVariables);
|
||
|
||
var notice = cfg.IgnoredVariablesNotice()!;
|
||
Assert.StartsWith("Variabili ignorate: DB_PORT e PORT.", notice);
|
||
Assert.Contains("DB_HOST (host:porta)", notice);
|
||
Assert.Contains("8080", notice);
|
||
Assert.DoesNotContain("6001", notice);
|
||
Assert.DoesNotContain("9001", notice);
|
||
|
||
var onlyDb = EnvConfig.Read(k => k == "DB_PORT" ? "6001" : null, Array.Empty<string>());
|
||
Assert.Equal(new[] { "DB_PORT" }, onlyDb.IgnoredVariables);
|
||
Assert.StartsWith("Variabile ignorata: DB_PORT.", onlyDb.IgnoredVariablesNotice());
|
||
Assert.DoesNotContain("8080", onlyDb.IgnoredVariablesNotice());
|
||
|
||
Assert.Empty(EnvConfig.Read(k => k == "PORT" ? " " : null, Array.Empty<string>()).IgnoredVariables);
|
||
}
|
||
|
||
[Theory]
|
||
[InlineData(new string[0], 8080)]
|
||
[InlineData(new[] { "--porta", "8090" }, 8090)]
|
||
[InlineData(new[] { "--config", "/tmp/x", "--porta", "8091", "--simulatore" }, 8091)]
|
||
[InlineData(new[] { "--porta", "0" }, 8080)]
|
||
[InlineData(new[] { "--porta", "65536" }, 8080)]
|
||
[InlineData(new[] { "--porta", "otto" }, 8080)]
|
||
[InlineData(new[] { "--porta" }, 8080)]
|
||
public void La_porta_dell_interfaccia_viene_solo_da_porta(string[] args, int expected)
|
||
{
|
||
Assert.Equal(expected, EnvConfig.HttpPortFrom(args));
|
||
Assert.Equal(expected, EnvConfig.Read(_ => null, args).HttpPort);
|
||
Assert.Equal(8080, EnvConfig.Read(k => k == "PORT" ? "9001" : null, Array.Empty<string>()).HttpPort);
|
||
}
|
||
}
|
||
|
||
/// <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);
|
||
Assert.Equal(StartupCheck.DatabaseUnreachableHint, item.Hint);
|
||
}
|
||
|
||
[Fact]
|
||
public void Con_DB_PORT_rimasta_e_DB_HOST_senza_porta_la_schermata_lo_dice()
|
||
{
|
||
var vars = new Dictionary<string, string?> { ["DB_HOST"] = "db", ["DB_PORT"] = "6543", ["DB_PASSWORD"] = "segreta" };
|
||
var env = EnvConfig.Read(k => vars.GetValueOrDefault(k), Array.Empty<string>());
|
||
|
||
var hint = StartupCheck.DatabaseHint(env);
|
||
Assert.StartsWith("DB_PORT non si legge più: scrivi la porta in DB_HOST (host:porta), senza porta vale 5432.", hint);
|
||
Assert.EndsWith(StartupCheck.DatabaseUnreachableHint, hint);
|
||
Assert.DoesNotContain("6543", hint);
|
||
|
||
// La voce «Database non raggiungibile» porta il suggerimento sulla schermata d'errore.
|
||
var report = new StartupReport { Attempt = 1 };
|
||
report.Items.Add(new CheckItem("database", false, "Database non raggiungibile", "db:5432", "Npgsql: connection refused", hint));
|
||
var html = Pages.ConfigError("1.0.0", report, 30);
|
||
Assert.Contains("DB_PORT non si legge pi", html); // la «ù» esce codificata
|
||
Assert.Contains("scrivi la porta in DB_HOST", html);
|
||
Assert.DoesNotContain("6543", html);
|
||
Assert.DoesNotContain("segreta", html);
|
||
|
||
// Con la porta già in DB_HOST, o senza DB_PORT, DB_PORT non c'entra: il suggerimento di sempre.
|
||
vars["DB_HOST"] = "db:6543";
|
||
Assert.Equal(StartupCheck.DatabaseUnreachableHint, StartupCheck.DatabaseHint(EnvConfig.Read(k => vars.GetValueOrDefault(k), Array.Empty<string>())));
|
||
vars["DB_HOST"] = "db";
|
||
vars.Remove("DB_PORT");
|
||
Assert.Equal(StartupCheck.DatabaseUnreachableHint, StartupCheck.DatabaseHint(EnvConfig.Read(k => vars.GetValueOrDefault(k), Array.Empty<string>())));
|
||
}
|
||
}
|
||
|
||
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);
|
||
}
|
||
}
|