Files
Mimante/tests/Mimante.Tests/ServiceTests.cs
T
Alby96 2d74aed552 Telegram: via /halt, /riprendi con conferma, spesa del giorno nel riepilogo e avviso dell'errore ripetuto del motore (#47)
Il comando /halt era l'ultimo modo di mettere un HALT a mano, contro la regola «HALT solo
automatico» (ADR 0011): si toglie, e il freno a distanza resta /osserva. /riprendi da solo
non toglie più un blocco nato da stop-loss o drawdown: risponde con il motivo e chiede
«/riprendi si» (anche «sì», maiuscole indifferenti), come «Togli il blocco» chiede conferma
nell'interfaccia; un HALT manuale salvato in passato si legge e si toglie come prima. Il
riepilogo torna a dire spesa e saldo netto del giorno, che la specifica §6.7 chiede e che il
record portava già senza scriverli. Gli errori del motore restavano solo nei registri: ora
passano da EngineErrorWatch, una finestra scorrevole per asta (O(1) ammortizzato, lock breve
sulla sola asta, nessun disco né database sul percorso caldo), e N errori della stessa asta
in M minuti (5 in 10 di fabbrica, impostazioni nuove con validazione) danno un solo
messaggio Telegram, il successivo solo dopo una finestra intera senza errori. Infine la
sessione illeggibile all'avvio non dice più «si parte dal simulatore» sul sito vero, dove il
bot segue le aste senza puntare. Guida, come-funziona e una nota in fondo all'ADR 0011
seguono il codice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit ef372fe14aff6eafebeefe2e760e355de7ffc630)
2026-11-27 15:33:35 +01:00

