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>
446 lines
21 KiB
C#
446 lines
21 KiB
C#
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 rows = Enumerable.Range(0, 1000).Select(i => i < 900 ? "osservata" : i < 998 ? "persa" : "vinta").ToList();
|
||
var (kept, sampled, note) = CsvExport.Stratify(rows, 100, r => r);
|
||
Assert.True(sampled);
|
||
Assert.InRange(kept.Count, 98, 103);
|
||
Assert.InRange(kept.Count(r => r == "osservata"), 88, 92);
|
||
Assert.InRange(kept.Count(r => r == "persa"), 9, 11);
|
||
Assert.Equal(1, kept.Count(r => r == "vinta"));
|
||
Assert.Contains("stratificato", note);
|
||
|
||
var (all, s2, n2) = CsvExport.Stratify(rows, 5000, r => r);
|
||
Assert.False(s2);
|
||
Assert.Null(n2);
|
||
Assert.Equal(1000, all.Count);
|
||
}
|
||
|
||
[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")]);
|
||
}
|
||
}
|