Files
Mimante/tests/Mimante.Tests/ServiceTests.cs
T
Alby96andClaude Opus 5.5 b0901c0248
verifica / controlli (push) Successful in 1m1s
verifica / prove (push) Successful in 3m8s
verifica / immagine (push) Failing after 8m11s
Esportazioni a memoria costante, di fondo e annullabili (#25)
Cadevano con molti dati: ogni riga del periodo finiva in un dizionario in
memoria prima del campionamento, il file intero in una stringa, le letture
avevano il limite di 15 s delle pagine e non si potevano annullare, e la
puntata di risposta si cercava con ABS(price_after - x) < 0,005, che non usa
l'indice. Ora:

- CsvExport apre una sua connessione in sola lettura (REPEATABLE READ, tempo
  massimo ExportTimeoutMinutes), conta le righe per esito e chiede a
  PostgreSQL solo quelle scelte da SamplePlan (quota proporzionale, almeno
  una per gruppo, righe equidistanti nel tempo, stessa regola in SQL e in C#);
  le scrive una alla volta su nome.tmp, rinominato alla fine. Annullare,
  sforare il tempo o restare sotto ExportMinFreeMb cancella il .tmp e ferma
  la lettura sul server. Oltre ExportZipAboveMb il file esce in .zip.
- Puntata di risposta con l'uguaglianza su price_after (numeric(10,2)) e una
  finestra su created_at: indice (auction_id, price_after) in ogni partizione,
  anche in AuctionRecorder alla chiusura. Storico con le colonne che servono e
  un solo passaggio sulle decisioni per i tre conteggi. Indice nuovo su
  my_bids(decision_id) (0003, tabella piccola).
- ExportJobs: un'esportazione alla volta, di fondo, comandi export.start e
  export.cancel; lo stato arriva come blocco «export» del WebSocket, così
  sopravvive a una ricarica. exports.js è la finestra unica (fase, righe,
  Annulla, file pronti) per Storico, Apprendimento e Prodotti, e si riapre da
  sola quando un'esportazione finisce a finestra chiusa.
- Apprendimento: i tre rapporti di confronto con una sola lettura in
  streaming invece di tre caricamenti interi; ShadowReport accumula media e
  varianza in corsa (stesso intervallo al 95%).

Verifica: build con avvisi come errori, 306 prove verdi; le nuove prove su
PostgreSQL (campione in SQL, zip, annullamento e spazio senza file residui)
girano nella CI, qui Docker non parte. Le interrogazioni nuove sono state
pianificate con EXPLAIN sul database vero in sola lettura: nessuna scansione
intera di bids. Non fatto: le schermate dell'interfaccia con il bot in
locale (manca un PostgreSQL); da rifare prima della chiusura. La pausa durante
le puntate vere prevista dal piano non serve: il percorso caldo non tocca
il database né il disco delle esportazioni.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:24:14 +01:00

643 lines
31 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 System.Threading.Channels;
using Mimante.Bidoo;
using Mimante.Config;
using Mimante.Data;
using Mimante.Logging;
using Mimante.Ml;
using Mimante.Net;
using Mimante.Session;
using Mimante.Session.Cdp;
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 I_cookie_incollati_si_normalizzano_e_serve_quello_di_sessione()
{
Assert.Equal("__stattrb=1; a=2", SessionStore.NormalizePastedCookie("Cookie: __stattrb=1; a=2\r\n").Cookie);
Assert.Contains("__stattrb", SessionStore.NormalizePastedCookie("PHPSESSID=9").Error);
Assert.NotNull(SessionStore.NormalizePastedCookie(" ").Error);
}
}
public class CdpClientTests
{
private sealed class FakeTransport : ICdpTransport
{
private readonly Channel<string> _incoming = Channel.CreateUnbounded<string>();
public List<JsonElement> Sent { get; } = new();
public Func<JsonElement, string?>? Reply { get; set; }
public Task SendAsync(string json, CancellationToken ct)
{
var msg = JsonDocument.Parse(json).RootElement.Clone();
lock (Sent) Sent.Add(msg);
if (Reply?.Invoke(msg) is { } answer) Push(answer);
return Task.CompletedTask;
}
public async Task<string?> ReceiveAsync(CancellationToken ct)
{
try { return await _incoming.Reader.ReadAsync(ct); }
catch (ChannelClosedException) { return null; }
}
public void Push(string json) => _incoming.Writer.TryWrite(json);
public void Close() => _incoming.Writer.TryComplete();
public ValueTask DisposeAsync() { Close(); return ValueTask.CompletedTask; }
}
[Fact]
public async Task Le_risposte_si_abbinano_per_id_e_gli_errori_diventano_eccezioni()
{
var t = new FakeTransport
{
Reply = m => m.GetProperty("method").GetString() == "Boom"
? JsonSerializer.Serialize(new { id = m.GetProperty("id").GetInt32(), error = new { code = -32000, message = "non va" } })
: JsonSerializer.Serialize(new { id = m.GetProperty("id").GetInt32(), result = new { echo = m.GetProperty("method").GetString() } })
};
await using var cdp = new CdpClient(t);
var a = cdp.SendAsync("Page.enable", sessionId: "S1");
var b = cdp.SendAsync("Target.createTarget", new { url = "about:blank" });
Assert.Equal("Page.enable", (await a).GetProperty("echo").GetString());
Assert.Equal("Target.createTarget", (await b).GetProperty("echo").GetString());
var sent = t.Sent.First(x => x.GetProperty("method").GetString() == "Page.enable");
Assert.Equal("S1", sent.GetProperty("sessionId").GetString());
Assert.Equal("about:blank", t.Sent.First(x => x.GetProperty("method").GetString() == "Target.createTarget").GetProperty("params").GetProperty("url").GetString());
var ex = await Assert.ThrowsAsync<CdpException>(() => cdp.SendAsync("Boom"));
Assert.Contains("non va", ex.Message);
}
[Fact]
public async Task Gli_eventi_portano_la_sessione_e_la_chiusura_sblocca_le_attese()
{
var t = new FakeTransport();
await using var cdp = new CdpClient(t);
var got = new TaskCompletionSource<(string, string?, string?)>();
cdp.Event += (m, p, s) => got.TrySetResult((m, s, p.GetProperty("url").GetString()));
t.Push("""{"method":"Page.frameNavigated","params":{"url":"https://it.bidoo.com/"},"sessionId":"S9"}""");
var (method, session, url) = await got.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal("Page.frameNavigated", method);
Assert.Equal("S9", session);
Assert.Equal("https://it.bidoo.com/", url);
var pending = cdp.SendAsync("Network.getCookies");
t.Close();
await Assert.ThrowsAsync<CdpException>(() => pending);
Assert.True(cdp.IsClosed);
}
[Fact]
public void Il_login_si_riconosce_anche_come_finestra_sulla_home()
{
var refs = BidooReferences.Default;
Assert.True(AssistedLogin.IsLoginUrl("https://it.bidoo.com/login.php", refs));
Assert.True(AssistedLogin.IsLoginUrl("https://it.bidoo.com/?login=true&redirect=index.php", refs));
Assert.True(AssistedLogin.IsLoginUrl("", refs));
Assert.False(AssistedLogin.IsLoginUrl("https://it.bidoo.com/index.php", refs));
}
[Fact]
public void DevToolsActivePort_da_l_indirizzo_del_browser()
{
using var dir = new TempDir();
var file = Path.Combine(dir.Path, "DevToolsActivePort");
File.WriteAllText(file, "41233\n/devtools/browser/abc-123\n");
Assert.Equal("ws://127.0.0.1:41233/devtools/browser/abc-123", ChromiumProcess.TryReadPort(file)!.ToString());
File.WriteAllText(file, "x\n");
Assert.Null(ChromiumProcess.TryReadPort(file));
Assert.Contains("--headless=new", ChromiumProcess.Arguments("/config/browser"));
Assert.Contains("--user-data-dir=/config/browser", ChromiumProcess.Arguments("/config/browser"));
}
}
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 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);
// Guadagno e perdita del giorno non si dicono più.
Assert.DoesNotContain("Oggi", text);
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)));
}
}
[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 + 28, header.Length);
Assert.Equal("id_decisione", header[0]);
Assert.Equal("motivazione", header[^1]);
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.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);
}
}
}