719 lines
35 KiB
C#
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text;
using System.Text.Json;
using Mimante.Bidoo;
using Mimante.Config;
using Mimante.Data;
using Mimante.Logging;
using Mimante.Ml;
using Mimante.Net;
using Mimante.Session;
using Mimante.Settings;
using Mimante.Simulator;
using Mimante.Telegram;
using Mimante.Web;
using Xunit;
namespace Mimante.Tests;
public class SessionStoreTests
{
[Fact]
public void La_sessione_si_salva_cifrata_e_si_rilegge()
{
using var dir = new TempDir();
var store = new SessionStore(dir.Path);
store.Save(new BidooSession { Cookie = "__stattrb=abc; PHPSESSID=xyz", UserAgent = "UA", Username = "utente", Source = SessionStore.SourcePasted });
var raw = File.ReadAllText(store.FilePath);
Assert.DoesNotContain("abc", raw);
Assert.DoesNotContain("utente", raw);
Assert.Equal(32, File.ReadAllBytes(store.KeyPath).Length);
var (session, error) = new SessionStore(dir.Path).Load();
Assert.Null(error);
Assert.Equal("__stattrb=abc; PHPSESSID=xyz", session!.Cookie);
Assert.Equal("utente", session.Username);
Assert.Equal(SessionStore.SourcePasted, session.Source);
}
[Fact]
public void Senza_chiave_o_con_file_manomesso_non_si_legge()
{
using var dir = new TempDir();
var store = new SessionStore(dir.Path);
store.Save(new BidooSession { Cookie = "__stattrb=abc" });
File.Delete(store.KeyPath);
var (s1, e1) = store.Load();
Assert.Null(s1);
Assert.Contains("chiave", e1);
store.Save(new BidooSession { Cookie = "__stattrb=abc" });
var env = JsonDocument.Parse(File.ReadAllText(store.FilePath)).RootElement;
var data = Convert.FromBase64String(env.GetProperty("Data").GetString()!);
data[0] ^= 0xFF;
File.WriteAllText(store.FilePath, JsonSerializer.Serialize(new { V = 1, Nonce = env.GetProperty("Nonce").GetString(), Tag = env.GetProperty("Tag").GetString(), Data = Convert.ToBase64String(data) }));
var (s2, e2) = store.Load();
Assert.Null(s2);
Assert.Contains("non decifrabile", e2);
File.WriteAllText(store.FilePath, "{ non è json");
var (s3, e3) = store.Load();
Assert.Null(s3);
Assert.NotNull(e3);
store.Delete();
var (s4, e4) = store.Load();
Assert.Null(s4);
Assert.Null(e4);
}
[Fact]
public void Il_profilo_del_browser_della_1x_si_cancella_all_avvio()
{
using var dir = new TempDir();
var paths = new ConfigPaths(dir.Path);
Assert.False(paths.RemoveOldBrowserProfile());
Directory.CreateDirectory(Path.Combine(paths.OldBrowserProfile, "Default"));
File.WriteAllText(Path.Combine(paths.OldBrowserProfile, "Default", "Cookies"), "x");
Assert.True(paths.RemoveOldBrowserProfile());
Assert.False(Directory.Exists(paths.OldBrowserProfile));
paths.EnsureAll();
Assert.False(Directory.Exists(paths.OldBrowserProfile));
}
}
/// <summary>La sessione incollata (ADR 0017): ogni modo in cui Chrome la lascia copiare.</summary>
public class SessionPasteTests
{
private const string Ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36";
[Fact]
public void Copy_as_cURL_per_bash_con_i_cookie_in_b()
{
var text = $"""
curl 'https://it.bidoo.com/' \
-H 'accept: text/html,application/xhtml+xml' \
-H 'accept-language: it-IT,it;q=0.9' \
-b '__stattrb=AbC123%3D%3D; PHPSESSID=s3ss10n; _ga=GA1.2.3' \
-H 'priority: u=0, i' \
-H 'user-agent: {Ua}'
""";
var p = SessionPaste.Parse(text);
Assert.Null(p.Error);
Assert.Equal("__stattrb=AbC123%3D%3D; PHPSESSID=s3ss10n; _ga=GA1.2.3", p.Cookie);
Assert.Equal(Ua, p.UserAgent);
Assert.Equal("cURL", p.Format);
}
[Fact]
public void Copy_as_cURL_con_l_intestazione_cookie_e_le_virgolette_ansi()
{
var text = "curl 'https://it.bidoo.com/data.php' -H 'Cookie: __stattrb=x1; PHPSESSID=y2' -b $'nota=l\\'altra' -A 'UA di prova' --compressed";
var p = SessionPaste.Parse(text);
Assert.Equal("__stattrb=x1; PHPSESSID=y2; nota=l'altra", p.Cookie);
Assert.Equal("UA di prova", p.UserAgent);
}
[Fact]
public void Copy_as_cURL_per_cmd_con_gli_accenti_circonflessi()
{
var text = "curl ^\"https://it.bidoo.com/^\" ^\r\n" +
" -H ^\"accept: text/html^\" ^\r\n" +
" -b ^\"__stattrb=AbC123^%^3D; PHPSESSID=s3ss10n^\" ^\r\n" +
" -H ^\"user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)^\"";
var p = SessionPaste.Parse(text);
Assert.Null(p.Error);
Assert.Equal("__stattrb=AbC123%3D; PHPSESSID=s3ss10n", p.Cookie);
Assert.Equal("Mozilla/5.0 (Windows NT 10.0; Win64; x64)", p.UserAgent);
}
[Fact]
public void Copy_as_PowerShell()
{
var text = """
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$session.UserAgent = "Mozilla/5.0 (Windows NT 10.0)"
$session.Cookies.Add((New-Object System.Net.Cookie("__stattrb", "AbC123%3D%3D", "/", ".bidoo.com")))
$session.Cookies.Add((New-Object System.Net.Cookie("PHPSESSID", "s3ss10n", "/", "it.bidoo.com")))
Invoke-WebRequest -UseBasicParsing -Uri "https://it.bidoo.com/" `
-WebSession $session
""";
var p = SessionPaste.Parse(text);
Assert.Equal("__stattrb=AbC123%3D%3D; PHPSESSID=s3ss10n", p.Cookie);
Assert.Equal("Mozilla/5.0 (Windows NT 10.0)", p.UserAgent);
Assert.Equal("PowerShell", p.Format);
}
[Fact]
public void Le_intestazioni_della_richiesta_in_riga_o_con_il_valore_sotto_il_nome()
{
var raw = SessionPaste.Parse("GET / HTTP/1.1\r\nHost: it.bidoo.com\r\nCookie: __stattrb=AbC; PHPSESSID=s\r\nUser-Agent: Mozilla/5.0 X\r\n");
Assert.Equal("__stattrb=AbC; PHPSESSID=s", raw.Cookie);
Assert.Equal("Mozilla/5.0 X", raw.UserAgent);
var panel = SessionPaste.Parse(":authority\nit.bidoo.com\naccept-language\nit-IT,it;q=0.9\ncookie\n__stattrb=AbC; PHPSESSID=s\nuser-agent:\nMozilla/5.0 Y\n");
Assert.Equal("__stattrb=AbC; PHPSESSID=s", panel.Cookie);
Assert.Equal("Mozilla/5.0 Y", panel.UserAgent);
Assert.Equal("intestazioni", panel.Format);
}
[Fact]
public void La_riga_cookie_da_sola_con_o_senza_prefisso()
{
Assert.Equal("__stattrb=1; a=2", SessionPaste.Parse("Cookie: __stattrb=1; a=2\r\n").Cookie);
var line = SessionPaste.Parse("__stattrb=1; a=2");
Assert.Equal("__stattrb=1; a=2", line.Cookie);
Assert.Null(line.UserAgent);
Assert.Equal("riga Cookie", line.Format);
}
[Fact]
public void Le_righe_della_tabella_dei_cookie_e_il_solo_valore()
{
var table = SessionPaste.Parse("__stattrb\tAbC123\tit.bidoo.com\t/\t2027-01-01T00:00:00.000Z\t15\t✓\n" +
"PHPSESSID\ts3ss10n\tit.bidoo.com\t/\tSessione\t17\t✓");
Assert.Equal("__stattrb=AbC123; PHPSESSID=s3ss10n", table.Cookie);
Assert.Equal("__stattrb=AbC123%3D%3D", SessionPaste.Parse(" AbC123%3D%3D \n").Cookie);
Assert.Equal("__stattrb=QWxhZGRpbjpvcGVu==", SessionPaste.Parse("QWxhZGRpbjpvcGVu==").Cookie);
Assert.Equal("__sess=v", SessionPaste.Parse("v", "__sess").Cookie);
}
[Fact]
public void Senza_il_cookie_di_accesso_la_sessione_non_si_accetta()
{
Assert.Contains("__stattrb", SessionPaste.Parse("PHPSESSID=9").Error);
Assert.Contains("__stattrb", SessionPaste.Parse("__stattrb=; PHPSESSID=9").Error);
Assert.Contains("__stattrb", SessionPaste.Parse("curl 'https://it.bidoo.com/' -b 'PHPSESSID=9' -H 'user-agent: X'").Error);
Assert.NotNull(SessionPaste.Parse("curl 'https://it.bidoo.com/' -H 'accept: */*'").Error);
Assert.NotNull(SessionPaste.Parse("ciao, come stai?").Error);
Assert.NotNull(SessionPaste.Parse(" ").Error);
Assert.NotNull(SessionPaste.Parse(null).Error);
Assert.Null(SessionPaste.Parse("PHPSESSID=9").Cookie);
}
[Fact]
public void Le_parole_della_riga_di_comando()
{
Assert.Equal(new[] { "curl", "a b", "c\"d", "e'f", "g\nh", "ij" }, SessionPaste.ShellWords("curl 'a b' \"c\\\"d\" $'e\\'f' $'g\\nh' i\\\n\\j"));
}
}
public class TelegramFormatTests
{
[Fact]
public void Prima_riga_breve_poi_i_dettagli_senza_simboli()
{
var won = TelegramFormat.Won("Buono Amazon 50 €", 4.12, 9, 6.30, 50);
var lines = won.Split('\n');
Assert.StartsWith("Asta vinta: Buono Amazon 50", lines[0]);
Assert.Contains("4,12 €", won);
Assert.Contains("9 puntate tue", won);
Assert.Contains("confermare", won);
var lost = TelegramFormat.Lost("Dyson", 41.2, "gigi72", 3, "coperta dall'autopuntata");
Assert.Contains("vinta da gigi72", lost);
Assert.Contains("Perché: coperta", lost);
Assert.StartsWith("Sessione Bidoo scaduta", TelegramFormat.SessionExpired("utente", "pagina di login"));
Assert.StartsWith("HALT automatico", TelegramFormat.Halt("stop-loss", automatic: true));
}
[Fact]
public void Riprendere_senza_conferma_spiega_come_si_conferma()
{
var text = TelegramFormat.ResumeNeedsConfirmation("Stop-loss del giorno superato");
Assert.StartsWith("HALT ancora attivo", text);
Assert.Contains("Stop-loss del giorno superato", text);
Assert.Contains("/riprendi si", text);
}
[Fact]
public void L_avviso_degli_errori_del_motore_dice_asta_soglia_e_ultimo_errore()
{
var text = TelegramFormat.EngineErrors("Dyson V15", 5, 10, "Errore nel polling: timeout\r\nseconda riga");
var lines = text.Split('\n');
Assert.Equal("Errore ripetuto del motore: Dyson V15", lines[0]);
Assert.Contains("5 errori in 10 minuti", text);
// L'ultimo errore su una riga sola, senza a capo che rompano il messaggio.
Assert.Contains("L'ultimo: Errore nel polling: timeout seconda riga", text);
Assert.Contains("10 minuti senza errori", text);
}
[Fact]
public void Il_riepilogo_dice_utente_saldo_e_roi_e_si_tronca()
{
var text = TelegramFormat.SummaryText(new TelegramFormat.Summary(12, 4, 1407, 3.8, -3.8, -0.08, null, 71, false, false));
Assert.StartsWith("Mimante, riepilogo, nessun utente collegato", text);
Assert.Contains("Puntate residue: 1.407.", text);
// Solo il totale: la divisione fra a pagamento e gratuite non si dice.
Assert.DoesNotContain("gratis", text);
Assert.DoesNotContain("pagamento", text);
Assert.Contains("Osserva -0,08 €", text);
Assert.Contains("Attive n.d.", text);
// Spesa e saldo netto del giorno, in euro all'italiana e con il segno sul saldo.
Assert.Contains("\nSpesa oggi 3,80 €, saldo netto oggi -3,80 €.", text);
var positive = TelegramFormat.SummaryText(new TelegramFormat.Summary(1, 0, null, 1234.5, 46, null, null, null, true, false));
Assert.Contains("Spesa oggi 1234,50 €, saldo netto oggi +46,00 €.", positive);
var zero = TelegramFormat.SummaryText(new TelegramFormat.Summary(1, 0, null, 0, 0, null, null, null, true, false));
Assert.Contains("Spesa oggi 0,00 €, saldo netto oggi 0,00 €.", zero);
var halted = TelegramFormat.SummaryText(new TelegramFormat.Summary(1, 1, null, 0, 0, null, null, null, true, true));
Assert.StartsWith("Mimante, riepilogo, puntate ferme (HALT)", halted);
var longText = TelegramFormat.Message("titolo", new string('x', 5000));
Assert.True(longText.Length <= TelegramFormat.MaxLength);
}
}
public class WebSocketProtocolTests
{
[Fact]
public void Il_delta_porta_solo_i_campi_cambiati()
{
var sent = new Dictionary<string, object?> { ["id"] = "1", ["price"] = 4.12, ["lastBidder"] = "anna", ["isMe"] = false, ["ev"] = null };
Assert.Null(WebSocketHub.Delta("1", sent, new Dictionary<string, object?>(sent)));
var row = new Dictionary<string, object?>(sent) { ["price"] = 4.13, ["lastBidder"] = "utente_demo", ["isMe"] = true };
var d = WebSocketHub.Delta("1", sent, row)!;
Assert.Equal("auction.delta", d["t"]);
Assert.Equal("1", d["id"]);
Assert.Equal(4.13, d["price"]);
Assert.Equal(true, d["isMe"]);
Assert.False(d.ContainsKey("ev"));
// Un campo nuovo (null compreso) arriva anche se prima mancava.
var withNew = new Dictionary<string, object?>(sent) { ["forecastClose"] = null };
Assert.True(WebSocketHub.Delta("1", sent, withNew)!.ContainsKey("forecastClose"));
}
[Fact]
public void Eventi_e_stati_hanno_i_nomi_dell_interfaccia()
{
var e = WebSocketHub.EventMessage(new LogEntry(7, DateTimeOffset.UtcNow, LogLevel.Warning, "PUNTATA", "rifiutata", "85559716"));
Assert.Equal("event", e["t"]);
Assert.Equal("warn", e["level"]);
Assert.Equal("[PUNTATA] rifiutata", e["msg"]);
Assert.Equal("85559716", e["auctionId"]);
Assert.Equal("scaduta", Views.SessionState(SessionStatus.Expired));
Assert.Equal("simulatore", Views.SessionState(SessionStatus.Simulator));
Assert.Equal("ok", Views.SessionState(SessionStatus.Valid));
}
}
public class BidLaneTests
{
private sealed class FailingHandler : HttpMessageHandler
{
public int Calls;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
Interlocked.Increment(ref Calls);
throw new HttpRequestException("rete giù");
}
}
[Fact]
public async Task Se_la_corsia_cade_e_c_e_tempo_la_puntata_ritenta_una_volta_sul_pool()
{
var world = new SimWorld(seed: 5, populate: false);
await using var sim = await SimulatedBidoo.StartAsync(world);
var target = world.AddRunningAuction(seconds: 8, freq: 10);
var refs = sim.References();
using var transport = new BidooTransport(() => refs, 0);
var failing = new FailingHandler();
using var lane = new BidLane(transport, () => refs, failing, keepWarm: false);
var api = new BidooApi(transport, lane, () => refs) { Username = world.MyUsername };
var withTime = await api.PlaceBidAsync(target.Id, null, () => 5000, 100, CancellationToken.None);
Assert.True(withTime.Success);
Assert.True(withTime.UsedFallback);
var noTime = await api.PlaceBidAsync(target.Id, null, () => 50, 100, CancellationToken.None);
Assert.False(noTime.Success);
Assert.False(noTime.UsedFallback);
Assert.Equal(2, failing.Calls);
Assert.Single(world.MyBids, b => b.Accepted);
}
}
public class CsvExportPureTests
{
[Fact]
public void Punto_e_virgola_virgolette_e_a_capo_si_proteggono()
{
Assert.Equal("", CsvExport.Escape(null));
Assert.Equal("semplice", CsvExport.Escape("semplice"));
Assert.Equal("\"a;b\"", CsvExport.Escape("a;b"));
Assert.Equal("\"detto \"\"così\"\"\"", CsvExport.Escape("detto \"così\""));
Assert.Equal("due righe", CsvExport.Escape("due\nrighe"));
var sb = new StringBuilder();
CsvExport.Line(sb, new[] { "a", null, "c;d" });
Assert.Equal("a;;\"c;d\"\r\n", sb.ToString());
}
[Fact]
public void Il_campionamento_tiene_le_proporzioni_e_almeno_una_riga_per_gruppo()
{
var counts = new List<(string, long)> { ("osservata", 900), ("persa", 98), ("vinta", 2) };
var plan = SamplePlan.For(counts, 100);
Assert.True(plan.Sampled);
Assert.Equal(1000, plan.Total);
Assert.InRange(plan.Kept, 98, 103);
Assert.Equal(90, plan.Groups.Single(g => g.Key == "osservata").Quota);
Assert.Equal(10, plan.Groups.Single(g => g.Key == "persa").Quota);
Assert.Equal(1, plan.Groups.Single(g => g.Key == "vinta").Quota);
Assert.Contains("stratificato", plan.Note);
Assert.Contains("vinta: 1 su 2", plan.Note);
var all = SamplePlan.For(counts, 5000);
Assert.False(all.Sampled);
Assert.Null(all.Note);
Assert.Equal(1000, all.Kept);
}
[Theory]
[InlineData(900, 90)]
[InlineData(98, 10)]
[InlineData(7, 3)]
[InlineData(5, 5)]
[InlineData(1_000_003, 999)]
public void La_regola_di_sql_sceglie_esattamente_q_righe_ben_distribuite(long n, long q)
{
var kept = new List<long>();
for (long rn = 1; rn <= n; rn++)
if (SamplePlan.Keep(rn, n, q)) kept.Add(rn);
Assert.Equal(q, kept.Count);
Assert.Equal(1, kept[0]);
// Fra una riga tenuta e la successiva c'è al più un passo intero in più della media.
var step = (double)n / q;
for (var i = 1; i < kept.Count; i++) Assert.InRange(kept[i] - kept[i - 1], Math.Floor(step), Math.Ceiling(step));
}
[Fact]
public async Task Le_esportazioni_vanno_una_alla_volta_e_si_annullano()
{
var gate = new TaskCompletionSource();
var jobs = new ExportJobs(async (req, ct, progress) =>
{
progress.Report(new CsvExport.Progress("Scrivo le decisioni", 10, 100));
await gate.Task.WaitAsync(ct);
return new CsvExport.Result(true, "fatto", new[] { "a.csv", "a-legenda.txt" }, 100, false);
}, new AppLog(null), CancellationToken.None);
var req = new CsvExport.Request(CsvExport.ModelData, null, null, false, 5000, Worlds.Real);
Assert.Equal("idle", jobs.Current.State);
Assert.True(jobs.Start(req).Ok);
var (again, why) = jobs.Start(req);
Assert.False(again);
Assert.Contains("già un'esportazione in corso", why);
await WaitUntil(() => jobs.Current.Rows == 10);
Assert.Equal("running", jobs.Current.State);
Assert.Equal(100, jobs.Current.Total);
Assert.True(jobs.Cancel());
await jobs.Running.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal("cancelled", jobs.Current.State);
Assert.Empty(jobs.Current.Files);
Assert.False(jobs.Cancel());
Assert.True(jobs.Start(req).Ok);
gate.SetResult();
await jobs.Running.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal("done", jobs.Current.State);
Assert.Equal(new[] { "a.csv", "a-legenda.txt" }, jobs.Current.Files);
}
[Fact]
public async Task Un_errore_dell_esportazione_finisce_nello_stato_senza_far_cadere_nulla()
{
var jobs = new ExportJobs((_, _, _) => throw new IOException("Spazio libero insufficiente"), new AppLog(null), CancellationToken.None);
Assert.True(jobs.Start(new CsvExport.Request(CsvExport.AuctionHistory, null, null, false, 0, Worlds.Real)).Ok);
await jobs.Running.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal("failed", jobs.Current.State);
Assert.Contains("Spazio libero insufficiente", jobs.Current.Message);
}
[Fact]
public void Il_rapporto_in_streaming_dà_lo_stesso_intervallo_dell_elenco()
{
var rows = Enumerable.Range(0, 200).Select(i => new ShadowReport.Row(i % 3 == 0 ? "BID" : "NO-OP", null,
i % 7 == 0 ? "would_win" : "would_be_answered", 0.01, 1 + i * 0.01, 50, 0, 0.13, true, false)).ToList();
var once = ShadowReport.Compute(rows, 1.0, 7).Policies[0];
// Lo stesso calcolo a due passate, come faceva la versione con l'elenco delle puntate.
var perBid = rows.Where(r => r.Action == "BID")
.Select(r => ShadowReport.Unanswered(r.Outcome) ? r.Value - (r.Price + Theory.PriceIncrement) - 1.0 - r.Shipping - r.BidCost : -r.BidCost).ToList();
var m = perBid.Average();
var half = 1.96 * Math.Sqrt(perBid.Sum(x => (x - m) * (x - m)) / (perBid.Count - 1)) / Math.Sqrt(perBid.Count);
Assert.Equal(m - half, once.Ci95!.Value.Low, 9);
Assert.Equal(m + half, once.Ci95!.Value.High, 9);
}
private static async Task WaitUntil(Func<bool> condition)
{
var until = DateTime.UtcNow.AddSeconds(5);
while (!condition() && DateTime.UtcNow < until) await Task.Delay(10);
Assert.True(condition());
}
[Fact]
public void I_registri_vecchi_si_cancellano_per_data_nel_nome()
{
using var dir = new TempDir();
foreach (var n in new[] { "app-2026-01-01.log", "aste-2026-09-20.log", "app-2026-09-25.log", "altro.log" })
File.WriteAllText(Path.Combine(dir.Path, n), "x");
Assert.Equal(1, Maintenance.CleanLogs(dir.Path, 90, new DateTime(2026, 9, 26)));
Assert.False(File.Exists(Path.Combine(dir.Path, "app-2026-01-01.log")));
Assert.True(File.Exists(Path.Combine(dir.Path, "altro.log")));
Assert.Equal(0, Maintenance.CleanLogs(dir.Path, 0, new DateTime(2030, 1, 1)));
}
}
/// <summary>Il backup notturno copia ogni tabella non partizionata delle migrazioni, e solo quelle.</summary>
public partial class BackupTablesTests
{
[Fact]
public void Il_backup_notturno_copia_tutte_le_tabelle_non_partizionate()
{
var created = Migrations.Embedded()
.SelectMany(s => CreateTable().Matches(s.Sql).Select(m => m.Groups["name"].Value.ToLowerInvariant()))
.Append("schema_migrations")
.Except(Partitions.Tables)
.ToHashSet();
Assert.Contains("account_rewards", created);
Assert.Equal(created.Order(), Maintenance.BackupTables.Order());
Assert.Equal(Maintenance.BackupTables.Length, Maintenance.BackupTables.Distinct().Count());
Assert.Empty(Maintenance.BackupTables.Intersect(Partitions.Tables));
}
[System.Text.RegularExpressions.GeneratedRegex(@"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\(",
System.Text.RegularExpressions.RegexOptions.IgnoreCase)]
private static partial System.Text.RegularExpressions.Regex CreateTable();
}
[Collection("Database")]
public class DataRetentionTests(DatabaseFixture fx)
{
[DbFact]
public async Task Oltre_il_tetto_si_sacrifica_nell_ordine_giusto_e_mai_le_tabelle_protette()
{
await fx.TruncateAsync();
var db = fx.Db!;
foreach (var t in Partitions.Tables)
await db.ExecuteAsync($"CREATE TABLE IF NOT EXISTS {t}_2020_01 PARTITION OF {t} FOR VALUES FROM ('2020-01-01') TO ('2020-02-01')");
await db.ExecuteAsync("INSERT INTO auctions(auction_id, name, product_key) VALUES ('A', 'con mie', 'p'), ('B', 'senza mie', 'p')");
await db.ExecuteAsync("INSERT INTO my_bids(auction_id, t, price, success) VALUES ('A', 1, 1.00, true)");
const string old = "'2020-01-15T12:00:00Z'";
await db.ExecuteAsync($"INSERT INTO bids(auction_id, username, price_after, created_at) VALUES ('A','x',1.01,{old}), ('A','y',1.02,{old}), ('B','x',0.50,{old}), ('B','y',0.51,{old}), ('B','z',0.52,{old})");
await db.ExecuteAsync($"INSERT INTO resets(auction_id, t, created_at) VALUES ('B', 1, {old})");
await db.ExecuteAsync($"INSERT INTO bot_decisions(decision_id, auction_id, ts, has_my_bid, created_at) VALUES (1,'A',{old},true,{old}), (2,'B',{old},false,{old}), (3,'B',{old},false,{old})");
await db.ExecuteAsync("INSERT INTO bids(auction_id, username, price_after) VALUES ('B', 'oggi', 0.60)");
const long gib = 1L << 30;
var sizes = new Queue<long>(new[] { 2 * gib, 19 * gib / 10, 18 * gib / 10, 17 * gib / 10, 16 * gib / 10, 15 * gib / 10, 14 * gib / 10 });
var retention = new DataRetention(db, new AppLog(null), () => Task.FromResult(sizes.Count > 1 ? sizes.Dequeue() : sizes.Peek()));
var result = await retention.RunAsync(1, DateTime.UtcNow, CancellationToken.None);
Assert.Equal(5, result.Actions);
Assert.Contains("decisioni delle aste senza mie puntate", result.Lines[0]);
Assert.Contains("partizione di reset", result.Lines[1]);
Assert.Contains("puntate delle aste senza mie puntate", result.Lines[2]);
Assert.Contains("partizione di puntate", result.Lines[3]);
Assert.Contains("partizione di decisioni", result.Lines[4]);
foreach (var t in Partitions.Tables)
Assert.DoesNotContain(await Partitions.ListAsync(db, t), p => p.Name == $"{t}_2020_01");
Assert.Equal(2L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM auctions"));
Assert.Equal(1L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM my_bids"));
Assert.Equal(1L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM bids WHERE username = 'oggi'"));
}
[DbFact]
public async Task Sotto_il_tetto_non_si_tocca_nulla()
{
var retention = new DataRetention(fx.Db!, new AppLog(null), () => Task.FromResult(100L));
var r = await retention.RunAsync(50, DateTime.UtcNow, CancellationToken.None);
Assert.Equal(0, r.Actions);
Assert.True(r.UsedFraction < 0.01);
}
}
[Collection("Database")]
public class CsvExportTests(DatabaseFixture fx)
{
[DbFact]
public async Task I_due_csv_hanno_bom_colonne_complete_virgola_decimale_e_legenda()
{
await fx.TruncateAsync();
var db = fx.Db!;
using var dir = new TempDir();
var paths = new ConfigPaths(dir.Path);
await using var queue = new WriteQueue(db.Writer, new AppLog(null));
await db.ExecuteAsync(
"INSERT INTO auctions(auction_id, name, product_key, type, outcome, final_price, end_time, won_by_me, my_bids, my_bids_cost, winner_user, buy_now_price, shipping, loss_reason) " +
"VALUES ('E1', 'Buono Amazon 50 €', 'buono-amazon-50', 'normal', 'lost', 3.21, now() - interval '1 hour', false, 2, 0.26, 'anna', 50, 0, 'coperta dall''autopuntata')");
var ctx = new BidContext(9.4, 0.8, 3, 0.06, 20, DayOfWeek.Friday, 19, false, 2, 320, false, "buono-amazon-50", 3, 0.7);
var state = JsonSerializer.Serialize(new DecisionState { Ctx = ctx, Price = 3.20, Balance = 1407, Paid = 927, Free = 480 });
await db.ExecuteAsync(
"INSERT INTO bot_decisions(decision_id, auction_id, ts, price, timer, kind, action, p_model, p_win, ev, bid_cost, value, reason_detail, state, shadow, outcome, champion) " +
"VALUES (1, 'E1', now() - interval '2 hours', 3.20, 0.9, 'ev-negativo', 'NO-OP', 0.012, 0.012, -0.05, 0.13, 50, 'P bassa, serve 0,3%', $1, true, 'right_skip', 'logit')",
new Jsonb(state));
await db.ExecuteAsync("INSERT INTO bids(auction_id, username, price_after, bid_type, server_ts) VALUES ('E1', 'anna', 3.20, 'Auto', 100), ('E1', 'bob', 3.21, 'Manuale', 104)");
var export = new CsvExport(db, queue, paths, () => new AppSettings(), _ => null);
var today = AppInfo.LocalNow.Date;
var model = await export.RunAsync(new CsvExport.Request(CsvExport.ModelData, today.AddDays(-1), today, false, 5000, Worlds.Real), CancellationToken.None);
Assert.True(model.Ok, model.Message);
Assert.Equal(1, model.Rows);
var bytes = File.ReadAllBytes(Path.Combine(paths.Exports, model.Files[0]));
Assert.Equal(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3]);
var lines = Encoding.UTF8.GetString(bytes[3..]).Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
var header = lines[0].Split(';');
Assert.Equal(17 + BidFeatures.Size + 32, header.Length);
Assert.Equal("id_decisione", header[0]);
Assert.Equal("motivazione", header[^5]);
Assert.Equal(new[] { "ripetizioni", "ultimo_prezzo", "parere_modello", "nota_fuoco" }, header[^4..]);
var row = lines[1].Split(';');
Assert.Equal(header.Length, row.Length);
Assert.Equal("3,2", row[Array.IndexOf(header, "prezzo")]);
Assert.Equal("no", row[Array.IndexOf(header, "verdetto")]);
Assert.Equal("No", row[Array.IndexOf(header, "tipo_decisione")]);
Assert.Equal("bob", row[Array.IndexOf(header, "risposto_da")]);
Assert.Equal("manuale", row[Array.IndexOf(header, "risposto_tipo")]);
Assert.Equal("4", row[Array.IndexOf(header, "risposto_dopo_s")]);
Assert.Equal("1407", row[Array.IndexOf(header, "puntate_residue")]);
Assert.Equal("1", row[Array.IndexOf(header, "ripetizioni")]);
Assert.Contains(row[17..(17 + BidFeatures.Size)], v => v == "1");
Assert.True(File.Exists(Path.Combine(paths.Exports, model.Files[1])));
Assert.Contains("Righe trovate: 1", File.ReadAllText(Path.Combine(paths.Exports, model.Files[1])));
var history = await export.RunAsync(new CsvExport.Request(CsvExport.AuctionHistory, today.AddDays(-1), today, true, 5000, Worlds.Real), CancellationToken.None);
Assert.Equal(1, history.Rows);
var hLines = File.ReadAllText(Path.Combine(paths.Exports, history.Files[0]), Encoding.UTF8).Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
var hHeader = hLines[0].TrimStart('').Split(';');
var hRow = hLines[1].Split(';');
Assert.Equal(hHeader.Length, hRow.Length);
Assert.Equal("3,21", hRow[Array.IndexOf(hHeader, "prezzo_finale")]);
Assert.Contains("Persa a 3,21", hRow[^1]);
Assert.Contains("coperta", hRow[Array.IndexOf(hHeader, "motivo_perdita")]);
}
/// <summary>10.000 decisioni sintetiche su un'asta: 1.000 «missed» e 9.000 «right_skip».</summary>
private static async Task SeedDecisionsAsync(Db db)
{
await db.ExecuteAsync(
"INSERT INTO auctions(auction_id, name, product_key, type, outcome, final_price, end_time, my_bids) " +
"VALUES ('S1', 'Sintetica', 'sintetica', 'normal', 'lost', 5.00, now() - interval '1 hour', 0)");
await db.ExecuteAsync(
"INSERT INTO bot_decisions(decision_id, auction_id, ts, price, action, kind, outcome, shadow, reason_detail) " +
"SELECT g, 'S1', now() - interval '4 hours' + g * interval '1 second', 1.00 + g * 0.01, 'NO-OP', 'ev-negativo', " +
" CASE WHEN g % 10 = 0 THEN 'missed' ELSE 'right_skip' END, true, 'valore atteso negativo, servirebbe una probabilità più alta' " +
"FROM generate_series(1, 10000) g");
}
[DbFact]
public async Task Il_campione_si_sceglie_in_sql_con_le_proporzioni_per_esito()
{
await fx.TruncateAsync();
var db = fx.Db!;
using var dir = new TempDir();
var paths = new ConfigPaths(dir.Path);
await using var queue = new WriteQueue(db.Writer, new AppLog(null));
await SeedDecisionsAsync(db);
var export = new CsvExport(db, queue, paths, () => new AppSettings(), _ => null);
var today = AppInfo.LocalNow.Date;
var steps = new List<CsvExport.Progress>();
var r = await export.RunAsync(new CsvExport.Request(CsvExport.ModelData, today.AddDays(-1), today, false, 100, Worlds.Real),
CancellationToken.None, new SyncProgress(steps));
Assert.True(r.Ok, r.Message);
Assert.True(r.Sampled);
Assert.Equal(100, r.Rows);
var lines = File.ReadAllLines(Path.Combine(paths.Exports, r.Files[0]), Encoding.UTF8);
var header = lines[0].TrimStart('').Split(';');
var unanswered = Array.IndexOf(header, "esito_senza_risposta");
Assert.Equal(101, lines.Length);
Assert.Equal(10, lines.Skip(1).Count(l => l.Split(';')[unanswered] == "si"));
// In ordine di tempo, e distribuite su tutto il periodo (non le prime 100).
var ids = lines.Skip(1).Select(l => long.Parse(l.Split(';')[0])).ToList();
Assert.Equal(ids.OrderBy(x => x), ids);
Assert.True(ids[^1] > 9000);
Assert.Contains("missed: 10 su 1000", File.ReadAllText(Path.Combine(paths.Exports, r.Files[1])));
Assert.Contains(steps, s => s.Phase == "Conto le decisioni");
Assert.Empty(Directory.GetFiles(paths.Exports, "*.tmp"));
}
[DbFact]
public async Task Un_file_grande_si_consegna_in_zip()
{
await fx.TruncateAsync();
var db = fx.Db!;
using var dir = new TempDir();
var paths = new ConfigPaths(dir.Path);
await using var queue = new WriteQueue(db.Writer, new AppLog(null));
await SeedDecisionsAsync(db);
var export = new CsvExport(db, queue, paths, () => new AppSettings { ExportZipAboveMb = 1 }, _ => null);
var today = AppInfo.LocalNow.Date;
var r = await export.RunAsync(new CsvExport.Request(CsvExport.ModelData, today.AddDays(-1), today, false, 0, Worlds.Real), CancellationToken.None);
Assert.True(r.Ok, r.Message);
Assert.Equal(10_000, r.Rows);
Assert.EndsWith(".csv.zip", r.Files[0]);
Assert.False(File.Exists(Path.Combine(paths.Exports, r.Files[0][..^4])));
using var zip = System.IO.Compression.ZipFile.OpenRead(Path.Combine(paths.Exports, r.Files[0]));
var entry = Assert.Single(zip.Entries);
using var reader = new StreamReader(entry.Open(), Encoding.UTF8);
var count = 0;
while (reader.ReadLine() != null) count++;
Assert.Equal(10_001, count);
}
[DbFact]
public async Task Annullare_a_metà_o_restare_senza_spazio_non_lascia_file()
{
await fx.TruncateAsync();
var db = fx.Db!;
using var dir = new TempDir();
var paths = new ConfigPaths(dir.Path);
await using var queue = new WriteQueue(db.Writer, new AppLog(null));
await SeedDecisionsAsync(db);
var today = AppInfo.LocalNow.Date;
var req = new CsvExport.Request(CsvExport.ModelData, today.AddDays(-1), today, false, 0, Worlds.Real);
// Annullata quando ha scritto le prime 5.000 righe (il primo avanzamento con righe).
using var cts = new CancellationTokenSource();
var export = new CsvExport(db, queue, paths, () => new AppSettings(), _ => null);
var started = DateTime.UtcNow;
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
export.RunAsync(req, cts.Token, new SyncProgress(null, p => { if (p.Rows > 0) cts.Cancel(); })));
Assert.True(DateTime.UtcNow - started < TimeSpan.FromSeconds(30));
Assert.Empty(Directory.GetFiles(paths.Exports));
// Lo spazio finisce durante la scrittura: nessun .tmp, nessun csv.
long free = 10L << 30;
var full = new CsvExport(db, queue, paths, () => new AppSettings(), _ => null, _ => Interlocked.Exchange(ref free, 0));
var e = await Assert.ThrowsAsync<IOException>(() => full.RunAsync(req, CancellationToken.None));
Assert.Contains("Spazio libero insufficiente", e.Message);
Assert.Empty(Directory.GetFiles(paths.Exports));
}
/// <summary>Un IProgress che chiama subito, sullo stesso thread (Progress&lt;T&gt; passa dal pool).</summary>
private sealed class SyncProgress(List<CsvExport.Progress>? into, Action<CsvExport.Progress>? on = null) : IProgress<CsvExport.Progress>
{
public void Report(CsvExport.Progress value)
{
into?.Add(value);
on?.Invoke(value);
}
}
}