Files
Mimante/tests/Mimante.Tests/RecorderTests.cs
T
Alby96andClaude Opus 5.5 9d89624434 Il programma si chiama Mimante, con le convenzioni di Febe (#23)
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>
2026-11-24 11:47:13 +01:00

172 lines
9.4 KiB
C#

using Mimante.Bidoo;
using Mimante.Data;
using Mimante.Engine;
using Mimante.Ml;
using Mimante.Products;
using Mimante.Settings;
using Mimante.Strategy;
using Xunit;
namespace Mimante.Tests;
/// <summary>Il registratore delle aste su PostgreSQL (AuctionRecorderTests del legacy, rifatti).</summary>
[Collection("Database")]
public class RecorderTests
{
private readonly DatabaseFixture _fx;
public RecorderTests(DatabaseFixture fx) => _fx = fx;
private static BidHistoryEntry Bid(int cents, string user, long unix, string type, bool mine = false) =>
new() { Price = cents / 100m, Username = user, Timestamp = unix, BidType = type, IsMyBid = mine };
[DbFact]
public async Task Una_storia_completa_da_risposte_esiti_e_previsione_realta()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var recorder = new AuctionRecorder(queue, db, () => new AppSettings(), () => "io");
await recorder.InitAsync();
var a = new AuctionInfo("900") { Name = "Buono Amazon 50 €", ProductKey = "buono amazon 50", Url = "u", BuyNowPrice = 50, Shipping = 1 };
var rec = (await recorder.PrepareAsync(a))!;
// Storico: 4,10 anna, 4,11 io, 4,12 bruno (risponde a me dopo 6 s), 4,13 io (l'ultima).
rec.ForeignBid(Bid(410, "anna", 1000, "Manuale"));
rec.ForeignBid(Bid(411, "io", 1004, "Manuale", mine: true));
rec.ForeignBid(Bid(412, "bruno", 1010, "Auto"));
rec.ForeignBid(Bid(412, "bruno", 1010, "Auto")); // doppione: non si riscrive
rec.ForeignBid(Bid(413, "io", 1016, "", mine: true));
rec.ForeignBid(Bid(413, "io", 1016, "Manuale", mine: true)); // il tipo arriva dopo: si aggiorna
rec.Reset(1, 4.12, "bruno");
var state = new AuctionState { Price = 4.10, Timer = 1.2 };
var d1 = recorder.RecordDecision(a, state, new DecisionRecord("punta", "BID", 0.02, 0.03, 1, 0.02, 0.1, 0.13, 50, "punto", "g5|r0", "logit", "v", "BID", 500, false,
new DecisionState { Ctx = new BidContext(9, 0.5, 2, 0.08, 12, DayOfWeek.Monday, 11, false, 0, 410, false, "buono amazon 50"), Price = 4.10 }));
rec.MyBid(4.10, 500, 480, 0.3, 60, 70, true, null, 1, 1406, 926, 480, d1, 0.02, "punta", manual: false);
var d2 = recorder.RecordDecision(a, new AuctionState { Price = 4.12 }, new DecisionRecord("punta", "BID", 0.03, null, 1, 0.03, 0.2, 0.13, 50, "punto", "g5|r0", "logit", "v", "BID", 500, false, new DecisionState()));
rec.MyBid(4.12, 500, 490, 0.2, 60, 70, true, null, 2, 1405, 925, 480, d2, 0.03, "punta", manual: false);
recorder.RecordDecision(a, new AuctionState { Price = 4.12 }, new DecisionRecord("ev-negativo", "NO-OP", 0.001, null, 1, 0.001, -0.1, 0.13, 50, "no", "k", "logit", "v", "NO-OP", 500, true, new DecisionState()));
recorder.RecordForecast(a, new ForecastResult(4.50, 3.00, 6.00, 40, 5, 0.1, 1, 0.5, "prova", 20, DateTime.UtcNow, 4.10), initial: true);
recorder.Close(a, new CloseSummary(DateTime.UtcNow, "vinta", "EndedWon", true, "io", 4.13, 50, 1, null, 0.13, 1, 2, 0.26,
3, 1, 1, 3, 4, 0.5, true, true, 12, DateTime.UtcNow.AddMinutes(-12), DateTime.UtcNow.AddMinutes(-12), 60, 80, 120, 500, 0,
500, false, 0, 2, 0, 0.3, "[]", "{}", "attiva", null));
Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20)));
Assert.Equal(0, queue.Failed);
Assert.Equal(4L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM bids WHERE auction_id = '900'"));
Assert.Equal("Manuale", await db.ScalarAsync<string>("SELECT bid_type FROM bids WHERE auction_id = '900' AND price_after = 4.13"));
Assert.Equal(1L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM resets WHERE auction_id = '900'"));
// La mia a 4,10 (prezzo dopo 4,11) è stata coperta da bruno a 4,12 dopo 6 s; quella a 4,12 è rimasta l'ultima.
var first = await db.QueryOneAsync("SELECT answered_by, answered_type, answered_after_s, unanswered FROM my_bids WHERE auction_id = '900' AND price = 4.10",
r => new { By = r.StrOrNull("answered_by"), Type = r.StrOrNull("answered_type"), After = r.DblOrNull("answered_after_s"), U = r.BoolOrNull("unanswered") });
Assert.Equal("bruno", first!.By);
Assert.Equal("Auto", first.Type);
Assert.Equal(6, first.After);
Assert.False(first.U);
Assert.True(await db.ScalarAsync<bool>("SELECT unanswered FROM my_bids WHERE auction_id = '900' AND price = 4.12"));
Assert.Equal("answered", await db.ScalarAsync<string>("SELECT outcome FROM bot_decisions WHERE decision_id = $1", d1));
Assert.Equal("won", await db.ScalarAsync<string>("SELECT outcome FROM bot_decisions WHERE decision_id = $1", d2));
Assert.Equal(1L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM bot_decisions WHERE auction_id = '900' AND shadow AND outcome = 'right_skip'"));
Assert.True(await db.ScalarAsync<bool>("SELECT bool_and(has_my_bid) FROM bot_decisions WHERE auction_id = '900'"));
var f = await db.QueryOneAsync("SELECT actual_close, error_close, in_interval FROM auction_forecasts WHERE auction_id = '900'",
r => new { Actual = r.Dbl("actual_close"), Err = r.Dbl("error_close"), In = r.Bool("in_interval") });
Assert.Equal(4.13, f!.Actual, 6);
Assert.Equal(4.13 - 4.50, f.Err, 6);
Assert.True(f.In);
Assert.Equal("vinta", await db.ScalarAsync<string>("SELECT outcome FROM auctions WHERE auction_id = '900'"));
Assert.Equal(1, await db.ScalarAsync<int>("SELECT win_count FROM bidders WHERE username = 'io'"));
Assert.Equal(2, await db.ScalarAsync<int>("SELECT n_bids FROM bidders WHERE username = 'io'"));
}
[DbFact]
public async Task Riaprendo_un_asta_gia_seguita_non_si_duplicano_le_puntate()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var a = new AuctionInfo("901") { Name = "X", ProductKey = "x" };
var first = new AuctionRecorder(queue, db, () => new AppSettings(), () => null);
(await first.PrepareAsync(a))!.ForeignBid(Bid(101, "anna", 1000, "Auto"));
await queue.FlushAsync(TimeSpan.FromSeconds(20));
var restarted = new AuctionRecorder(queue, db, () => new AppSettings(), () => null);
var rec = (await restarted.PrepareAsync(a))!;
rec.ForeignBid(Bid(101, "anna", 1000, "Auto"));
rec.ForeignBid(Bid(102, "bruno", 1005, "Auto"));
await queue.FlushAsync(TimeSpan.FromSeconds(20));
Assert.Equal(2L, await db.ScalarAsync<long>("SELECT COUNT(*) FROM bids WHERE auction_id = '901'"));
}
[DbFact]
public async Task Senza_registrazione_non_si_scrive_nulla()
{
await _fx.TruncateAsync();
var off = new AuctionRecorder(null, null, () => new AppSettings(), () => null);
Assert.Null(await off.PrepareAsync(new AuctionInfo("902")));
Assert.False(off.Enabled);
}
[DbFact]
public async Task Il_rischio_rilegge_la_contabilita_del_giorno()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var docs = new MemoryDocumentStore();
var risk = new RiskManager(docs, new DbRiskLedger(queue));
risk.NoteBidSpent("a", 0.20);
risk.NoteBidSpent("a", 0.20);
risk.NoteWin("a", 1.50, "vinta");
await queue.FlushAsync(TimeSpan.FromSeconds(20));
var reloaded = new RiskManager(docs, new DbRiskLedger(queue));
await reloaded.LoadAsync(db);
var n = reloaded.Snapshot();
Assert.Equal(0.40, n.TodaySpent, 2);
Assert.Equal(1.50, n.TodayGained, 2);
Assert.Equal(1.10, n.Cumulative, 2);
Assert.Equal(1.10, n.Peak, 2);
}
[DbFact]
public async Task Prodotti_e_statistiche_si_salvano_e_si_ricalcolano()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var store = new ProductStore(queue);
store.Upsert(new ProductRecord { ProductKey = "buono", DisplayName = "Buono", MarketValue = 45, Followed = true, MaxPrice = 6.5 });
store.MarkProposed("buono", "777");
await queue.FlushAsync(TimeSpan.FromSeconds(20));
var again = new ProductStore(queue);
await again.LoadAsync(db);
Assert.Equal(45, again.Find("buono")!.MarketValue);
Assert.True(again.IsHandled("777"));
Assert.Equal(45.0, await db.ScalarAsync<double>("SELECT market_price_est FROM items WHERE product_key = 'buono'"));
for (var i = 0; i < 6; i++)
await db.ExecuteAsync("INSERT INTO auctions(auction_id, product_key, name, outcome, final_price, end_time, winner_bids_paid, winner_bids_free, won_by_me, my_bids, my_bids_cost, buy_now_price) " +
"VALUES($1, 'buono', 'Buono', 'persa', $2, now(), 5, 20, $3, $4, $5, 50)", $"s{i}", 3.0 + i, i == 0, i == 0 ? 10 : 0, i == 0 ? 1.3 : 0);
var stats = (await ProductStatsRepository.RefreshAsync(db, queue, "buono", 1.0))!;
Assert.Equal(6, stats.Auctions);
Assert.Equal(1, stats.Won);
Assert.Equal(5.5, stats.AvgFinal, 6);
Assert.Equal(25, stats.AvgWinnerBids);
Assert.Equal(3.0 + 1.3 + 1.0, stats.AvgRealCostWon!.Value, 6);
await queue.FlushAsync(TimeSpan.FromSeconds(20));
Assert.True((await ProductStatsRepository.LoadAllAsync(db)).ContainsKey("buono"));
}
}