Repository alla radice: via la cartella Mimante/ (#22)
Il servizio stava in Mimante/ con, alla radice, il README e il .gitignore della vecchia app WPF. Come negli altri progetti (Febe), soluzione, sorgenti, documenti e Docker stanno ora alla radice. Solo spostamenti con git mv, così la storia di ogni file si segue con --follow; nessun contenuto cambia. Tolti: il README della app WPF (quello del bot prende il suo posto), Modifiche.txt (vuoto) e i due flussi di .gitea/workflows, che non sono mai partiti e pubblicavano la porta 5432 sul Docker dove gira il PostgreSQL vero: li sostituisce la CI nuova. Fino ad allora nessun flusso parte. .gitignore unico, preso da Febe, con le voci del bot più /dati/ (i dati scaricati per l'analisi) e .claude/worktrees/. Build e 288 test verdi dalla radice (14 sul database saltati senza TEST_DB_HOST). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f70a49a930
commit
650ccea844
242 files changed
+206
-985
No files matched your search
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
<RootNamespace>BidooBidBot.Tests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\BidooBidBot\BidooBidBot.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Risposte registrate dal sito vero: i parser si provano su quelle. -->
|
||||
<None Include="Fixtures\**\*" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,123 @@
|
||||
using System.Text.Json;
|
||||
using BidooBidBot.Data;
|
||||
using BidooBidBot.Settings;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>Migrazioni, partizioni, coda di scrittura, documenti e impostazioni su PostgreSQL 18.</summary>
|
||||
[Collection("Database")]
|
||||
public class DatabaseTests
|
||||
{
|
||||
private readonly DatabaseFixture _fx;
|
||||
|
||||
public DatabaseTests(DatabaseFixture fx) => _fx = fx;
|
||||
|
||||
[DbFact]
|
||||
public async Task Le_migrazioni_sono_applicate_una_volta_sola()
|
||||
{
|
||||
var again = await Migrations.ApplyAsync(_fx.Db!.Writer);
|
||||
Assert.Empty(again);
|
||||
Assert.True(await Migrations.CurrentVersionAsync(_fx.Db) >= 1);
|
||||
|
||||
// Nessuna delle tabelle che la specifica esclude.
|
||||
foreach (var t in new[] { "polls", "auction_log", "network_metrics", "app_sessions", "maintenance_log" })
|
||||
Assert.False(await _fx.Db.ScalarAsync<bool>("SELECT to_regclass($1) IS NOT NULL", t));
|
||||
}
|
||||
|
||||
[DbFact]
|
||||
public async Task Le_partizioni_del_mese_e_del_successivo_esistono()
|
||||
{
|
||||
var created = await Partitions.EnsureAsync(_fx.Db!, new DateTime(2031, 12, 5));
|
||||
Assert.Equal(6, created); // dicembre 2031 e gennaio 2032, per tre tabelle
|
||||
Assert.Equal(0, await Partitions.EnsureAsync(_fx.Db!, new DateTime(2031, 12, 20)));
|
||||
|
||||
var list = await Partitions.ListAsync(_fx.Db!, "bids");
|
||||
Assert.Contains(list, p => p.Name == "bids_2032_01" && p.Month == new DateTime(2032, 1, 1));
|
||||
}
|
||||
|
||||
[DbFact]
|
||||
public async Task La_coda_scrive_a_lotti_e_svuota_allo_spegnimento()
|
||||
{
|
||||
await _fx.TruncateAsync();
|
||||
await using (var queue = new WriteQueue(_fx.Db!.Writer) { BatchRows = 50 })
|
||||
{
|
||||
for (var i = 0; i < 230; i++)
|
||||
queue.EnqueueBid("INSERT INTO bids(auction_id, username, price_after, bid_type) VALUES($1, $2, $3, $4)",
|
||||
"a1", $"u{i % 7}", 0.01 * (i + 1), "Auto");
|
||||
|
||||
Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20)));
|
||||
Assert.Equal(230, queue.Written);
|
||||
}
|
||||
|
||||
Assert.Equal(230L, await _fx.Db.ScalarAsync<long>("SELECT COUNT(*) FROM bids WHERE auction_id = 'a1'"));
|
||||
}
|
||||
|
||||
[DbFact]
|
||||
public async Task Un_istruzione_sbagliata_non_blocca_le_altre()
|
||||
{
|
||||
await _fx.TruncateAsync();
|
||||
await using var queue = new WriteQueue(_fx.Db!.Writer);
|
||||
queue.Enqueue("INSERT INTO risk_ledger(ts, kind, amount_euro) VALUES(now(), 'bid', -0.2)");
|
||||
queue.Enqueue("INSERT INTO tabella_che_non_esiste(x) VALUES(1)");
|
||||
queue.Enqueue("INSERT INTO risk_ledger(ts, kind, amount_euro) VALUES(now(), 'bid', -0.2)");
|
||||
Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20)));
|
||||
|
||||
Assert.Equal(1, queue.Failed);
|
||||
Assert.Equal(2L, await _fx.Db.ScalarAsync<long>("SELECT COUNT(*) FROM risk_ledger"));
|
||||
}
|
||||
|
||||
[DbFact]
|
||||
public async Task I_documenti_si_rileggono_dopo_il_riavvio()
|
||||
{
|
||||
await _fx.TruncateAsync();
|
||||
await using (var queue = new WriteQueue(_fx.Db!.Writer))
|
||||
{
|
||||
var docs = new DocumentStore(queue);
|
||||
docs.Set("ml/prova", """{"a":1}""");
|
||||
docs.Set("ml/altro", """{"b":2}""");
|
||||
docs.Set("risk/halt", """{"reason":"x"}""");
|
||||
docs.DeletePrefix("ml/");
|
||||
docs.Set("ml/nuovo", """{"c":3}""");
|
||||
await queue.FlushAsync(TimeSpan.FromSeconds(20));
|
||||
}
|
||||
|
||||
await using var q2 = new WriteQueue(_fx.Db.Writer);
|
||||
var reloaded = new DocumentStore(q2);
|
||||
await reloaded.LoadAsync(_fx.Db);
|
||||
Assert.Null(reloaded.Get("ml/prova"));
|
||||
Assert.NotNull(reloaded.Get("ml/nuovo"));
|
||||
Assert.Contains("reason", reloaded.Get("risk/halt"));
|
||||
}
|
||||
|
||||
[DbFact]
|
||||
public async Task Le_impostazioni_nascono_di_fabbrica_e_sopravvivono_al_riavvio()
|
||||
{
|
||||
await _fx.TruncateAsync();
|
||||
await using var queue = new WriteQueue(_fx.Db!.Writer);
|
||||
var store = new SettingsStore(queue, null);
|
||||
await store.LoadAsync(_fx.Db);
|
||||
Assert.Equal(300, store.Current.LearningMinAuctions);
|
||||
|
||||
var patch = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>("""{"DataCapGb": 20}""")!;
|
||||
Assert.True((await store.SaveAsync(patch)).Ok);
|
||||
|
||||
var again = new SettingsStore(queue, null);
|
||||
await again.LoadAsync(_fx.Db);
|
||||
Assert.Equal(20, again.Current.DataCapGb);
|
||||
}
|
||||
}
|
||||
|
||||
public class WriteQueueCapacityTests
|
||||
{
|
||||
[Fact]
|
||||
public void A_coda_piena_si_scartano_prima_le_puntate_osservate()
|
||||
{
|
||||
var queue = new WriteQueue(null) { Capacity = 10 };
|
||||
for (var i = 0; i < 8; i++) queue.EnqueueBid("INSERT bid", i);
|
||||
for (var i = 0; i < 5; i++) queue.Enqueue("INSERT altro", i);
|
||||
|
||||
Assert.Equal(10, queue.Pending);
|
||||
Assert.Equal(3, queue.Dropped);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
using System.Diagnostics;
|
||||
using BidooBidBot.Bidoo;
|
||||
using BidooBidBot.Engine;
|
||||
using BidooBidBot.Logging;
|
||||
using BidooBidBot.Net;
|
||||
using BidooBidBot.Settings;
|
||||
using BidooBidBot.Simulator;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>L'orologio del server: l'errore residuo resta piccolo e non cresce (portati dal legacy).</summary>
|
||||
public class ServerClockTests
|
||||
{
|
||||
private static readonly long Freq = Stopwatch.Frequency;
|
||||
|
||||
[Fact]
|
||||
public void Serve_piu_di_un_campione_prima_di_fidarsi()
|
||||
{
|
||||
var clock = new ServerClock();
|
||||
clock.AddSample(1000, Freq * 1000, 0);
|
||||
clock.AddSample(1001, Freq * 1001, 0);
|
||||
Assert.False(clock.IsSynced);
|
||||
clock.AddSample(1002, Freq * 1002, 0);
|
||||
Assert.True(clock.IsSynced);
|
||||
Assert.Equal(3, clock.SampleCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_media_segue_la_finestra_e_dimentica_il_passato()
|
||||
{
|
||||
var clock = new ServerClock();
|
||||
for (var i = 0; i < 256; i++) clock.AddSample(1000 + i, Freq * (1000 + i), 500);
|
||||
Assert.Equal(500, clock.AverageLatencyMs, 3);
|
||||
for (var i = 0; i < 256; i++) clock.AddSample(2000 + i, Freq * (2000 + i), 50);
|
||||
Assert.Equal(50, clock.AverageLatencyMs, 3);
|
||||
Assert.Equal(256, clock.SampleCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ignora_i_campioni_privi_di_senso()
|
||||
{
|
||||
var clock = new ServerClock();
|
||||
clock.AddSample(0, Freq, 0);
|
||||
clock.AddSample(-5, Freq, 0);
|
||||
clock.AddSample(1000, 0, 0);
|
||||
Assert.Equal(0, clock.SampleCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Con_zero_latenza_ricostruisce_esattamente_l_origine()
|
||||
{
|
||||
const long origin = 500;
|
||||
var clock = new ServerClock();
|
||||
for (var sec = 1000; sec < 1010; sec++) clock.AddSample(sec, origin + sec * Freq, 0);
|
||||
Assert.Equal(origin, clock.Origin);
|
||||
Assert.Equal(origin + 2000 * Freq, clock.ToLocalTicks(2000));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sottrae_meta_del_tempo_di_andata_e_ritorno()
|
||||
{
|
||||
const int latency = 100;
|
||||
var half = (long)(latency / 2.0 / 1000.0 * Freq);
|
||||
var clock = new ServerClock();
|
||||
for (var sec = 1000; sec < 1005; sec++) clock.AddSample(sec, sec * Freq + half, latency);
|
||||
Assert.Equal(0, clock.Origin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_filtro_al_minimo_scarta_le_risposte_lente()
|
||||
{
|
||||
const long origin = 1_000_000;
|
||||
var clock = new ServerClock();
|
||||
clock.AddSample(1000, origin + 1000 * Freq, 0);
|
||||
for (var sec = 1001; sec < 1010; sec++) clock.AddSample(sec, origin + sec * Freq + Freq / 2, 0);
|
||||
Assert.Equal(origin, clock.Origin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void L_errore_resta_entro_il_millisecondo_dal_campione_migliore()
|
||||
{
|
||||
const long origin = 5_000_000;
|
||||
var clock = new ServerClock();
|
||||
var delays = new long[] { 3, 17, 5, 40, 9, 22, 1, 31 };
|
||||
for (var i = 0; i < delays.Length; i++)
|
||||
{
|
||||
var sec = 2000 + i;
|
||||
clock.AddSample(sec, origin + sec * Freq + delays[i] * Freq / 1000, 0);
|
||||
}
|
||||
Assert.True(clock.Origin <= origin + Freq / 1000);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_dispersione_misura_la_finestra_dei_campioni()
|
||||
{
|
||||
var clock = new ServerClock();
|
||||
clock.AddSample(1000, 1000 * Freq, 0);
|
||||
clock.AddSample(1001, 1001 * Freq + Freq / 100, 0);
|
||||
clock.AddSample(1002, 1002 * Freq, 0);
|
||||
Assert.InRange(clock.SpreadMs, 9.0, 11.0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_e_finestra_scorrevole()
|
||||
{
|
||||
var clock = new ServerClock();
|
||||
for (var sec = 1000; sec < 1400; sec++) clock.AddSample(sec, sec * Freq, 0);
|
||||
Assert.Equal(256, clock.SampleCount);
|
||||
clock.Reset();
|
||||
Assert.False(clock.IsSynced);
|
||||
Assert.Equal(0, clock.Origin);
|
||||
Assert.Equal(0, clock.AverageLatencyMs);
|
||||
}
|
||||
}
|
||||
|
||||
public class PollCadenceTests
|
||||
{
|
||||
private static readonly AppSettings S = new();
|
||||
private static readonly BidooReferences R = BidooReferences.Default;
|
||||
|
||||
[Theory]
|
||||
[InlineData(RunMode.Watch, 120_000, 2000)]
|
||||
[InlineData(RunMode.Watch, 30_000, 900)]
|
||||
[InlineData(RunMode.Watch, 8_000, 400)]
|
||||
[InlineData(RunMode.Watch, 3_000, 400)] // la finestra critica vale solo in Attiva
|
||||
[InlineData(RunMode.Active, 3_000, 220)]
|
||||
[InlineData(RunMode.Active, 8_000, 400)]
|
||||
public void La_cadenza_si_stringe_verso_la_scadenza(RunMode mode, double ms, int expected)
|
||||
{
|
||||
Assert.Equal(expected, PollCadence.NextDelayMs(mode, AuctionStatus.Running, ms, S, R));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Un_asta_programmata_non_si_interroga_di_continuo_ma_non_si_perde_l_apertura()
|
||||
{
|
||||
Assert.Equal(1_200_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 3 * 3_600_000, S, R));
|
||||
Assert.Equal(120_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 30 * 60_000, S, R));
|
||||
Assert.Equal(30_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 8 * 60_000, S, R));
|
||||
|
||||
// A 130 s dall'apertura: al massimo fino al risveglio (120 s prima), cioè 10 s.
|
||||
Assert.Equal(10_000, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Scheduled, 130_000, S, R));
|
||||
|
||||
// Dentro il risveglio: cadenza normale.
|
||||
Assert.Equal(900, PollCadence.NextDelayMs(RunMode.Watch, AuctionStatus.Pending, 50_000, S, R));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Un_asta_sospesa_di_notte_si_guarda_ogni_30_secondi()
|
||||
{
|
||||
Assert.Equal(30_000, PollCadence.NextDelayMs(RunMode.Active, AuctionStatus.Paused, 8 * 3_600_000, S, R));
|
||||
}
|
||||
}
|
||||
|
||||
public class PrecisionWaitTests
|
||||
{
|
||||
[Fact]
|
||||
public void L_attesa_arriva_puntuale()
|
||||
{
|
||||
var errors = new List<double>();
|
||||
for (var i = 0; i < 25; i++)
|
||||
{
|
||||
var target = Stopwatch.GetTimestamp() + PrecisionWait.MsToTicks(30 + i % 7);
|
||||
PrecisionWait.Until(target, CancellationToken.None);
|
||||
errors.Add(-PrecisionWait.MsUntil(target));
|
||||
}
|
||||
|
||||
errors.Sort();
|
||||
// Mai in anticipo; in ritardo di poco. Soglia larga: in CI i core sono condivisi.
|
||||
Assert.All(errors, e => Assert.True(e >= 0));
|
||||
Assert.True(errors.Average() < 3, $"errore medio {errors.Average():F3} ms");
|
||||
Assert.True(errors[^2] < 15, $"errore quasi massimo {errors[^2]:F3} ms");
|
||||
}
|
||||
}
|
||||
|
||||
public class AuctionLogTests
|
||||
{
|
||||
[Fact]
|
||||
public void Una_decisione_ripetuta_e_una_riga_sola()
|
||||
{
|
||||
var log = new AuctionLog();
|
||||
log.AddDecision("ev-negativo", "Non punto: valore atteso -0,10 EUR");
|
||||
log.AddDecision("ev-negativo", "Non punto: valore atteso -0,12 EUR");
|
||||
log.AddDecision("ev-negativo", "Non punto: valore atteso -0,08 EUR");
|
||||
|
||||
var rows = log.Snapshot();
|
||||
Assert.Single(rows);
|
||||
Assert.Equal(3, rows[0].Count);
|
||||
Assert.Contains("-0,08", rows[0].Message);
|
||||
|
||||
log.AddDecision("punta", "Punto a 1,20 EUR");
|
||||
log.AddDecision("ev-negativo", "Non punto: valore atteso -0,20 EUR");
|
||||
Assert.Equal(3, log.Snapshot().Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Le_righe_passano_dal_pulitore_e_le_uguali_si_contano()
|
||||
{
|
||||
var log = new AuctionLog();
|
||||
var sunk = new List<AuctionLogEntry>();
|
||||
log.Sink = sunk.Add;
|
||||
|
||||
log.Add("Puntata ✓ riuscita → 1,20 €", LogLevel.Success, AuctionLogCategory.Bid);
|
||||
log.Add("Ciclo scaduto", LogLevel.Debug, AuctionLogCategory.Timing);
|
||||
log.Add("Ciclo scaduto", LogLevel.Debug, AuctionLogCategory.Timing);
|
||||
|
||||
var rows = log.Snapshot();
|
||||
Assert.Equal("Puntata riuscita -> 1,20 EUR", rows[0].Message);
|
||||
Assert.Equal(2, rows[1].Count);
|
||||
Assert.Equal(2, sunk.Count); // sul file solo le righe nuove
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Il simulatore risponde con lo stesso formato del sito: lo leggono i parser veri.</summary>
|
||||
public class SimulatorTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Le_risposte_del_simulatore_si_leggono_con_i_parser_veri()
|
||||
{
|
||||
await using var sim = await SimulatedBidoo.StartAsync(new SimWorld(seed: 7));
|
||||
var refs = sim.References();
|
||||
using var transport = new BidooTransport(() => refs, 0);
|
||||
using var lane = new BidLane(transport, () => refs, keepWarm: false);
|
||||
var api = new BidooApi(transport, lane, () => refs) { Username = "utente_demo" };
|
||||
|
||||
var running = sim.World.Read(w => w.Auctions.First(a => a.Started && a.Status == "ON"));
|
||||
var poll = await api.PollAsync(running.Id, null, 50, CancellationToken.None);
|
||||
Assert.NotNull(poll.State);
|
||||
Assert.Equal(AuctionStatus.Running, poll.State!.Status);
|
||||
Assert.Equal(running.PriceCents / 100.0, poll.State.Price, 3);
|
||||
Assert.NotNull(poll.State.RecentBidsHistory);
|
||||
Assert.Equal(running.LastBidder, poll.State.RecentBidsHistory![0].Username);
|
||||
|
||||
var scheduled = sim.World.Read(w => w.Auctions.First(a => !a.Started));
|
||||
var sched = await api.PollAsync(scheduled.Id, null, 50, CancellationToken.None);
|
||||
Assert.Equal(AuctionStatus.Scheduled, sched.State!.Status);
|
||||
|
||||
var account = await api.GetUserInfoAsync(CancellationToken.None);
|
||||
Assert.Equal("utente_demo", account!.Username);
|
||||
Assert.Equal(1407, account.RemainingBids);
|
||||
Assert.Equal(1, await api.GetAuctionsWonAsync(CancellationToken.None));
|
||||
|
||||
var page = await api.GetAuctionPageAsync(running.Id, null, CancellationToken.None);
|
||||
Assert.Equal(running.Name, page!.Name);
|
||||
Assert.Equal(running.Value, page.BuyNowPrice);
|
||||
|
||||
var catalog = new CatalogClient(transport, () => refs, null);
|
||||
var categories = await catalog.GetCategoriesAsync(true, CancellationToken.None);
|
||||
Assert.Contains(categories, c => c.DisplayName == "Buoni" && c.TagId == 6);
|
||||
var all = await catalog.GetAllAuctionsAsync(CatalogCategory.AllAuctions, 500, 0, CancellationToken.None);
|
||||
Assert.Equal(sim.World.Read(w => w.Auctions.Count(a => a.Status != "OFF")), all.Count);
|
||||
await catalog.UpdateStatesAsync(all, CancellationToken.None);
|
||||
Assert.Contains(all, a => a.CurrentPrice > 0.01m);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Un_asta_conclusa_porta_le_puntate_del_vincitore()
|
||||
{
|
||||
var world = new SimWorld(seed: 3, populate: false);
|
||||
await using var sim = await SimulatedBidoo.StartAsync(world);
|
||||
var a = world.AddRunningAuction(seconds: 1);
|
||||
await Task.Delay(1600);
|
||||
|
||||
var refs = sim.References();
|
||||
using var transport = new BidooTransport(() => refs, 0);
|
||||
using var lane = new BidLane(transport, () => refs, keepWarm: false);
|
||||
var poll = await new BidooApi(transport, lane, () => refs).PollAsync(a.Id, null, 50, CancellationToken.None);
|
||||
|
||||
Assert.Equal(AuctionStatus.EndedLost, poll.State!.Status);
|
||||
Assert.Equal(1, poll.State.WinnerBidsTotal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task La_mia_puntata_da_la_risposta_di_bid_php()
|
||||
{
|
||||
var world = new SimWorld(seed: 3, populate: false);
|
||||
await using var sim = await SimulatedBidoo.StartAsync(world);
|
||||
var a = world.AddRunningAuction(seconds: 8);
|
||||
|
||||
var refs = sim.References();
|
||||
using var transport = new BidooTransport(() => refs, 0);
|
||||
using var lane = new BidLane(transport, () => refs, keepWarm: false);
|
||||
var api = new BidooApi(transport, lane, () => refs);
|
||||
|
||||
var bid = await api.PlaceBidAsync(a.Id, null, null, 0, CancellationToken.None);
|
||||
Assert.True(bid.Success, bid.Error);
|
||||
Assert.Equal(1406, bid.Response.Remaining);
|
||||
Assert.Equal(1, bid.Response.UsedOnAuction);
|
||||
|
||||
var again = await api.PlaceBidAsync(a.Id, null, null, 0, CancellationToken.None);
|
||||
Assert.False(again.Success);
|
||||
Assert.Contains("miglior offerente", again.Error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Il motore vero contro il simulatore: una sola puntata per ciclo, partita all'anticipo
|
||||
/// voluto (misurato dal «server») e con l'attesa di precisione che sbaglia di poco.
|
||||
/// </summary>
|
||||
public class RunnerAgainstSimulatorTests
|
||||
{
|
||||
private sealed class Host : IAuctionRunnerHost
|
||||
{
|
||||
private readonly BidooApi _api;
|
||||
public readonly ServerClock Clock = new();
|
||||
public readonly List<double> WaitErrors = new();
|
||||
public int Evaluations;
|
||||
|
||||
public Host(BidooApi api, BidooReferences refs)
|
||||
{
|
||||
_api = api;
|
||||
References = refs;
|
||||
}
|
||||
|
||||
public AppSettings Settings { get; } = new();
|
||||
public BidooReferences References { get; }
|
||||
public int Lead { get; set; } = 400;
|
||||
|
||||
public async Task<AuctionState?> PollAsync(AuctionInfo auction, CancellationToken ct) =>
|
||||
(await _api.PollAsync(auction.Id, null, 50, ct)).State;
|
||||
|
||||
public void ApplySnapshot(AuctionInfo auction, AuctionState s)
|
||||
{
|
||||
Clock.AddSample(s.ServerUnixSeconds, s.ReceivedTicks, s.PollingLatencyMs);
|
||||
if (s.ExpiryUnixSeconds > 0 && Clock.IsSynced) auction.DeadlineTicks = Clock.ToLocalTicks(s.ExpiryUnixSeconds);
|
||||
auction.LastState = s;
|
||||
if (s.IsTerminal) auction.Outcome = s.Status == AuctionStatus.EndedWon ? "won" : "lost";
|
||||
}
|
||||
|
||||
public bool IsFinished(AuctionInfo auction) => auction.IsFinished;
|
||||
public bool IsShadow(AuctionInfo auction) => false;
|
||||
public int EffectiveLeadMs(AuctionInfo auction) => Lead;
|
||||
|
||||
public bool EvaluateBid(AuctionInfo auction, AuctionState state, bool shadow)
|
||||
{
|
||||
Evaluations++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void FireBid(AuctionInfo auction, AuctionState state, int leadMs, long fireTicks)
|
||||
{
|
||||
lock (WaitErrors) WaitErrors.Add((Stopwatch.GetTimestamp() - fireTicks) * 1000.0 / Stopwatch.Frequency);
|
||||
_api.PlaceBidAsync(auction.Id, null, null, 0, CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Il_cecchino_punta_una_volta_per_ciclo_prima_della_scadenza()
|
||||
{
|
||||
var world = new SimWorld(seed: 11, populate: false);
|
||||
await using var sim = await SimulatedBidoo.StartAsync(world);
|
||||
var target = world.AddRunningAuction(seconds: 6, freq: 4);
|
||||
|
||||
var refs = sim.References();
|
||||
using var transport = new BidooTransport(() => refs, 0);
|
||||
using var lane = new BidLane(transport, () => refs, keepWarm: false);
|
||||
var api = new BidooApi(transport, lane, () => refs) { Username = world.MyUsername };
|
||||
var host = new Host(api, refs);
|
||||
|
||||
var auction = new AuctionInfo(target.Id) { Name = target.Name, Mode = RunMode.Active };
|
||||
var runner = new AuctionRunner(auction, host);
|
||||
runner.Start();
|
||||
|
||||
// Nessun avversario: la nostra puntata resta l'ultima e l'asta chiude vinta.
|
||||
var deadline = DateTime.UtcNow.AddSeconds(20);
|
||||
while (!auction.IsFinished && DateTime.UtcNow < deadline) await Task.Delay(100);
|
||||
await runner.StopAsync();
|
||||
|
||||
var mine = world.MyBids.Where(b => b.AuctionId == target.Id).ToList();
|
||||
Assert.Equal("won", auction.Outcome);
|
||||
Assert.Single(mine, b => b.Accepted);
|
||||
|
||||
var bid = mine.First(b => b.Accepted);
|
||||
// Arrivata prima della scadenza, non prima del doppio dell'anticipo voluto.
|
||||
Assert.InRange(bid.LeadMs, 1, host.Lead * 2 + 1000);
|
||||
Assert.All(host.WaitErrors, e => Assert.InRange(e, 0, 5));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
error|Timer scaduto<br>Riprova
|
||||
@@ -0,0 +1 @@
|
||||
ok|927|480|3|5|0|1234567|0|0
|
||||
@@ -0,0 +1 @@
|
||||
1785597295*[95235087;OFF;1784757333;838;redberri;1;1h 24m;|0|25|0|0|0|0|,838;redberri;1784757325;1|837;semoricci;1784757318;3|836;redberri;1784757312;1]
|
||||
@@ -0,0 +1 @@
|
||||
1785597356*[95755813;ON;1785597364;4;kikisi9;1,4;kikisi9;1785597356;1|3;casmeride;1785597348;1|2;kikisi9;1785597340;1]
|
||||
@@ -0,0 +1 @@
|
||||
1764068200*(95216992;ON;1764068210;342;fedekikka2323#95216993;OFF;1764068100;120;tizio#95216994;ON;1764075000;1;)
|
||||
@@ -0,0 +1 @@
|
||||
1785597337*[95760550;ON;1785597351;1;;,]
|
||||
@@ -0,0 +1,314 @@
|
||||
using System.Text.Json;
|
||||
using BidooBidBot.Config;
|
||||
using BidooBidBot.Logging;
|
||||
using BidooBidBot.Settings;
|
||||
using BidooBidBot.Web;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>Niente simboli né emoji nei registri (portati dal legacy).</summary>
|
||||
public class LogTextTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("✓ Convenienza OK → tutto ok — bene… ≤ 3 × 2 €", "Convenienza OK -> tutto ok - bene... <= 3 x 2 EUR")]
|
||||
[InlineData("🔥 avvio motore ⚡", "avvio motore")]
|
||||
[InlineData("riga uno\r\nriga due\tfine", "riga uno riga due fine")]
|
||||
[InlineData("«virgolette» e “altre”", "\"virgolette\" e \"altre\"")]
|
||||
[InlineData("", "")]
|
||||
public void Il_testo_esce_in_chiaro(string dentro, string fuori)
|
||||
{
|
||||
Assert.Equal(fuori, LogText.Clean(dentro));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_registro_applicativo_tiene_il_tag_e_rispetta_il_livello()
|
||||
{
|
||||
var log = new AppLog(null) { MinLevel = LogLevel.Info, Capacity = 50 };
|
||||
LogEntry? seen = null;
|
||||
log.Entry += e => seen = e;
|
||||
|
||||
log.Debug("PUNTATA", "non si vede");
|
||||
Assert.Null(seen);
|
||||
|
||||
log.Info("puntata", "Buono → 4,12 €");
|
||||
Assert.NotNull(seen);
|
||||
Assert.Equal("PUNTATA", seen!.Tag);
|
||||
Assert.Equal("[PUNTATA] Buono -> 4,12 EUR", seen.Text);
|
||||
Assert.Single(log.Snapshot());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void L_anello_in_memoria_ha_un_tetto()
|
||||
{
|
||||
var log = new AppLog(null) { Capacity = 60 };
|
||||
for (var i = 0; i < 200; i++) log.Info("X", $"riga {i}");
|
||||
var rows = log.Snapshot();
|
||||
Assert.Equal(60, rows.Count);
|
||||
Assert.Equal("riga 199", rows[^1].Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Il_file_giornaliero_riceve_le_righe()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
var file = new FileLog(dir.Path);
|
||||
var log = new AppLog(file);
|
||||
log.Info("AVVIO", "prova");
|
||||
await file.DisposeAsync();
|
||||
|
||||
var text = File.ReadAllText(file.PathFor("app", DateTime.Now));
|
||||
Assert.Contains("[AVVIO] prova", text);
|
||||
}
|
||||
}
|
||||
|
||||
public class EnvConfigTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("192.168.30.23", "192.168.30.23", null)]
|
||||
[InlineData("192.168.30.23:5433", "192.168.30.23", 5433)]
|
||||
[InlineData("postgres:5432", "postgres", 5432)]
|
||||
[InlineData("[::1]:5432", "::1", 5432)]
|
||||
[InlineData(" ", "", null)]
|
||||
public void DB_HOST_accetta_anche_la_porta(string raw, string host, int? port)
|
||||
{
|
||||
var (h, p) = EnvConfig.SplitHost(raw);
|
||||
Assert.Equal(host, h);
|
||||
Assert.Equal(port, p);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Predefiniti_e_porta_separata()
|
||||
{
|
||||
var env = new Dictionary<string, string?> { ["DB_HOST"] = "db", ["DB_PORT"] = "6000", ["DB_PASSWORD"] = "x" };
|
||||
var cfg = EnvConfig.Read(k => env.GetValueOrDefault(k), Array.Empty<string>());
|
||||
Assert.Equal("db", cfg.DbHost);
|
||||
Assert.Equal(6000, cfg.DbPort);
|
||||
Assert.Equal("admin", cfg.DbUser);
|
||||
Assert.Equal("autobidder", cfg.DbName);
|
||||
Assert.Equal(8080, cfg.HttpPort);
|
||||
Assert.False(cfg.HasUiPassword);
|
||||
Assert.Equal("/config", cfg.ConfigDir);
|
||||
Assert.DoesNotContain("x", cfg.ToDbConfig().Describe());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Avvio senza variabili: schermata d'errore, niente database (ConfigErrorTests della specifica).</summary>
|
||||
public class ConfigErrorTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Senza_variabili_il_rapporto_dice_cosa_manca()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
var env = EnvConfig.Read(_ => null, new[] { "--config", dir.Path });
|
||||
var (report, db) = await StartupCheck.RunAsync(env, new ConfigPaths(dir.Path), 1, CancellationToken.None);
|
||||
|
||||
Assert.Null(db);
|
||||
Assert.False(report.AllOk);
|
||||
Assert.Contains(report.Items, i => i.Key == "db_host" && !i.Ok);
|
||||
Assert.Contains(report.Items, i => i.Key == "db_password" && !i.Ok);
|
||||
Assert.Contains(report.Items, i => i.Key == "ui_password" && !i.Ok);
|
||||
Assert.Contains(report.Items, i => i.Key == "config" && i.Ok);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Database_irraggiungibile_da_un_errore_leggibile()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
var vars = new Dictionary<string, string?> { ["DB_HOST"] = "127.0.0.1:1", ["DB_PASSWORD"] = "segreta", ["UI_PASSWORD"] = "x" };
|
||||
var env = EnvConfig.Read(k => vars.GetValueOrDefault(k), new[] { "--config", dir.Path });
|
||||
var (report, db) = await StartupCheck.RunAsync(env, new ConfigPaths(dir.Path), 1, CancellationToken.None);
|
||||
|
||||
Assert.Null(db);
|
||||
var item = Assert.Single(report.Items, i => i.Key == "database");
|
||||
Assert.False(item.Ok);
|
||||
Assert.StartsWith("Npgsql:", item.Error);
|
||||
Assert.DoesNotContain("segreta", item.Error + item.Detail);
|
||||
|
||||
var html = Pages.ConfigError("1.0.0", report, 30);
|
||||
Assert.Contains("Bidoo BidBot non può partire", html);
|
||||
Assert.Contains("Riprova adesso", html);
|
||||
Assert.DoesNotContain("segreta", html);
|
||||
}
|
||||
}
|
||||
|
||||
public class UiAuthTests
|
||||
{
|
||||
private static UiAuth Make(string password = "giusta") => new(password, new byte[32]);
|
||||
|
||||
[Fact]
|
||||
public void Solo_la_password_giusta_passa()
|
||||
{
|
||||
var auth = Make();
|
||||
Assert.True(auth.CheckPassword("giusta"));
|
||||
Assert.False(auth.CheckPassword("Giusta"));
|
||||
Assert.False(auth.CheckPassword(""));
|
||||
Assert.False(auth.CheckPassword(null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_cookie_vale_30_giorni_e_poi_scade()
|
||||
{
|
||||
var auth = Make();
|
||||
var now = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero);
|
||||
var token = auth.IssueToken(now);
|
||||
|
||||
Assert.True(auth.Validate(token, now.AddDays(29)).Valid);
|
||||
Assert.False(auth.Validate(token, now.AddDays(31)).Valid);
|
||||
Assert.True(auth.Validate(token, now.AddDays(2)).ShouldRenew);
|
||||
Assert.False(auth.Validate(token, now.AddHours(2)).ShouldRenew);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Un_cookie_alterato_o_di_un_altra_password_non_vale()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var token = Make().IssueToken(now);
|
||||
|
||||
Assert.False(Make("altra").Validate(token, now).Valid);
|
||||
Assert.False(Make().Validate(token[..^2] + "AA", now).Valid);
|
||||
Assert.False(Make().Validate("spazzatura", now).Valid);
|
||||
Assert.False(Make().Validate(null, now).Valid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dopo_cinque_tentativi_l_attesa_cresce()
|
||||
{
|
||||
var auth = Make();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
for (var i = 0; i < 4; i++) Assert.Equal(TimeSpan.Zero, auth.RecordFailure("1.2.3.4", now));
|
||||
|
||||
Assert.Equal(TimeSpan.FromSeconds(2), auth.RecordFailure("1.2.3.4", now));
|
||||
Assert.Equal(TimeSpan.FromSeconds(4), auth.RecordFailure("1.2.3.4", now));
|
||||
Assert.Equal(TimeSpan.FromSeconds(8), auth.RecordFailure("1.2.3.4", now));
|
||||
Assert.True(auth.LockedFor("1.2.3.4", now) > TimeSpan.Zero);
|
||||
Assert.Equal(TimeSpan.Zero, auth.LockedFor("5.6.7.8", now));
|
||||
|
||||
auth.RecordSuccess("1.2.3.4");
|
||||
Assert.Equal(TimeSpan.Zero, auth.LockedFor("1.2.3.4", now));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_chiave_si_crea_una_volta_e_si_rilegge()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
var file = Path.Combine(dir.Path, "sessione", "interfaccia.key");
|
||||
var a = UiAuth.LoadOrCreateKey(file);
|
||||
var b = UiAuth.LoadOrCreateKey(file);
|
||||
Assert.Equal(32, a.Length);
|
||||
Assert.Equal(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Impostazioni: valori di fabbrica, migrazione, puntate virtuali, segreti (SettingsMigrationTests).</summary>
|
||||
public class SettingsTests
|
||||
{
|
||||
private static Dictionary<string, JsonElement> Patch(string json) =>
|
||||
JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json)!;
|
||||
|
||||
[Fact]
|
||||
public void I_paletti_di_fabbrica_sono_tutti_a_zero()
|
||||
{
|
||||
var s = new AppSettings();
|
||||
Assert.Equal(0, s.DefaultMaxPrice);
|
||||
Assert.Equal(0, s.MaxBidsPerAuction);
|
||||
Assert.Equal(0, s.MinimumRemainingBids);
|
||||
Assert.Equal(0, s.DailyBudgetEuro);
|
||||
Assert.False(s.QuietHoursEnabled);
|
||||
Assert.True(s.ShadowDecisionsInWatch);
|
||||
Assert.Equal(100, s.LeadMinMs);
|
||||
Assert.Equal(250, s.DefaultBidBeforeDeadlineMs);
|
||||
Assert.Equal(300, s.LearningMinAuctions);
|
||||
Assert.Equal(50, s.DataCapGb);
|
||||
Assert.Equal("Osserva", s.AutoAddNewAuctionState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_migrazione_porta_i_modi_in_italiano()
|
||||
{
|
||||
var s = new AppSettings { SettingsSchemaVersion = 0, AutoAddNewAuctionState = "Watch", DefaultNewAuctionState = "Active" };
|
||||
Assert.True(SettingsStore.Migrate(s));
|
||||
Assert.Equal("Osserva", s.AutoAddNewAuctionState);
|
||||
Assert.Equal("Attiva", s.DefaultNewAuctionState);
|
||||
Assert.False(SettingsStore.Migrate(s));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_migrazione_stringe_l_anticipo_solo_se_era_quello_di_fabbrica()
|
||||
{
|
||||
var old = new AppSettings { SettingsSchemaVersion = 1, LeadMinMs = 300, DefaultBidBeforeDeadlineMs = 500, ShadowDecisionsInWatch = false, MaxRequestsPerSecond = 40 };
|
||||
Assert.True(SettingsStore.Migrate(old));
|
||||
Assert.Equal(100, old.LeadMinMs);
|
||||
Assert.Equal(250, old.DefaultBidBeforeDeadlineMs);
|
||||
Assert.True(old.ShadowDecisionsInWatch);
|
||||
Assert.Equal(0, old.MaxRequestsPerSecond);
|
||||
|
||||
// Un valore scritto dall'utente resta com'era.
|
||||
var mine = new AppSettings { SettingsSchemaVersion = 1, LeadMinMs = 180, DefaultBidBeforeDeadlineMs = 400, MaxRequestsPerSecond = 25 };
|
||||
SettingsStore.Migrate(mine);
|
||||
Assert.Equal(180, mine.LeadMinMs);
|
||||
Assert.Equal(400, mine.DefaultBidBeforeDeadlineMs);
|
||||
Assert.Equal(25, mine.MaxRequestsPerSecond);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void I_valori_fuori_scala_si_riportano_nei_limiti()
|
||||
{
|
||||
var s = SettingsStore.Normalize(new AppSettings { LeadMinMs = 10, LeadMaxMs = 5, QuietHoursStart = 25, DataCapGb = 0, PollCriticalMs = 1 });
|
||||
Assert.Equal(100, s.LeadMinMs);
|
||||
Assert.Equal(100, s.LeadMaxMs);
|
||||
Assert.Equal(1, s.QuietHoursStart);
|
||||
Assert.Equal(1, s.DataCapGb);
|
||||
Assert.Equal(50, s.PollCriticalMs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Il_salvataggio_vale_subito_e_si_scrive_nel_registro()
|
||||
{
|
||||
var log = new AppLog(null);
|
||||
var store = new SettingsStore(null, log);
|
||||
var result = await store.SaveAsync(Patch("""{"DailyBudgetEuro": 15, "MaxBidsPerAuction": 25}"""));
|
||||
|
||||
Assert.True(result.Ok);
|
||||
Assert.Equal(15, store.Current.DailyBudgetEuro);
|
||||
Assert.Equal(2, result.Changes.Count);
|
||||
Assert.Contains(log.Snapshot(), e => e.Tag == "IMPOSTAZIONI" && e.Message.StartsWith("DailyBudgetEuro: 0 -> 15"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Le_puntate_virtuali_si_spengono_senza_conferme_e_la_vecchia_modalita_non_esiste_piu()
|
||||
{
|
||||
var store = new SettingsStore(null, null);
|
||||
|
||||
var off = await store.SaveAsync(Patch("""{"ShadowDecisionsInWatch": false}"""));
|
||||
Assert.True(off.Ok);
|
||||
Assert.False(store.Current.ShadowDecisionsInWatch);
|
||||
|
||||
// DAL VIVO non c'è più: le aste in Attiva puntano e basta.
|
||||
Assert.False((await store.SaveAsync(Patch("""{"LiveBiddingEnabled": true}"""))).Ok);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task I_segreti_non_finiscono_nel_registro_e_tornano_mascherati()
|
||||
{
|
||||
var log = new AppLog(null);
|
||||
var store = new SettingsStore(null, log);
|
||||
await store.SaveAsync(Patch("""{"TelegramBotToken": "123:segretissimo"}"""));
|
||||
|
||||
Assert.DoesNotContain(log.Snapshot(), e => e.Message.Contains("segretissimo"));
|
||||
Assert.Equal(SettingsStore.MaskedSecret, SettingsStore.ForDisplay(store.Current)["TelegramBotToken"]);
|
||||
|
||||
// Il valore mascherato che torna dall'interfaccia lascia il segreto com'era.
|
||||
await store.SaveAsync(Patch("""{"TelegramBotToken": "********", "TelegramChatId": "42"}"""));
|
||||
Assert.Equal("123:segretissimo", store.Current.TelegramBotToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Una_chiave_sconosciuta_o_un_tipo_sbagliato_non_si_salvano()
|
||||
{
|
||||
var store = new SettingsStore(null, null);
|
||||
Assert.False((await store.SaveAsync(Patch("""{"NonEsiste": 1}"""))).Ok);
|
||||
Assert.False((await store.SaveAsync(Patch("""{"DailyBudgetEuro": "tanto"}"""))).Ok);
|
||||
Assert.Equal(0, store.Current.DailyBudgetEuro);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
using BidooBidBot.Data;
|
||||
using BidooBidBot.Ml;
|
||||
using BidooBidBot.Products;
|
||||
using BidooBidBot.Session;
|
||||
using BidooBidBot.Settings;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>L'anticipo adattivo (portato dal legacy, margine ristretto nella 1.1.0).</summary>
|
||||
public class LatencyModelTests
|
||||
{
|
||||
private static AppSettings Paletti(int min = 100, int max = 1500, int fixedMs = 250) =>
|
||||
new() { LeadMinMs = min, LeadMaxMs = max, DefaultBidBeforeDeadlineMs = fixedMs };
|
||||
|
||||
[Fact]
|
||||
public void Senza_misure_vale_l_anticipo_fisso_dentro_i_paletti()
|
||||
{
|
||||
var m = new LatencyModel(null);
|
||||
Assert.Equal(250, m.RecommendedLeadMs(Paletti()));
|
||||
Assert.Equal(600, m.RecommendedLeadMs(Paletti(min: 600)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Con_le_misure_e_margine_piu_p99_della_rete()
|
||||
{
|
||||
var m = new LatencyModel(null);
|
||||
for (var i = 0; i < 98; i++) m.NotePing(55);
|
||||
m.NotePing(90);
|
||||
m.NotePing(90);
|
||||
// p99 su cento campioni = 90; margine di partenza 80.
|
||||
Assert.Equal(LatencyModel.DefaultMarginMs + 90, m.RecommendedLeadMs(Paletti()));
|
||||
Assert.InRange(m.RecommendedLeadMs(Paletti()), 150, 200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Una_puntata_tardiva_allarga_subito_e_venti_puntuali_stringono()
|
||||
{
|
||||
var m = new LatencyModel(null);
|
||||
for (var i = 0; i < 20; i++) m.NotePing(50);
|
||||
var before = m.RecommendedLeadMs(Paletti());
|
||||
|
||||
m.NoteBid(60, late: true);
|
||||
var after = m.RecommendedLeadMs(Paletti());
|
||||
Assert.True(after >= before + 90, $"prima {before}, dopo {after}");
|
||||
|
||||
var margin = m.Snapshot().MarginMs;
|
||||
for (var i = 0; i < 20; i++) m.NoteBid(60, late: false);
|
||||
Assert.Equal(margin - 10, m.Snapshot().MarginMs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_margine_non_scende_sotto_il_minimo_e_l_anticipo_resta_nei_paletti()
|
||||
{
|
||||
var m = new LatencyModel(null);
|
||||
for (var i = 0; i < 400; i++) m.NoteBid(40, late: false);
|
||||
Assert.Equal(LatencyModel.MinMarginMs, m.Snapshot().MarginMs);
|
||||
Assert.Equal(100, m.RecommendedLeadMs(Paletti()));
|
||||
|
||||
for (var i = 0; i < 30; i++) m.NoteBid(40, late: true);
|
||||
Assert.Equal(1500, m.RecommendedLeadMs(Paletti()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_margine_salvato_con_la_versione_vecchia_riparte_da_quello_nuovo()
|
||||
{
|
||||
var docs = new MemoryDocumentStore();
|
||||
docs.Set(LatencyModel.DocKey, """{"MarginMs":300,"LateBids":2,"Bids":50,"RoundTrips":[60,70,80]}""");
|
||||
var m = new LatencyModel(docs);
|
||||
Assert.Equal(LatencyModel.DefaultMarginMs, m.Snapshot().MarginMs);
|
||||
Assert.Equal(2, m.Snapshot().LateBids);
|
||||
|
||||
// Salvato con la versione nuova, il margine imparato resta.
|
||||
for (var i = 0; i < 3; i++) m.NoteBid(60, late: true);
|
||||
m.Save(force: true);
|
||||
Assert.Equal(LatencyModel.DefaultMarginMs + 300, new LatencyModel(docs).Snapshot().MarginMs);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Il mercato di un prodotto (dal ProductStatSummary del legacy).</summary>
|
||||
public class ProductMarketTests
|
||||
{
|
||||
private static ProductStatsData Stats()
|
||||
{
|
||||
var s = new ProductStatsData { Shipping = 0, HoursBetweenAuctions = 6, WinnerBidsPaidTotal = 16, WinnerBidsFreeTotal = 84 };
|
||||
s.RecentCloses.AddRange(new[] { 1.00, 2.00, 3.00, 4.00, 5.00 });
|
||||
s.RecentWinnerBids.AddRange(new[] { 10, 20, 30 });
|
||||
s.RecentWins.Add(new ProductStatsData.WinSample(1.00, 10, 50, 0));
|
||||
s.RecentWins.Add(new ProductStatsData.WinSample(3.00, 20, 50, 0));
|
||||
s.RecentWins.Add(new ProductStatsData.WinSample(40.00, 30, 50, 0));
|
||||
return s;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_costo_tipico_e_la_chiusura_mediana_piu_le_puntate_mediane()
|
||||
{
|
||||
var m = ProductMarket.Of(Stats(), bidCostEuro: 0.20, transactionFee: 1.00, value: 50);
|
||||
Assert.Equal(3.00, m.MedianClose);
|
||||
Assert.Equal(20, m.MedianWinnerBids);
|
||||
// 3 + 20 × 0,20 + 1 di fee = 8
|
||||
Assert.Equal(8.00, m.TypicalWinCost);
|
||||
Assert.Equal(84.0, m.TypicalSavingPercent);
|
||||
Assert.Equal(10, m.MinWinnerBids);
|
||||
Assert.Equal(30, m.MaxWinnerBids);
|
||||
Assert.Equal(0.84, m.FreeBidShare);
|
||||
Assert.Equal(6, m.HoursBetweenAuctions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_risparmio_di_ogni_asta_dice_quante_sarebbero_state_in_utile()
|
||||
{
|
||||
var m = ProductMarket.Of(Stats(), bidCostEuro: 0.20, transactionFee: 1.00, value: 50);
|
||||
// 1+2+1 = 4 → 92 %; 3+4+1 = 8 → 84 %; 40+6+1 = 47 → 6 %: tutte in utile.
|
||||
Assert.Equal(6.0, m.MinSavingPercent);
|
||||
Assert.Equal(92.0, m.MaxSavingPercent);
|
||||
Assert.Equal(1.0, m.ProfitableShare);
|
||||
|
||||
var cheap = ProductMarket.Of(Stats(), bidCostEuro: 0.20, transactionFee: 1.00, value: 10);
|
||||
Assert.True(cheap.TypicalSavingPercent is > 0);
|
||||
Assert.Equal(2 / 3.0, cheap.ProfitableShare!.Value, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Senza_dati_non_inventa_nulla()
|
||||
{
|
||||
var m = ProductMarket.Of(new ProductStatsData(), 0.20, 1.00, 50);
|
||||
Assert.Null(m.MedianClose);
|
||||
Assert.Null(m.TypicalWinCost);
|
||||
Assert.Null(m.ProfitableShare);
|
||||
Assert.Null(m.FreeBidShare);
|
||||
Assert.Equal(default, ProductMarket.Of(null, 0.20, 1.00, 50));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Il saldo del conto: a pagamento + gratuite finché tornano col totale (dal legacy).</summary>
|
||||
public class AccountBalanceTests
|
||||
{
|
||||
[Fact]
|
||||
public void La_divisione_resta_finche_torna_col_totale()
|
||||
{
|
||||
var a = new AccountState();
|
||||
a.SetBids(927, 480);
|
||||
Assert.Equal(1407, a.Total);
|
||||
|
||||
a.SetTotal(1407);
|
||||
Assert.Equal(927, a.Paid);
|
||||
|
||||
// Un totale diverso: la divisione non è più affidabile.
|
||||
a.SetTotal(1400);
|
||||
Assert.Equal(1400, a.Total);
|
||||
Assert.Null(a.Paid);
|
||||
Assert.Null(a.Free);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_saldo_per_l_utente_e_solo_il_totale()
|
||||
{
|
||||
var a = new AccountState();
|
||||
Assert.Equal("n.d.", a.BalanceText());
|
||||
|
||||
// Anche con la divisione nota, nei testi compare solo il totale.
|
||||
a.SetBids(926, 480);
|
||||
Assert.Equal("1.406", a.BalanceText());
|
||||
Assert.Equal(926, a.Paid);
|
||||
|
||||
a.SetTotal(1400);
|
||||
Assert.Equal("1.400", a.BalanceText());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
using BidooBidBot.Ml;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>Le formule del modello matematico (portati dal legacy).</summary>
|
||||
public class TheoryTests
|
||||
{
|
||||
private static Theory.BidSituation S(double p, double value = 11, double price = 0.50, double c = 0.20,
|
||||
double fee = 1.0, double ship = 0, double? list = null, double spent = 0, bool hedge = false) =>
|
||||
new(p, value, price, c, fee, ship, list, spent, hedge);
|
||||
|
||||
[Fact]
|
||||
public void Senza_copertura_la_puntata_si_paga_in_entrambi_i_rami()
|
||||
{
|
||||
Assert.Equal(0.5 * 9.29 - 0.5 * 0.20, Theory.BidExpectedValue(S(0.5)), 6);
|
||||
Assert.Equal(-0.20, Theory.BidExpectedValue(S(0)), 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_pareggio_e_dove_il_valore_atteso_e_zero()
|
||||
{
|
||||
var s = S(0.123);
|
||||
Assert.Equal(0, Theory.BidExpectedValue(s with { PWin = Theory.BreakEvenPWin(s) }), 6);
|
||||
var hopeless = S(0.9, value: 1.0, price: 0.90);
|
||||
Assert.Equal(1, Theory.BreakEvenPWin(hopeless));
|
||||
Assert.False(Theory.ShouldBid(hopeless));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_copertura_azzera_il_costo_di_sconfitta_solo_oltre_la_perdita_coperta()
|
||||
{
|
||||
Assert.Equal(0.20, Theory.LossBranchCost(S(0.1, value: 8.80, list: 11, spent: 1.00, hedge: true)));
|
||||
Assert.Equal(0, Theory.LossBranchCost(S(0.1, value: 8.80, list: 11, spent: 2.20, hedge: true)));
|
||||
Assert.Equal(0, Theory.LossBranchCost(S(0.01, value: 11, list: 11, hedge: true)));
|
||||
Assert.Equal(0.20, Theory.LossBranchCost(S(0.1, value: 8.80, list: 11, spent: 5, hedge: false)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Con_V_uguale_al_listino_la_copertura_rende_gratis_ogni_puntata()
|
||||
{
|
||||
var s = new Theory.BidSituation(0.001, 11, 1.48, 0.20, 1, 0, 11, 0, true);
|
||||
Assert.True(Theory.BidExpectedValue(s) > 0);
|
||||
Assert.True(Theory.BidExpectedValue(s with { HedgeEnabled = false }) < 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sopravvivenza_kaplan_meier_e_poisson()
|
||||
{
|
||||
var cycles = new List<Theory.CycleObservation>();
|
||||
for (var i = 0; i < 30; i++) cycles.Add(new(5.0, false));
|
||||
for (var i = 0; i < 15; i++) cycles.Add(new(1.0, false));
|
||||
for (var i = 0; i < 5; i++) cycles.Add(new(0, true));
|
||||
Assert.Equal(0.25, Theory.WinProbabilityAtLead(cycles, 2.0)!.Value, 6);
|
||||
Assert.Equal(0.10, Theory.WinProbabilityAtLead(cycles, 6.0)!.Value, 6);
|
||||
Assert.Null(Theory.WinProbabilityAtLead(cycles.Take(10), 2.0));
|
||||
|
||||
var km = Theory.KaplanMeier(new[] { new Theory.CycleObservation(8, false), new(8, false), new(3, false), new(0, true) });
|
||||
Assert.Equal(0.5, km[0].Survival, 6);
|
||||
Assert.Equal(0.25, km[1].Survival, 6);
|
||||
|
||||
Assert.Equal(Math.Exp(-1), Theory.NoBidProbability(0.5, 2), 9);
|
||||
Assert.Equal(55, Theory.CriticalBidders(11, 0.20), 6);
|
||||
}
|
||||
}
|
||||
|
||||
public class OnlineLogitTests
|
||||
{
|
||||
[Fact]
|
||||
public void Impara_una_regola_semplice_e_resta_calibrato()
|
||||
{
|
||||
var m = new OnlineLogit(2);
|
||||
var rnd = new Random(7);
|
||||
for (var i = 0; i < 20000; i++)
|
||||
{
|
||||
var a = rnd.Next(2) == 1;
|
||||
m.Update(new[] { a ? 1.0 : 0.0, rnd.Next(2) }, a);
|
||||
}
|
||||
Assert.True(m.Predict(new[] { 1.0, 0.0 }) > 0.9);
|
||||
Assert.True(m.Predict(new[] { 0.0, 1.0 }) < 0.1);
|
||||
|
||||
var rare = new OnlineLogit(1);
|
||||
for (var i = 0; i < 40000; i++) rare.Update(new[] { 1.0 }, rnd.NextDouble() < 0.02);
|
||||
Assert.InRange(rare.Predict(new[] { 1.0 }), 0.01, 0.04);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Si_salva_e_i_parametri_vengono_dal_codice()
|
||||
{
|
||||
var m = new OnlineLogit(3) { LearningRate = 0.5 };
|
||||
m.Update(new[] { 1.0, 0.0, 1.0 }, true);
|
||||
var back = OnlineLogit.FromJson(m.ToJson(), 3);
|
||||
Assert.Equal(m.Weights, back.Weights);
|
||||
Assert.Equal(new OnlineLogit(3).LearningRate, back.LearningRate);
|
||||
Assert.Equal(0, OnlineLogit.FromJson(m.ToJson(), 5).Updates);
|
||||
}
|
||||
}
|
||||
|
||||
public class NeuralNetTests
|
||||
{
|
||||
[Fact]
|
||||
public void Impara_lo_xor()
|
||||
{
|
||||
var net = new NeuralNet(new[] { 2, 8, 1 }, seed: 3) { LearningRate = 0.02 };
|
||||
var data = new[] { (new[] { 0.0, 0.0 }, false), (new[] { 0.0, 1.0 }, true), (new[] { 1.0, 0.0 }, true), (new[] { 1.0, 1.0 }, false) };
|
||||
var rng = new Random(1);
|
||||
for (var i = 0; i < 6000; i++)
|
||||
{
|
||||
var (x, y) = data[rng.Next(4)];
|
||||
net.Update(x, y);
|
||||
}
|
||||
Assert.True(net.Predict(new[] { 0.0, 0.0 }) < 0.2);
|
||||
Assert.True(net.Predict(new[] { 0.0, 1.0 }) > 0.8);
|
||||
Assert.True(net.Predict(new[] { 1.0, 1.0 }) < 0.2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Si_salva_identica_e_una_forma_diversa_riparte()
|
||||
{
|
||||
var net = new NeuralNet(new[] { 3, 4, 1 }, seed: 9);
|
||||
for (var i = 0; i < 100; i++) net.Update(new[] { 0.1 * i, 0.5, 1.0 }, i % 3 == 0);
|
||||
var back = NeuralNet.FromJson(net.ToJson(), new[] { 3, 4, 1 });
|
||||
Assert.Equal(net.Predict(new[] { 0.3, 0.5, 1.0 }), back.Predict(new[] { 0.3, 0.5, 1.0 }), 12);
|
||||
Assert.Equal(0, NeuralNet.FromJson(net.ToJson(), new[] { 5, 4, 1 }).Updates);
|
||||
}
|
||||
}
|
||||
|
||||
public class ThompsonBanditTests
|
||||
{
|
||||
[Fact]
|
||||
public void Parte_dal_prior_e_converge_all_evidenza()
|
||||
{
|
||||
var b = new ThompsonBandit { BaseRate = 0.05, PriorStrength = 4 };
|
||||
Assert.Equal(0.05, b.Mean("k"), 6);
|
||||
for (var i = 0; i < 100; i++) b.Observe("k", i % 2 == 0);
|
||||
Assert.True(Math.Abs(b.Mean("k") - 0.5) < 0.05);
|
||||
Assert.Equal(100, b.Evidence("k"), 6);
|
||||
Assert.Equal(b.Mean("k"), ThompsonBandit.FromJson(b.ToJson()).Mean("k"), 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Decide_con_il_valore_atteso_sul_p_estratto()
|
||||
{
|
||||
var b = new ThompsonBandit { BaseRate = 0.5, PriorStrength = 1000 };
|
||||
var good = new Theory.BidSituation(0, 11, 0.50, 0.20, 1.0, 0, null, 0, false);
|
||||
Assert.True(b.Decide("k", good, new Random(1)).Bid);
|
||||
Assert.False(b.Decide("k", good with { Value = 1.0, CurrentPrice = 0.95 }, new Random(1)).Bid);
|
||||
}
|
||||
}
|
||||
|
||||
public class BidFeaturesTests
|
||||
{
|
||||
private static BidContext Ctx(double gap = 7, double auto = 0.8, double? ratio = 0.05) =>
|
||||
new(gap, auto, 3, ratio, 12, DayOfWeek.Tuesday, 11, false, 2, 120, false, "50 bidoo shop");
|
||||
|
||||
[Fact]
|
||||
public void Dimensione_nomi_e_una_casella_per_gruppo()
|
||||
{
|
||||
Assert.Equal(BidFeatures.Size, BidFeatures.Names.Length);
|
||||
var x = BidFeatures.Build(Ctx());
|
||||
Assert.Equal(BidFeatures.Size, x.Length);
|
||||
int On(string prefix) => BidFeatures.Names.Select((n, i) => (n, i)).Count(t => t.n.StartsWith(prefix, StringComparison.Ordinal) && x[t.i] == 1);
|
||||
Assert.Equal(1, On("ciclo"));
|
||||
Assert.Equal(1, On("puntatori"));
|
||||
Assert.Equal(1, On("prodotto#"));
|
||||
Assert.Equal(1, On("tipico"));
|
||||
Assert.Equal(1, On("aggancio"));
|
||||
Assert.Equal(1, On("ora"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Size_e_nomi_contano_diciassette_fasce_orarie_per_l_ora_e_per_l_aggancio()
|
||||
{
|
||||
Assert.Equal(16, BidFeatures.OpenHourBands);
|
||||
Assert.Equal(17, BidFeatures.HourBands);
|
||||
Assert.Equal(BidFeatures.Names.Length, BidFeatures.Names.Distinct(StringComparer.Ordinal).Count());
|
||||
var ora = BidFeatures.Names.Where(n => n.StartsWith("ora", StringComparison.Ordinal)).ToList();
|
||||
var aggancio = BidFeatures.Names.Where(n => n.StartsWith("aggancio", StringComparison.Ordinal)).ToList();
|
||||
Assert.Equal(BidFeatures.HourBands, ora.Count);
|
||||
Assert.Equal(BidFeatures.HourBands, aggancio.Count);
|
||||
Assert.Equal("ora9-10", ora[0]);
|
||||
Assert.Equal("ora23-24", ora[14]);
|
||||
Assert.Equal("ora0-1", ora[15]);
|
||||
Assert.Equal("oraChiuso1-9", ora[16]);
|
||||
Assert.Equal("aggancioChiuso1-9", aggancio[^1]);
|
||||
|
||||
// Le altre variabili non sono cambiate: 86 prima, con 6 + 6 fasce orarie.
|
||||
Assert.Equal(86 - 12 + 2 * BidFeatures.HourBands, BidFeatures.Size);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(9, 0)] [InlineData(10, 1)] [InlineData(11, 2)] [InlineData(12, 3)] [InlineData(13, 4)] [InlineData(14, 5)]
|
||||
[InlineData(15, 6)] [InlineData(16, 7)] [InlineData(17, 8)] [InlineData(18, 9)] [InlineData(19, 10)] [InlineData(20, 11)]
|
||||
[InlineData(21, 12)] [InlineData(22, 13)] [InlineData(23, 14)] [InlineData(0, 15)]
|
||||
[InlineData(1, 16)] [InlineData(2, 16)] [InlineData(3, 16)] [InlineData(4, 16)] [InlineData(5, 16)] [InlineData(6, 16)] [InlineData(7, 16)] [InlineData(8, 16)]
|
||||
[InlineData(24, 15)] [InlineData(-1, 14)] [InlineData(33, 0)]
|
||||
public void Ogni_ora_di_apertura_di_Bidoo_ha_la_sua_fascia_e_le_ore_chiuse_una_sola(int hour, int band) =>
|
||||
Assert.Equal(band, BidFeatures.HourBand(hour));
|
||||
|
||||
[Fact]
|
||||
public void Le_etichette_dicono_le_ore_della_fascia()
|
||||
{
|
||||
var labels = Enumerable.Range(0, BidFeatures.HourBands).Select(BidFeatures.HourBandLabel).ToArray();
|
||||
Assert.Equal(new[]
|
||||
{
|
||||
"9-10", "10-11", "11-12", "12-13", "13-14", "14-15", "15-16", "16-17", "17-18",
|
||||
"18-19", "19-20", "20-21", "21-22", "22-23", "23-24", "0-1", "chiuso 1-9"
|
||||
}, labels);
|
||||
Assert.Equal("fascia sconosciuta", BidFeatures.HourBandLabel(17));
|
||||
Assert.Equal("fascia sconosciuta", BidFeatures.HourBandLabel(-1));
|
||||
|
||||
// Ogni ora del giorno cade nella fascia la cui etichetta la contiene.
|
||||
for (var h = 0; h < 24; h++)
|
||||
{
|
||||
var band = BidFeatures.HourBand(h);
|
||||
if (BidFeatures.IsOpenHourBand(band)) Assert.Equal(h, BidFeatures.HourBandStart(band));
|
||||
else Assert.InRange(h, BidFeatures.ClosingHour, BidFeatures.OpeningHour - 1);
|
||||
}
|
||||
|
||||
Assert.Equal("puntata fra le 9 e le 10", BidFeatures.Describe("ora9-10"));
|
||||
Assert.Equal("puntata fra le 23 e mezzanotte", BidFeatures.Describe("ora23-24"));
|
||||
Assert.Equal("asta agganciata fra mezzanotte e l'una", BidFeatures.Describe("aggancio0-1"));
|
||||
Assert.Equal("puntata fra l'una e le 9, ad aste sospese", BidFeatures.Describe("oraChiuso1-9"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Le_ore_vicine_non_scavalcano_la_chiusura_notturna()
|
||||
{
|
||||
Assert.Equal(0, BidFeatures.HourBandDistance(BidFeatures.HourBand(10), BidFeatures.HourBand(10)));
|
||||
Assert.Equal(1, BidFeatures.HourBandDistance(BidFeatures.HourBand(23), BidFeatures.HourBand(0)));
|
||||
Assert.Equal(15, BidFeatures.HourBandDistance(BidFeatures.HourBand(0), BidFeatures.HourBand(9)));
|
||||
Assert.Equal(int.MaxValue, BidFeatures.HourBandDistance(BidFeatures.HourBand(0), BidFeatures.HourBand(3)));
|
||||
Assert.Equal(0, BidFeatures.HourBandDistance(BidFeatures.HourBand(3), BidFeatures.HourBand(7)));
|
||||
Assert.Equal("9-12", BidFeatures.HourSpanLabel(0, 2));
|
||||
Assert.Equal("22-1", BidFeatures.HourSpanLabel(13, 15));
|
||||
Assert.Equal("10-11", BidFeatures.HourSpanLabel(1, 1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cicli_lunghi_cassetti_stabili_e_descrizioni()
|
||||
{
|
||||
Assert.Equal(2, BidFeatures.CountDeepCycles(new long[] { 100, 90, 88, 86, 70 }));
|
||||
Assert.Equal(1, BidFeatures.CountDeepCycles(new long[] { 100, 0, 90, 60 }));
|
||||
Assert.Equal(BidFeatures.ProductBucket("50 Bidoo Shop"), BidFeatures.ProductBucket("50 bidoo shop"));
|
||||
foreach (var n in BidFeatures.Names)
|
||||
{
|
||||
Assert.All(n, ch => Assert.True(ch < 128));
|
||||
Assert.NotEqual(n, BidFeatures.Describe(n));
|
||||
}
|
||||
var ignoto = BidFeatures.Build(Ctx(gap: -1, auto: -1, ratio: null));
|
||||
Assert.Equal(1, ignoto[Array.IndexOf(BidFeatures.Names, "valoreIgnoto")]);
|
||||
Assert.Equal(1, ignoto[Array.IndexOf(BidFeatures.Names, "quotaAutoIgnota")]);
|
||||
}
|
||||
}
|
||||
|
||||
public class AuctionProfileStatsTests
|
||||
{
|
||||
private static readonly DateTime Mon12 = new(2026, 9, 7, 12, 0, 0);
|
||||
private static readonly DateTime Sat21 = new(2026, 9, 12, 21, 0, 0);
|
||||
|
||||
[Fact]
|
||||
public void Si_restringe_verso_il_livello_sopra_con_pochi_esempi()
|
||||
{
|
||||
var s = new AuctionProfileStats();
|
||||
for (var i = 0; i < 200; i++) s.Observe("altro", Mon12, 25, 0.05);
|
||||
s.Observe("raro", Sat21, 100, 0.30);
|
||||
Assert.InRange(s.Expect("raro", Sat21)!.Value.WinnerBids, 25, 40);
|
||||
|
||||
for (var i = 0; i < 200; i++) s.Observe("caro", Sat21, 100, 0.30);
|
||||
Assert.InRange(s.Expect("caro", Sat21)!.Value.WinnerBids, 90, 100);
|
||||
Assert.Null(new AuctionProfileStats().Expect("x", Mon12));
|
||||
}
|
||||
}
|
||||
|
||||
public class TrainingReaderTests
|
||||
{
|
||||
private static TrainingReader.Session Session(string winner, params (string User, int Sec, string Type)[] bids) =>
|
||||
TrainingReader.Finish(new TrainingReader.Session
|
||||
{
|
||||
AuctionId = "1", ProductKey = "prova", BuyNowPrice = 10, AddedAtLocal = new DateTime(2026, 9, 7, 11, 0, 0),
|
||||
Winner = winner, FinalPrice = bids.Length / 100.0, HasSummary = true, Me = "carla",
|
||||
Bids = bids.Select((b, i) => new TrainingReader.Bid(i, b.User, 1_788_000_000 + b.Sec, b.Type, false, (i + 1) / 100.0)).ToList()
|
||||
});
|
||||
|
||||
[Fact]
|
||||
public void Etichetta_solo_l_ultima_e_marca_le_mie()
|
||||
{
|
||||
var s = Session("anna", ("bruno", 0, "Auto"), ("carla", 6, "Manuale"), ("anna", 16, "Auto"));
|
||||
Assert.True(s.IsUsable);
|
||||
var ex = TrainingReader.Examples(s).ToList();
|
||||
Assert.Equal(2, ex.Count);
|
||||
Assert.False(ex[0].Unanswered);
|
||||
Assert.True(ex[0].Mine);
|
||||
Assert.True(ex[1].Unanswered);
|
||||
Assert.Equal(10, ex[1].Context.CycleSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Un_buco_in_fondo_rende_l_asta_inutilizzabile()
|
||||
{
|
||||
Assert.False(Session("zeta", ("bruno", 0, "Auto"), ("carla", 6, "Manuale"), ("anna", 16, "Auto")).IsUsable);
|
||||
Assert.False(Session("anna", ("anna", 0, "Auto")).IsUsable);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Perché un'asta è andata così (famiglie allineate al mockup di «Perché perdo»).</summary>
|
||||
public class LossReasonsTests
|
||||
{
|
||||
private static LossReasons.DecisionRow D(string action, string kind, bool shadow = false, double? p = null, string? outcome = null) =>
|
||||
new(action, kind, p, shadow, outcome);
|
||||
|
||||
[Fact]
|
||||
public void Mai_puntato_dice_il_motivo_piu_frequente()
|
||||
{
|
||||
var decisions = Enumerable.Repeat(D("NO-OP", LossReasons.Kind.EvNegativo, p: 0.003), 4).Append(D("NO-OP", LossReasons.Kind.PrezzoMassimo)).ToList();
|
||||
var reason = LossReasons.Compute(decisions, Array.Empty<LossReasons.MyBidRow>(), false, "anna");
|
||||
Assert.StartsWith("mai puntato: il modello sconsigliava", reason);
|
||||
Assert.Contains("4 decisioni su 5", reason);
|
||||
Assert.Contains("vinta da anna", reason);
|
||||
Assert.Equal("mai puntato: il modello sconsigliava", LossReasons.Group(reason));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Un_paletto_che_ferma_e_la_famiglia_fermato()
|
||||
{
|
||||
var decisions = Enumerable.Repeat(D("NO-OP", LossReasons.Kind.PrezzoMassimo), 3).ToList();
|
||||
var reason = LossReasons.Compute(decisions, Array.Empty<LossReasons.MyBidRow>(), false, "anna");
|
||||
Assert.Equal("fermato: prezzo oltre il massimo", LossReasons.Group(reason));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Puntato_e_coperto_dice_da_chi_e_dopo_quanto()
|
||||
{
|
||||
var decisions = new[] { D("BID", LossReasons.Kind.Punta, p: 0.02), D("NO-OP", LossReasons.Kind.PrezzoMassimo) };
|
||||
var bids = new[] { new LossReasons.MyBidRow(4.85, 6, "anna", "Auto", false) };
|
||||
var reason = LossReasons.Compute(decisions, bids, false, "anna");
|
||||
Assert.StartsWith("puntato 1 volta; l'ultima coperta da anna (autopuntata) dopo 6 s", reason);
|
||||
Assert.Contains("poi fermato: prezzo oltre il massimo", reason);
|
||||
Assert.Equal("puntato e coperto dall'autopuntata", LossReasons.Group(reason));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void In_Osserva_si_dice_cosa_avrebbe_fatto()
|
||||
{
|
||||
var shadowOnly = new[] { D("NO-OP", LossReasons.Kind.EvNegativo, shadow: true), D("BID", LossReasons.Kind.Punta, shadow: true, outcome: "would_be_answered") };
|
||||
var reason = LossReasons.Compute(shadowOnly, Array.Empty<LossReasons.MyBidRow>(), false, "anna");
|
||||
Assert.StartsWith("in Osserva avrebbe puntato 1 volte", reason);
|
||||
Assert.Equal("in Osserva avrebbe puntato", LossReasons.Group(reason));
|
||||
Assert.Equal("vinta", LossReasons.Compute(shadowOnly, Array.Empty<LossReasons.MyBidRow>(), true, "io"));
|
||||
Assert.StartsWith("solo osservata", LossReasons.Compute(Array.Empty<LossReasons.DecisionRow>(), Array.Empty<LossReasons.MyBidRow>(), false, "x"));
|
||||
}
|
||||
}
|
||||
|
||||
public class ShadowReportTests
|
||||
{
|
||||
[Fact]
|
||||
public void Il_ROI_per_puntata_ha_il_suo_intervallo_e_il_null_model()
|
||||
{
|
||||
var rows = new List<ShadowReport.Row>();
|
||||
// 100 decisioni «punta»: 2 vincenti su un bene da 11 € a 0,50 €.
|
||||
for (var i = 0; i < 100; i++)
|
||||
rows.Add(new ShadowReport.Row("BID", "NO-OP", i < 2 ? "would_win" : "would_be_answered", 0.01, 0.50, 11, 0, 0.20, true, false));
|
||||
|
||||
var r = ShadowReport.Compute(rows, 1.0, 7);
|
||||
var model = r.Policies[0];
|
||||
Assert.Equal(100, model.Bids);
|
||||
Assert.Equal(2, model.Wins);
|
||||
Assert.Equal(2 * (11 - 0.51 - 1.0) - 100 * 0.20, model.Net, 6);
|
||||
Assert.NotNull(model.Ci95);
|
||||
Assert.False(model.BeatsNullModel);
|
||||
Assert.Equal(0, r.Policies[3].Bids); // «non punta mai»
|
||||
}
|
||||
}
|
||||
|
||||
public class ForecastTests
|
||||
{
|
||||
[Fact]
|
||||
public void La_previsione_e_condizionata_al_prezzo_e_copre_l_ottanta_per_cento()
|
||||
{
|
||||
var f = new AuctionForecast();
|
||||
var rng = new Random(5);
|
||||
var closes = new List<double>();
|
||||
for (var i = 0; i < 200; i++)
|
||||
{
|
||||
var c = Math.Round(1 + rng.NextDouble() * rng.NextDouble() * 10, 2);
|
||||
closes.Add(c);
|
||||
f.Observe("buono", c, 50, 2, 40 + rng.Next(40), 10);
|
||||
}
|
||||
|
||||
var at1 = f.Forecast(new ForecastInput("buono", 1.00, 50, 2, 6, 0.01, 0.13, 1, 0, 3, 0))!;
|
||||
var at4 = f.Forecast(new ForecastInput("buono", 4.00, 50, 2, 6, 0.01, 0.13, 1, 0, 3, 0))!;
|
||||
Assert.True(at4.Close >= 4.00);
|
||||
Assert.True(at4.P10 >= 4.00);
|
||||
Assert.True(at1.P10 <= at1.Close && at1.Close <= at1.P90);
|
||||
Assert.NotNull(at1.WinnerBids);
|
||||
Assert.NotNull(at1.MinutesLeft);
|
||||
Assert.NotNull(at1.EvIfEnter);
|
||||
|
||||
// Copertura: nuove chiusure dalla stessa distribuzione cadono nell'intervallo circa 8 volte su 10.
|
||||
var inside = 0;
|
||||
for (var i = 0; i < 400; i++)
|
||||
{
|
||||
var c = Math.Round(1 + rng.NextDouble() * rng.NextDouble() * 10, 2);
|
||||
if (c >= at1.P10 && c <= at1.P90) inside++;
|
||||
}
|
||||
Assert.InRange(inside / 400.0, 0.70, 0.90);
|
||||
|
||||
var back = AuctionForecast.FromJson(f.ToJson());
|
||||
Assert.Equal(at1.Close, back.Forecast(new ForecastInput("buono", 1.00, 50, 2, 6, 0.01, 0.13, 1, 0, 3, 0))!.Close);
|
||||
}
|
||||
|
||||
private static AuctionForecast.Sample At(int hour, double close = 2) => new(close, BidFeatures.HourBand(hour), null, null, null);
|
||||
|
||||
[Fact]
|
||||
public void Con_poche_aste_nell_ora_esatta_si_allarga_alle_ore_vicine()
|
||||
{
|
||||
// Dieci aste alle 10-11: basta l'ora esatta.
|
||||
var many = Enumerable.Repeat(At(10), 10).Concat(Enumerable.Repeat(At(11), 5)).ToList();
|
||||
var exact = AuctionForecast.PoolForHour(many, BidFeatures.HourBand(10));
|
||||
Assert.Equal(0, exact.Radius);
|
||||
Assert.Equal(10, exact.Samples.Count);
|
||||
Assert.Equal("10 aste del prodotto alle 10-11", AuctionForecast.DescribePool(exact, BidFeatures.HourBand(10)));
|
||||
|
||||
// Quattro alle 10-11, tre alle 9-10, quattro alle 11-12: si prende un'ora per parte.
|
||||
var few = Enumerable.Repeat(At(10), 4).Concat(Enumerable.Repeat(At(9), 3)).Concat(Enumerable.Repeat(At(11), 4))
|
||||
.Concat(Enumerable.Repeat(At(20), 30)).ToList();
|
||||
var near = AuctionForecast.PoolForHour(few, BidFeatures.HourBand(10));
|
||||
Assert.Equal(1, near.Radius);
|
||||
Assert.Equal(11, near.Samples.Count);
|
||||
Assert.Equal(4, near.Exact);
|
||||
Assert.Equal("11 aste del prodotto alle 9-12 (alle 10-11 solo 4: comprese le ore vicine)",
|
||||
AuctionForecast.DescribePool(near, BidFeatures.HourBand(10)));
|
||||
|
||||
// Mezzanotte-l'una: le vicine sono le 23 e le 22, non le 9 dall'altra parte della chiusura.
|
||||
var night = Enumerable.Repeat(At(0), 2).Concat(Enumerable.Repeat(At(23), 3)).Concat(Enumerable.Repeat(At(22), 5))
|
||||
.Concat(Enumerable.Repeat(At(9), 30)).ToList();
|
||||
var late = AuctionForecast.PoolForHour(night, BidFeatures.HourBand(0));
|
||||
Assert.Equal(2, late.Radius);
|
||||
Assert.Equal(10, late.Samples.Count);
|
||||
Assert.StartsWith("10 aste del prodotto alle 22-1", AuctionForecast.DescribePool(late, BidFeatures.HourBand(0)));
|
||||
|
||||
// Troppo poche anche a due ore: tutte le aste del prodotto. Le ore chiuse non hanno vicine.
|
||||
var sparse = new List<AuctionForecast.Sample> { At(10), At(12), At(15), At(3) };
|
||||
Assert.Equal(-1, AuctionForecast.PoolForHour(sparse, BidFeatures.HourBand(10)).Radius);
|
||||
Assert.Equal(4, AuctionForecast.PoolForHour(sparse, BidFeatures.HourBand(10)).Samples.Count);
|
||||
var closed = AuctionForecast.PoolForHour(Enumerable.Repeat(At(0), 20).Append(At(4)).ToList(), BidFeatures.HourBand(4));
|
||||
Assert.Equal(-1, closed.Radius);
|
||||
Assert.Equal("21 aste del prodotto", AuctionForecast.DescribePool(closed, BidFeatures.HourBand(4)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_previsione_usa_le_ore_vicine_quando_l_ora_esatta_non_basta()
|
||||
{
|
||||
var f = new AuctionForecast();
|
||||
// Alle 13-14 le chiusure sono alte, il resto della giornata basse: 3 + 4 + 4 aste attorno alle 13.
|
||||
foreach (var (hour, n) in new[] { (12, 4), (13, 3), (14, 4) })
|
||||
for (var i = 0; i < n; i++) f.Observe("buono", 8 + i * 0.1, 50, BidFeatures.HourBand(hour), 40, 10);
|
||||
for (var i = 0; i < 40; i++) f.Observe("buono", 1 + i * 0.01, 50, BidFeatures.HourBand(20), 40, 10);
|
||||
|
||||
var r = f.Forecast(new ForecastInput("buono", 0.5, 50, BidFeatures.HourBand(13), null, null, 0.13, 1, 0, 3, 0))!;
|
||||
Assert.True(r.Close >= 8);
|
||||
Assert.Contains("alle 12-15", r.Basis);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_finestra_delle_ore_conta_solo_le_chiusure_sopra_il_prezzo_attuale()
|
||||
{
|
||||
var ten = BidFeatures.HourBand(10);
|
||||
// All'ora esatta 12 aste chiuse a 2 €, alle ore accanto 10 chiuse a 6 €.
|
||||
var samples = Enumerable.Repeat(At(10, 2), 12).Concat(Enumerable.Repeat(At(9, 6), 5)).Concat(Enumerable.Repeat(At(11, 6), 5)).ToList();
|
||||
|
||||
// Senza prezzo basta l'ora esatta.
|
||||
Assert.Equal(0, AuctionForecast.PoolForHour(samples, ten).Radius);
|
||||
|
||||
// A 4 € l'ora esatta non ha nessuna chiusura utile: si allarga alle ore vicine.
|
||||
var pool = AuctionForecast.PoolForHour(samples, ten, 4);
|
||||
Assert.Equal(1, pool.Radius);
|
||||
Assert.Equal(10, pool.Samples.Count);
|
||||
Assert.All(pool.Samples, s => Assert.True(s.Close >= 4));
|
||||
Assert.Equal(0, pool.Exact);
|
||||
Assert.Equal(12, pool.Below);
|
||||
Assert.Equal("10 aste del prodotto alle 9-12 (alle 10-11 nessuna: comprese le ore vicine), escluse 12 finite sotto il prezzo attuale",
|
||||
AuctionForecast.DescribePool(pool, ten));
|
||||
|
||||
// Una chiusura pari al prezzo attuale conta.
|
||||
Assert.Equal(12, AuctionForecast.PoolForHour(samples, ten, 2).Samples.Count(s => s.Band == ten));
|
||||
|
||||
// Troppo poche anche a due ore: tutte le aste del prodotto sopra il prezzo.
|
||||
var sparse = Enumerable.Repeat(At(10, 2), 12).Concat(Enumerable.Repeat(At(9, 6), 3)).Concat(Enumerable.Repeat(At(20, 7), 3)).ToList();
|
||||
var all = AuctionForecast.PoolForHour(sparse, ten, 4);
|
||||
Assert.Equal(-1, all.Radius);
|
||||
Assert.Equal(6, all.Samples.Count);
|
||||
Assert.Equal(12, all.Below);
|
||||
Assert.Equal("6 aste del prodotto, escluse 12 finite sotto il prezzo attuale", AuctionForecast.DescribePool(all, ten));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_previsione_usa_le_aste_del_prodotto_sopra_il_prezzo_prima_del_ripiego_globale()
|
||||
{
|
||||
var f = new AuctionForecast();
|
||||
// 12 aste alle 10-11 chiuse basse, 6 alle 20-21 chiuse alte; un altro prodotto con chiusure basse.
|
||||
for (var i = 0; i < 12; i++) f.Observe("buono", 1 + i * 0.01, 50, BidFeatures.HourBand(10), 40, 10);
|
||||
for (var i = 0; i < 6; i++) f.Observe("buono", 8 + i * 0.1, 50, BidFeatures.HourBand(20), 40, 10);
|
||||
for (var i = 0; i < 40; i++) f.Observe("altro", 0.5, 50, BidFeatures.HourBand(15), 20, 5);
|
||||
|
||||
var r = f.Forecast(new ForecastInput("buono", 4, 50, BidFeatures.HourBand(10), null, null, 0.13, 1, 0, 3, 0))!;
|
||||
Assert.True(r.Close >= 8);
|
||||
Assert.Equal(6, r.Samples);
|
||||
Assert.Equal("6 aste del prodotto, escluse 12 finite sotto il prezzo attuale", r.Basis);
|
||||
|
||||
// Solo se nemmeno tutte le aste del prodotto bastano, il rapporto al valore di tutti i prodotti,
|
||||
// e la base dice quante chiusure usa davvero.
|
||||
for (var i = 0; i < 10; i++) f.Observe("terzo", 5, 50, BidFeatures.HourBand(15), 20, 5);
|
||||
var global = f.Forecast(new ForecastInput("mai visto", 4, 50, BidFeatures.HourBand(10), null, null, 0.13, 1, 0, 3, 0))!;
|
||||
Assert.Equal(16, global.Samples);
|
||||
Assert.Equal("16 aste di tutti i prodotti, in rapporto al valore, escluse 52 finite sotto il prezzo attuale", global.Basis);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_base_della_previsione_nelle_ore_chiuse_si_legge_bene()
|
||||
{
|
||||
var closed = BidFeatures.HourBand(3);
|
||||
var pool = AuctionForecast.PoolForHour(Enumerable.Repeat(At(3), 12).ToList(), closed);
|
||||
Assert.Equal(0, pool.Radius);
|
||||
Assert.Equal("12 aste del prodotto chiuse fra l'una e le 9, ad aste sospese", AuctionForecast.DescribePool(pool, closed));
|
||||
Assert.DoesNotContain("alle chiuso", AuctionForecast.DescribePool(pool, closed));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Senza_dati_non_si_inventa_e_gli_errori_si_riassumono()
|
||||
{
|
||||
Assert.Null(new AuctionForecast().Forecast(new ForecastInput("mai visto", 1, null, 2, null, null, 0.2, 1, 0, 2, 0)));
|
||||
|
||||
var s = ForecastErrors.Summarize(new[]
|
||||
{
|
||||
new ForecastErrors.Row(5, 3, 8, 6, 50, 60),
|
||||
new ForecastErrors.Row(5, 3, 8, 9, 50, 40),
|
||||
new ForecastErrors.Row(5, 3, 8, 4, null, null)
|
||||
});
|
||||
Assert.Equal(3, s.Auctions);
|
||||
Assert.Equal(2.0 / 3, s.Coverage!.Value, 6);
|
||||
Assert.Equal(1, s.MedianAbsError!.Value, 6);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
using BidooBidBot.Bidoo;
|
||||
using BidooBidBot.Data;
|
||||
using BidooBidBot.Engine;
|
||||
using BidooBidBot.Logging;
|
||||
using BidooBidBot.Ml;
|
||||
using BidooBidBot.Net;
|
||||
using BidooBidBot.Products;
|
||||
using BidooBidBot.Session;
|
||||
using BidooBidBot.Settings;
|
||||
using BidooBidBot.Simulator;
|
||||
using BidooBidBot.Strategy;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>Il monitor intero (motori, verdetto, puntata, chiusura) contro il simulatore, senza database.</summary>
|
||||
public class MonitorAgainstSimulatorTests
|
||||
{
|
||||
private sealed class Rig : IAsyncDisposable
|
||||
{
|
||||
public required SimulatedBidoo Sim { get; init; }
|
||||
public required AuctionMonitor Monitor { get; init; }
|
||||
public required BidooTransport Transport { get; init; }
|
||||
public required BidLane Lane { get; init; }
|
||||
public required AppLog Log { get; init; }
|
||||
public required RiskManager Risk { get; init; }
|
||||
public required AccountState Account { get; init; }
|
||||
public SimWorld World => Sim.World;
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Monitor.DisposeAsync();
|
||||
Lane.Dispose();
|
||||
Transport.Dispose();
|
||||
await Sim.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<Rig> StartAsync(SimWorld world, AppSettings settings, Func<bool>? canBid = null)
|
||||
{
|
||||
var sim = await SimulatedBidoo.StartAsync(world);
|
||||
var refs = sim.References();
|
||||
var transport = new BidooTransport(() => refs, 0);
|
||||
var lane = new BidLane(transport, () => refs, keepWarm: false);
|
||||
var api = new BidooApi(transport, lane, () => refs) { Username = world.MyUsername };
|
||||
var docs = new MemoryDocumentStore();
|
||||
var log = new AppLog(null);
|
||||
var account = new AccountState();
|
||||
account.SetUser(world.MyUsername, world.MyUserId);
|
||||
var risk = new RiskManager(docs, new ListLedger());
|
||||
var learning = new LearningService(docs, new MemoryLearningData(), () => settings, log);
|
||||
var products = new ProductStore(null);
|
||||
|
||||
var monitor = new AuctionMonitor(new MonitorDeps
|
||||
{
|
||||
Settings = () => settings,
|
||||
References = () => refs,
|
||||
Api = api,
|
||||
Clock = new ServerClock(),
|
||||
Strategy = new BidStrategy(risk, learning, products, () => account.Balance),
|
||||
Risk = risk,
|
||||
Learning = learning,
|
||||
Latency = new LatencyModel(docs),
|
||||
Recorder = new AuctionRecorder(null, null, () => settings, () => world.MyUsername, Worlds.Simulator),
|
||||
Products = products,
|
||||
Account = account,
|
||||
Log = log,
|
||||
Documents = docs,
|
||||
World = Worlds.Simulator,
|
||||
CanBid = canBid ?? (() => true)
|
||||
});
|
||||
return new Rig { Sim = sim, Monitor = monitor, Transport = transport, Lane = lane, Log = log, Risk = risk, Account = account };
|
||||
}
|
||||
|
||||
private static async Task<(AuctionInfo A, CloseSummary C, string Line)> RunToCompletionAsync(Rig rig, AuctionInfo a, int seconds = 30)
|
||||
{
|
||||
var done = new TaskCompletionSource<(AuctionInfo, CloseSummary, string)>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
rig.Monitor.AuctionCompleted += (x, c, line) => { if (x.Id == a.Id) done.TrySetResult((x, c, line)); };
|
||||
rig.Monitor.Start();
|
||||
return await done.Task.WaitAsync(TimeSpan.FromSeconds(seconds));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task In_Attiva_punta_una_volta_vince_e_chiude_con_il_riepilogo()
|
||||
{
|
||||
var world = new SimWorld(seed: 21, populate: false);
|
||||
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0 };
|
||||
await using var rig = await StartAsync(world, settings);
|
||||
var target = world.AddRunningAuction(seconds: 5, freq: 4);
|
||||
|
||||
var (a, message) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
||||
Assert.NotNull(a);
|
||||
Assert.Contains("Attiva", message);
|
||||
Assert.True(a!.ProductInfoLoaded);
|
||||
Assert.Equal(target.Value, a.BuyNowPrice);
|
||||
|
||||
var (done, summary, line) = await RunToCompletionAsync(rig, a);
|
||||
|
||||
Assert.Equal("won", done.Outcome);
|
||||
Assert.True(summary.WonByMe);
|
||||
Assert.Equal(1, summary.MyBids);
|
||||
Assert.Equal(1, done.SuccessfulBids);
|
||||
Assert.Single(world.MyBids, b => b.AuctionId == target.Id && b.Accepted);
|
||||
Assert.StartsWith("Vinta a", line);
|
||||
Assert.Contains("resta in elenco", line);
|
||||
Assert.NotNull(rig.Monitor.Find(target.Id));
|
||||
Assert.Contains(rig.Log.Snapshot(), e => e.Tag == "PUNTATA");
|
||||
Assert.Contains(rig.Log.Snapshot(), e => e.Tag == "FINE");
|
||||
// Il conto si aggiorna dalla risposta di bid.php.
|
||||
Assert.NotNull(rig.Account.Total);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task In_Osserva_decide_senza_puntare_e_la_conclusa_esce_dall_elenco()
|
||||
{
|
||||
var world = new SimWorld(seed: 22, populate: false);
|
||||
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0 };
|
||||
await using var rig = await StartAsync(world, settings);
|
||||
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
||||
|
||||
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Watch), CancellationToken.None);
|
||||
var (done, summary, line) = await RunToCompletionAsync(rig, a!);
|
||||
|
||||
Assert.Empty(world.MyBids);
|
||||
Assert.False(summary.WonByMe);
|
||||
Assert.Equal("lost", done.Outcome);
|
||||
Assert.NotNull(done.LastDecision);
|
||||
Assert.True(done.LastDecision!.Shadow);
|
||||
Assert.Contains(done.Log.Snapshot(), e => e.Message.StartsWith("Avrei puntato", StringComparison.Ordinal));
|
||||
Assert.Contains("tolta dall'elenco", line);
|
||||
Assert.Null(rig.Monitor.Find(target.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Il_rischio_fermo_blocca_la_puntata_dal_vivo_ma_non_la_decisione()
|
||||
{
|
||||
var world = new SimWorld(seed: 23, populate: false);
|
||||
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0, AutoRemoveFinished = false };
|
||||
await using var rig = await StartAsync(world, settings);
|
||||
rig.Risk.SetHalt("prova", automatic: false);
|
||||
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
||||
|
||||
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
||||
var (done, _, _) = await RunToCompletionAsync(rig, a!);
|
||||
|
||||
Assert.Empty(world.MyBids);
|
||||
Assert.Equal(LossReasons.Kind.Rischio, done.LastDecision?.Kind);
|
||||
var (ok, why) = await rig.Monitor.BidNowAsync(target.Id, CancellationToken.None);
|
||||
Assert.False(ok);
|
||||
Assert.NotEmpty(why);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Dopo_un_riavvio_ogni_asta_riprende_da_dove_era()
|
||||
{
|
||||
var world = new SimWorld(seed: 24, populate: false);
|
||||
var settings = new AppSettings { QuietHoursEnabled = false };
|
||||
var target = world.AddRunningAuction(seconds: 600, freq: 10);
|
||||
var other = world.AddRunningAuction(seconds: 600, freq: 10);
|
||||
|
||||
string? saved;
|
||||
await using (var rig = await StartAsync(world, settings))
|
||||
{
|
||||
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
||||
rig.Monitor.SetLimits(a!.Id, 2.5, 12.5, 30, 450, quietHours: false);
|
||||
a.ResetCount = 17;
|
||||
a.MyBidsPlaced = 3;
|
||||
a.MyBidsCost = 0.39;
|
||||
await rig.Monitor.AddAsync(new AddAuctionRequest(other.Id, Mode: RunMode.Watch), CancellationToken.None);
|
||||
await rig.Monitor.DisposeAsync();
|
||||
saved = rig.Monitor.Deps.Documents.Get(rig.Monitor.Deps.DocumentKey);
|
||||
}
|
||||
Assert.NotNull(saved);
|
||||
|
||||
await using var again = await StartAsync(world, settings);
|
||||
again.Monitor.Deps.Documents.Set(again.Monitor.Deps.DocumentKey, saved!);
|
||||
Assert.Equal(2, await again.Monitor.RestoreAsync());
|
||||
var restored = again.Monitor.Find(target.Id)!;
|
||||
Assert.Equal(RunMode.Active, restored.Mode);
|
||||
Assert.Equal(RunMode.Watch, again.Monitor.Find(other.Id)!.Mode);
|
||||
Assert.Equal(2.5, restored.MinPrice);
|
||||
Assert.Equal(12.5, restored.MaxPrice);
|
||||
Assert.Equal(30, restored.MaxBids);
|
||||
Assert.False(restored.LimitsFromProduct);
|
||||
Assert.True(restored.LeadIsManual);
|
||||
Assert.Equal(450, restored.LeadMs);
|
||||
Assert.False(restored.QuietHoursOverride);
|
||||
Assert.Equal(17, restored.ResetCount);
|
||||
Assert.Equal(3, restored.MyBidsPlaced);
|
||||
Assert.Equal(0.39, restored.MyBidsCost, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Senza_utente_collegato_l_asta_Attiva_decide_ma_non_punta()
|
||||
{
|
||||
var world = new SimWorld(seed: 25, populate: false);
|
||||
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0, AutoRemoveFinished = false };
|
||||
await using var rig = await StartAsync(world, settings, canBid: () => false);
|
||||
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
||||
|
||||
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
||||
Assert.True(rig.Monitor.IsShadow(a!));
|
||||
var (done, _, _) = await RunToCompletionAsync(rig, a!);
|
||||
|
||||
Assert.Empty(world.MyBids);
|
||||
Assert.NotNull(done.LastDecision);
|
||||
Assert.True(done.LastDecision!.Shadow);
|
||||
var (ok, why) = await rig.Monitor.BidNowAsync(target.Id, CancellationToken.None);
|
||||
Assert.False(ok);
|
||||
Assert.Contains("Browser", why);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task In_Osserva_senza_puntate_virtuali_segue_ma_non_decide()
|
||||
{
|
||||
var world = new SimWorld(seed: 26, populate: false);
|
||||
var settings = new AppSettings { QuietHoursEnabled = false, ShadowDecisionsInWatch = false, AutoRemoveFinished = false };
|
||||
await using var rig = await StartAsync(world, settings);
|
||||
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
||||
|
||||
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Watch), CancellationToken.None);
|
||||
var (done, _, _) = await RunToCompletionAsync(rig, a!);
|
||||
|
||||
Assert.Empty(world.MyBids);
|
||||
Assert.Null(done.LastDecision);
|
||||
Assert.Equal("lost", done.Outcome);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Gli_errori_di_puntata_tardiva_si_riconoscono()
|
||||
{
|
||||
Assert.True(AuctionMonitor.IsLateBidError("timer scaduto"));
|
||||
Assert.True(AuctionMonitor.IsLateBidError("auction closed"));
|
||||
Assert.False(AuctionMonitor.IsLateBidError("saldo insufficiente"));
|
||||
Assert.False(AuctionMonitor.IsLateBidError(null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dopo_una_puntata_il_registro_dice_solo_il_totale_delle_puntate()
|
||||
{
|
||||
Assert.Equal(", 1.406 puntate residue", AuctionMonitor.RemainingText(1406));
|
||||
Assert.Equal(", 12 puntate residue", AuctionMonitor.RemainingText(12));
|
||||
Assert.Equal("", AuctionMonitor.RemainingText(null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
using System.Text.Json;
|
||||
using BidooBidBot.Bidoo;
|
||||
using BidooBidBot.Data;
|
||||
using BidooBidBot.Engine;
|
||||
using BidooBidBot.Logging;
|
||||
using BidooBidBot.Ml;
|
||||
using BidooBidBot.Net;
|
||||
using BidooBidBot.Products;
|
||||
using BidooBidBot.Session;
|
||||
using BidooBidBot.Settings;
|
||||
using BidooBidBot.Simulator;
|
||||
using BidooBidBot.Strategy;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// La pagina Prodotti senza database: il valore delle celle vuote, «Ricalcola i paletti» sulle
|
||||
/// schede e le statistiche nuove salvate come JSON.
|
||||
/// </summary>
|
||||
public class ProductLimitsTests
|
||||
{
|
||||
/// <summary>Statistiche con <paramref name="closes"/> chiusure crescenti e puntate del vincitore attendibili.</summary>
|
||||
private static ProductStatsData Stats(int closes, string name, double buyNow = 50)
|
||||
{
|
||||
var s = new ProductStatsData { Name = name, Auctions = closes, BuyNow = buyNow, Shipping = 1 };
|
||||
for (var i = 0; i < closes; i++)
|
||||
{
|
||||
s.RecentCloses.Add(1.0 + i * 0.1);
|
||||
s.RecentWinnerBids.Add(10 + i);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
private static AppSettings Settings() => new() { DefaultMaxPrice = 20, DefaultMaxClicks = 0, DefaultMinPrice = 0, AverageBidCostEuro = 0.20 };
|
||||
|
||||
[Fact]
|
||||
public void Una_cella_vuota_vale_il_calcolato_altrimenti_il_predefinito_campo_per_campo()
|
||||
{
|
||||
var s = new AppSettings { DefaultMaxPrice = 20, DefaultMaxClicks = 50, DefaultMinPrice = 0.5, AutoAddMaxStartMinutes = 60 };
|
||||
var computed = new ProductAdvice.Advice(true, 6.5, 40, 1.2, 3, 3.5, 85, false, false, 30, "calcolati");
|
||||
var p = new ProductRecord { ProductKey = "x", MinPrice = 2, MaxPrice = 5, MaxBids = 10, HorizonMinutes = 30 };
|
||||
|
||||
// I valori scritti non contano: la cella vuota mostra ciò che varrebbe al loro posto.
|
||||
Assert.Equal(new ProductRules.Fallbacks(1.2, 6.5, 40, 60), ProductRules.FallbacksOf(p, s, autoAdded: true, computed));
|
||||
Assert.Equal(new ProductRules.Fallbacks(0.5, 20, 50, 60), ProductRules.FallbacksOf(p, s, autoAdded: true));
|
||||
Assert.Equal(new ProductRules.Fallbacks(1.2, 6.5, 40, 60), ProductRules.FallbacksOf(null, s, autoAdded: true, computed));
|
||||
Assert.Equal(2, p.MinPrice); // la scheda non si tocca
|
||||
|
||||
// Il minimo calcolato sopra un massimo scritto più basso fermerebbe tutto: vale zero, come per l'asta.
|
||||
Assert.Equal(0, ProductRules.FallbacksOf(new ProductRecord { ProductKey = "y", MaxPrice = 1 }, s, autoAdded: true, computed).MinPrice);
|
||||
|
||||
// Le puntate che lo storico non sa dare restano quelle predefinite.
|
||||
Assert.Equal(50, ProductRules.FallbacksOf(null, s, autoAdded: true, computed with { MaxBids = null }).MaxBids);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void I_paletti_da_scrivere_sono_quelli_che_varrebbero_dal_calcolo()
|
||||
{
|
||||
var a = new ProductAdvice.Advice(true, 4.0, null, 5.0, 3, 3.5, 85, false, false, 30, "x");
|
||||
// Minimo sopra il massimo: niente minimo; puntate che lo storico non dà: niente.
|
||||
Assert.Equal(((double?)null, (double?)4.0, (int?)null), LimitsRecompute.Values(a));
|
||||
// Un massimo a zero sulla scheda vorrebbe dire «nessun limite»: non si scrive.
|
||||
Assert.Equal(((double?)1.2, (double?)null, (int?)12), LimitsRecompute.Values(a with { MaxPrice = 0, Floor = 1.2, MaxBids = 12 }));
|
||||
Assert.Equal(((double?)1.2, (double?)6.5, (int?)40), LimitsRecompute.Values(a with { MaxPrice = 6.5, Floor = 1.2, MaxBids = 40 }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ricalcola_i_paletti_scrive_le_schede_sopra_i_valori_scritti_e_ignora_chi_ha_poche_aste()
|
||||
{
|
||||
var settings = Settings();
|
||||
var store = new ProductStore(null);
|
||||
store.Upsert(new ProductRecord { ProductKey = "scritto", DisplayName = "Scritto", MinPrice = 0.01, MaxPrice = 99, MaxBids = 1, MarketValue = 50, Followed = true, AutoState = "attiva" });
|
||||
store.Upsert(new ProductRecord { ProductKey = "senza", DisplayName = "Senza paletti", Followed = true });
|
||||
var stats = new Dictionary<string, ProductStatsData>(StringComparer.Ordinal)
|
||||
{
|
||||
["nuovo"] = Stats(40, "Nuovo"),
|
||||
["scritto"] = Stats(40, "Scritto"),
|
||||
["senza"] = Stats(40, "Senza paletti"),
|
||||
["pochi"] = Stats(3, "Pochi")
|
||||
};
|
||||
|
||||
var plan = LimitsRecompute.Plan(store.Find, stats, settings);
|
||||
Assert.Equal(new[] { "nuovo", "scritto", "senza" }, plan.Select(c => c.Key).ToArray());
|
||||
|
||||
var nuovo = plan.Single(c => c.Key == "nuovo");
|
||||
Assert.True(nuovo.Creates);
|
||||
Assert.False(nuovo.Overwrites);
|
||||
Assert.Equal("Nuovo", nuovo.Name);
|
||||
Assert.NotNull(nuovo.MaxPrice);
|
||||
|
||||
var scritto = plan.Single(c => c.Key == "scritto");
|
||||
Assert.True(scritto.Overwrites);
|
||||
Assert.False(scritto.Creates);
|
||||
// I paletti scritti prima non influenzano il calcolo: come dalla scheda vuota.
|
||||
var bare = ProductLimits.AdviceFor(new ProductRecord { ProductKey = "scritto", MarketValue = 50 }, stats["scritto"], settings)!.Value;
|
||||
Assert.Equal(LimitsRecompute.Values(bare), (scritto.MinPrice, scritto.MaxPrice, scritto.MaxBids));
|
||||
|
||||
Assert.False(plan.Single(c => c.Key == "senza").Overwrites);
|
||||
|
||||
// Dalle statistiche in memoria del mondo, poi sulle schede.
|
||||
var limits = new ProductLimits(store, () => settings);
|
||||
foreach (var (k, v) in stats) limits.Update(k, v);
|
||||
Assert.Equal(plan, limits.PlanRecompute());
|
||||
Assert.Equal(3, limits.ApplyRecompute(limits.PlanRecompute()));
|
||||
|
||||
var after = store.Find("scritto")!;
|
||||
Assert.Equal(scritto.MaxPrice, after.MaxPrice);
|
||||
Assert.Equal(scritto.MaxBids, after.MaxBids);
|
||||
Assert.Equal(scritto.MinPrice, after.MinPrice);
|
||||
Assert.Equal(50, after.MarketValue); // il resto della scheda resta
|
||||
Assert.True(after.Followed);
|
||||
Assert.Equal("attiva", after.AutoState);
|
||||
Assert.Equal("Nuovo", store.Find("nuovo")!.DisplayName);
|
||||
Assert.Null(store.Find("pochi"));
|
||||
|
||||
// Scritti una volta, non c'è altro da cambiare; i paletti scritti ora valgono per le aste nuove.
|
||||
Assert.Empty(limits.PlanRecompute());
|
||||
var resolved = limits.Resolve("scritto", autoAdded: true);
|
||||
Assert.Equal(scritto.MaxPrice, resolved.MaxPrice);
|
||||
Assert.StartsWith("scheda", resolved.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ricalcola_i_paletti_scrive_un_centesimo_quando_il_budget_e_esaurito()
|
||||
{
|
||||
// Valore 2 €: 50 puntate da 0,20 € e la spedizione non lasciano nulla per il prezzo.
|
||||
var settings = new AppSettings { DefaultMaxPrice = 20, DefaultMaxClicks = 50, AverageBidCostEuro = 0.20 };
|
||||
var store = new ProductStore(null);
|
||||
var stats = new Dictionary<string, ProductStatsData>(StringComparer.Ordinal) { ["caro"] = Stats(40, "Caro", buyNow: 2) };
|
||||
|
||||
var change = Assert.Single(LimitsRecompute.Plan(store.Find, stats, settings));
|
||||
Assert.Equal(ProductAdvice.StopAllMaxPrice, change.MaxPrice);
|
||||
Assert.Null(change.MinPrice); // il minimo starebbe sopra il massimo
|
||||
|
||||
var limits = new ProductLimits(store, () => settings);
|
||||
limits.Update("caro", stats["caro"]);
|
||||
Assert.Equal(1, limits.ApplyRecompute(limits.PlanRecompute()));
|
||||
Assert.Equal(0.01, store.Find("caro")!.MaxPrice);
|
||||
Assert.Equal(0.01, limits.Resolve("caro", autoAdded: true).MaxPrice);
|
||||
|
||||
// Anche senza scriverlo sulla scheda, l'asta nuova nasce con 0,01 e non con «nessun limite».
|
||||
var bare = new ProductLimits(new ProductStore(null), () => settings);
|
||||
bare.Update("caro", stats["caro"]);
|
||||
Assert.Equal(0.01, bare.Resolve("caro", autoAdded: true).MaxPrice);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Le_statistiche_nuove_si_leggono_anche_dai_json_salvati_prima()
|
||||
{
|
||||
var old = JsonSerializer.Deserialize<ProductStatsData>("{\"Auctions\":12,\"Won\":1,\"AvgFinal\":3.5,\"RecentCloses\":[1.0,2.0]}")!;
|
||||
Assert.Equal(12, old.Auctions);
|
||||
Assert.Null(old.AvgDistinctBidders);
|
||||
Assert.Null(old.ManualBidShare);
|
||||
Assert.Null(old.MedianCompleteMinutes);
|
||||
Assert.Null(old.AvgTopBidderShare);
|
||||
Assert.Equal(0, old.BiddersSamples);
|
||||
Assert.Equal(0, old.TypedBids);
|
||||
|
||||
var saved = new ProductStatsData { AvgDistinctBidders = 6.5, BiddersSamples = 40, ManualBidShare = 0.25, TypedBids = 800, MedianCompleteMinutes = 95.5, AvgTopBidderShare = 0.41 };
|
||||
var back = JsonSerializer.Deserialize<ProductStatsData>(JsonSerializer.Serialize(saved))!;
|
||||
Assert.Equal(6.5, back.AvgDistinctBidders);
|
||||
Assert.Equal(40, back.BiddersSamples);
|
||||
Assert.Equal(0.25, back.ManualBidShare);
|
||||
Assert.Equal(800, back.TypedBids);
|
||||
Assert.Equal(95.5, back.MedianCompleteMinutes);
|
||||
Assert.Equal(0.41, back.AvgTopBidderShare);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_quota_senza_base_non_esiste()
|
||||
{
|
||||
Assert.Null(ProductStatsRepository.Share(0, 0));
|
||||
Assert.Equal(0.75, ProductStatsRepository.Share(3, 4));
|
||||
Assert.Equal(0, ProductStatsRepository.Share(0, 9));
|
||||
Assert.Equal(1, ProductStatsRepository.Share(12, 9)); // mai oltre il totale
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// I paletti del prodotto sulle aste in corso: solo per scelta dell'utente («Applica alle aste in
|
||||
/// corso», «Torna ai paletti del prodotto»), mai da soli. Il monitor contro il simulatore, fermo.
|
||||
/// </summary>
|
||||
public class ApplyProductLimitsTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Le_aste_in_corso_prendono_i_paletti_del_prodotto_solo_quando_l_utente_li_applica()
|
||||
{
|
||||
var world = new SimWorld(seed: 31, populate: false);
|
||||
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 20, DefaultMaxClicks = 50, DefaultMinPrice = 0 };
|
||||
var one = world.AddRunningAuction(seconds: 600);
|
||||
var two = world.AddRunningAuction(seconds: 600);
|
||||
|
||||
await using var sim = await SimulatedBidoo.StartAsync(world);
|
||||
var refs = sim.References();
|
||||
using var transport = new BidooTransport(() => refs, 0);
|
||||
using var lane = new BidLane(transport, () => refs, keepWarm: false);
|
||||
var api = new BidooApi(transport, lane, () => refs) { Username = world.MyUsername };
|
||||
var docs = new MemoryDocumentStore();
|
||||
var log = new AppLog(null);
|
||||
var account = new AccountState();
|
||||
account.SetUser(world.MyUsername, world.MyUserId);
|
||||
var risk = new RiskManager(docs, new ListLedger());
|
||||
var learning = new LearningService(docs, new MemoryLearningData(), () => settings, log);
|
||||
var products = new ProductStore(null);
|
||||
await using var monitor = new AuctionMonitor(new MonitorDeps
|
||||
{
|
||||
Settings = () => settings,
|
||||
References = () => refs,
|
||||
Api = api,
|
||||
Clock = new ServerClock(),
|
||||
Strategy = new BidStrategy(risk, learning, products, () => account.Balance),
|
||||
Risk = risk,
|
||||
Learning = learning,
|
||||
Latency = new LatencyModel(docs),
|
||||
Recorder = new AuctionRecorder(null, null, () => settings, () => world.MyUsername, Worlds.Simulator),
|
||||
Products = products,
|
||||
Account = account,
|
||||
Log = log,
|
||||
Documents = docs,
|
||||
World = Worlds.Simulator,
|
||||
Limits = new ProductLimits(products, () => settings)
|
||||
});
|
||||
|
||||
var (a, _) = await monitor.AddAsync(new AddAuctionRequest(one.Id, Mode: RunMode.Watch), CancellationToken.None);
|
||||
var (b, _) = await monitor.AddAsync(new AddAuctionRequest(two.Id, Mode: RunMode.Watch), CancellationToken.None);
|
||||
Assert.NotNull(a);
|
||||
Assert.NotNull(b);
|
||||
Assert.Equal(a!.ProductKey, b!.ProductKey);
|
||||
Assert.Equal(20, a.MaxPrice); // entrate con i predefiniti
|
||||
|
||||
// La scheda cambia: le aste già in elenco no.
|
||||
products.Upsert(new ProductRecord { ProductKey = a.ProductKey, DisplayName = a.Name, MinPrice = 1, MaxPrice = 7, MaxBids = 12 });
|
||||
Assert.Equal(20, a.MaxPrice);
|
||||
Assert.Equal(50, b.MaxBids);
|
||||
|
||||
// Una delle due con paletti scritti a mano sull'asta, compresi fascia oraria e anticipo.
|
||||
monitor.SetLimits(b.Id, 0, 30, 99, 700, true);
|
||||
Assert.False(b.LimitsFromProduct);
|
||||
Assert.True(b.QuietHoursOverride);
|
||||
Assert.Equal((2, 2, 1), monitor.PreviewProductLimits(a.ProductKey));
|
||||
Assert.Equal((0, 0, 0), monitor.PreviewProductLimits("un altro prodotto"));
|
||||
|
||||
// «Applica alle aste in corso»: tutte, anche quella scritta a mano. La fascia oraria torna
|
||||
// quella del prodotto; l'anticipo scritto a mano resta (non è un paletto del prodotto).
|
||||
Assert.Equal(2, monitor.ApplyProductLimits(a.ProductKey));
|
||||
foreach (var x in new[] { a, b })
|
||||
{
|
||||
Assert.Equal(1, x.MinPrice);
|
||||
Assert.Equal(7, x.MaxPrice);
|
||||
Assert.Equal(12, x.MaxBids);
|
||||
Assert.True(x.LimitsFromProduct);
|
||||
Assert.Null(x.QuietHoursOverride);
|
||||
}
|
||||
Assert.True(b.LeadIsManual);
|
||||
Assert.Equal(700, b.LeadMs);
|
||||
Assert.Contains(b.Log.Snapshot(), e => e.Message ==
|
||||
"Paletti del prodotto applicati dalla pagina Prodotti (scheda): prezzo min 1,00 EUR, max 7,00 EUR, puntate max 12, fascia oraria di nuovo come il prodotto");
|
||||
Assert.Equal((2, 0, 0), monitor.PreviewProductLimits());
|
||||
Assert.Equal(0, monitor.ApplyProductLimits());
|
||||
|
||||
// Una fascia oraria scritta sull'asta basta perché l'asta non abbia «già» i paletti del prodotto.
|
||||
a.QuietHoursOverride = false;
|
||||
Assert.Equal((2, 1, 0), monitor.PreviewProductLimits());
|
||||
Assert.Equal(1, monitor.ApplyProductLimits());
|
||||
Assert.Null(a.QuietHoursOverride);
|
||||
|
||||
// «Torna ai paletti del prodotto»: quell'asta sola, subito, fascia oraria compresa.
|
||||
products.Upsert(new ProductRecord { ProductKey = a.ProductKey, DisplayName = a.Name, MinPrice = 1, MaxPrice = 8, MaxBids = 12 });
|
||||
monitor.SetLimits(a.Id, 0, 3, 5, null, false);
|
||||
var (ok, _) = monitor.ReturnToProductLimits(a.Id);
|
||||
Assert.True(ok);
|
||||
Assert.Equal(8, a.MaxPrice);
|
||||
Assert.True(a.LimitsFromProduct);
|
||||
Assert.Null(a.QuietHoursOverride);
|
||||
Assert.Contains(a.Log.Snapshot(), e => e.Message.StartsWith("Tornata ai paletti del prodotto (scheda): prezzo min 1,00 EUR, max 8,00 EUR", StringComparison.Ordinal));
|
||||
Assert.Equal(7, b.MaxPrice); // l'altra resta com'era
|
||||
Assert.False(monitor.ReturnToProductLimits("nessuna").Ok);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
using System.Diagnostics;
|
||||
using BidooBidBot.Bidoo;
|
||||
using BidooBidBot.Net;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
internal static class Fixture
|
||||
{
|
||||
public static string Read(string name) =>
|
||||
File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", name));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// data.php è posizionale e non documentato: se cambia forma l'unico sintomo è uno stato
|
||||
/// sbagliato. Questi test fissano il contratto osservato sul campo (portati dal legacy).
|
||||
/// </summary>
|
||||
public class DataResponseParserTests
|
||||
{
|
||||
private const string Sample =
|
||||
"1764068200*[95216992;ON;1764068210;342;fedekikka2323;1," +
|
||||
"342;fedekikka2323;1764068204;3|341;chamorro1984;1764068194;1]";
|
||||
|
||||
[Fact]
|
||||
public void Legge_i_campi_principali()
|
||||
{
|
||||
var r = DataResponseParser.Parse("95216992", Sample, 50, 1000, "tizio");
|
||||
Assert.True(r.Success);
|
||||
var s = r.State!;
|
||||
Assert.Equal("95216992", s.AuctionId);
|
||||
Assert.Equal(3.42, s.Price, 3);
|
||||
Assert.Equal("fedekikka2323", s.LastBidder);
|
||||
Assert.Equal(AuctionStatus.Running, s.Status);
|
||||
Assert.False(s.IsMyBid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Espone_gli_istanti_assoluti_del_server()
|
||||
{
|
||||
var r = DataResponseParser.Parse("1", Sample, 50, 1000, null);
|
||||
Assert.Equal(1764068200, r.State!.ServerUnixSeconds);
|
||||
Assert.Equal(1764068210, r.State.ExpiryUnixSeconds);
|
||||
Assert.Equal(10, r.State.Timer, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Riconosce_le_puntate_dell_utente_senza_badare_alle_maiuscole()
|
||||
{
|
||||
var r = DataResponseParser.Parse("1", Sample, 50, 1000, "FEDEKIKKA2323");
|
||||
Assert.True(r.State!.IsMyBid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Legge_lo_storico_con_tipo_e_prezzo()
|
||||
{
|
||||
var history = DataResponseParser.Parse("1", Sample, 50, 1000, "chamorro1984").State!.RecentBidsHistory!;
|
||||
Assert.Equal(2, history.Count);
|
||||
Assert.Equal(3.42m, history[0].Price);
|
||||
Assert.Equal(BidHistoryEntry.TypeAuto, history[0].BidType);
|
||||
Assert.False(history[0].IsMyBid);
|
||||
Assert.Equal(BidHistoryEntry.TypeManual, history[1].BidType);
|
||||
Assert.True(history[1].IsMyBid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void I_codici_del_tipo_sono_quelli_della_pagina_d_asta_di_Bidoo()
|
||||
{
|
||||
// Come liveauction_it.js: 1 e 2 manuale, 3 e 4 automatica, 5 Killer, 6 Shock, 7 automatica
|
||||
// con scudo; il codice 2 finiva «non dichiarato» fino alla 1.1.0.
|
||||
const string body = "1790630194*[99110113;ON;1790630198;16;mirotaglio;2,16;mirotaglio;1790630190;2|15;tumelato;1790630186;4|" +
|
||||
"14;bea;1790630180;5|13;leo;1790630176;6|12;ada;1790630170;7|11;zeno;1790630164;9]";
|
||||
var s = DataResponseParser.Parse("99110113", body, 50, 1000, null).State!;
|
||||
Assert.Equal(new[] { "Manuale", "Auto", "Killer", "Shock", "Auto", "" }, s.RecentBidsHistory!.Select(b => b.BidType).ToArray());
|
||||
// Il tipo della puntata in testa sta anche nel nucleo (sesto campo).
|
||||
Assert.Equal(BidHistoryEntry.TypeManual, s.LastBidType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_tipo_della_puntata_in_testa_viene_dal_nucleo()
|
||||
{
|
||||
Assert.Equal(BidHistoryEntry.TypeManual, DataResponseParser.Parse("95755813", Fixture.Read("data-in-corso.txt"), 50, 1000, null).State!.LastBidType);
|
||||
Assert.Equal(BidHistoryEntry.TypeUnknown, DataResponseParser.Parse("95760550", Fixture.Read("data-vergine.txt"), 50, 1000, null).State!.LastBidType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rispetta_il_tetto_sullo_storico()
|
||||
{
|
||||
var r = DataResponseParser.Parse("1", Sample, 50, 1000, null, maxHistoryEntries: 1);
|
||||
Assert.Single(r.State!.RecentBidsHistory!);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("senza-asterisco")]
|
||||
[InlineData("1764068200*nessuna-parentesi")]
|
||||
[InlineData("1764068200*[troppo;pochi;campi]")]
|
||||
public void Rifiuta_le_risposte_malformate_senza_eccezioni(string bad)
|
||||
{
|
||||
var r = DataResponseParser.Parse("1", bad, 50, 1000, null);
|
||||
Assert.False(r.Success);
|
||||
Assert.False(string.IsNullOrEmpty(r.Error));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ignora_i_campi_extra_prima_dell_asterisco()
|
||||
{
|
||||
var r = DataResponseParser.Parse("1", "1764068200|altro|ancora*[1;ON;1764068210;342;tizio]", 50, 1000, null);
|
||||
Assert.True(r.Success);
|
||||
Assert.Equal(1764068200, r.State!.ServerUnixSeconds);
|
||||
Assert.Null(r.State.RecentBidsHistory);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("ON", true, false, 10, AuctionStatus.Running)]
|
||||
[InlineData("ON", true, true, 10, AuctionStatus.Running)]
|
||||
[InlineData("ON", false, false, 10, AuctionStatus.Pending)]
|
||||
[InlineData("ON", false, false, 3600, AuctionStatus.Scheduled)]
|
||||
[InlineData("OFF", true, true, 0, AuctionStatus.EndedWon)]
|
||||
[InlineData("OFF", true, false, 0, AuctionStatus.EndedLost)]
|
||||
[InlineData("OFF", false, false, 0, AuctionStatus.Closed)]
|
||||
[InlineData("STOP", true, false, 0, AuctionStatus.Paused)]
|
||||
[InlineData("BOH", false, false, 0, AuctionStatus.Unknown)]
|
||||
public void Traduce_lo_stato_del_server(string api, bool hasWinner, bool iAmWinner, double timer, AuctionStatus expected)
|
||||
{
|
||||
Assert.Equal(expected, DataResponseParser.DetermineStatus(api, hasWinner, iAmWinner, timer));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Una_vittoria_richiede_che_il_vincitore_sia_l_utente()
|
||||
{
|
||||
Assert.Equal(AuctionStatus.EndedWon, DataResponseParser.Parse("1", "100*[1;OFF;100;500;ioStesso]", 10, 0, "ioStesso").State!.Status);
|
||||
Assert.Equal(AuctionStatus.EndedLost, DataResponseParser.Parse("1", "100*[1;OFF;100;500;unAltro]", 10, 0, "ioStesso").State!.Status);
|
||||
}
|
||||
|
||||
// ── Risposte vere registrate dal server (Fixtures) ──────────────────
|
||||
|
||||
[Fact]
|
||||
public void Asta_conclusa_con_le_puntate_del_vincitore()
|
||||
{
|
||||
var r = DataResponseParser.Parse("95235087", Fixture.Read("data-conclusa.txt"), 50, 0, null);
|
||||
Assert.True(r.Success);
|
||||
Assert.Equal("redberri", r.State!.LastBidder);
|
||||
Assert.Equal(8.38, r.State.Price, 2);
|
||||
Assert.Equal(AuctionStatus.EndedLost, r.State.Status);
|
||||
Assert.Equal(0, r.State.WinnerBidsPaid);
|
||||
Assert.Equal(25, r.State.WinnerBidsFree);
|
||||
Assert.Equal(25, r.State.WinnerBidsTotal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_puntata_piu_recente_non_si_perde()
|
||||
{
|
||||
var r = DataResponseParser.Parse("95755813", Fixture.Read("data-in-corso.txt"), 50, 0, null);
|
||||
var history = r.State!.RecentBidsHistory!;
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal("kikisi9", history[0].Username);
|
||||
Assert.Equal(0.04m, history[0].Price);
|
||||
Assert.Null(r.State.WinnerBidsTotal);
|
||||
Assert.Equal(AuctionStatus.Running, r.State.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unasta_senza_puntate_si_legge_lo_stesso()
|
||||
{
|
||||
var r = DataResponseParser.Parse("95760550", Fixture.Read("data-vergine.txt"), 50, 0, null);
|
||||
Assert.True(r.Success);
|
||||
Assert.Equal("", r.State!.LastBidder);
|
||||
Assert.Null(r.State.RecentBidsHistory);
|
||||
Assert.Equal(AuctionStatus.Pending, r.State.Status);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("0|25|0|0|0|0|", 0, 25)]
|
||||
[InlineData("371|0|0|0|0|0|", 371, 0)]
|
||||
[InlineData("12|3", 12, 3)]
|
||||
public void Legge_pagate_e_gratis(string tail, int paid, int free)
|
||||
{
|
||||
var (p, f) = DataResponseParser.ParseWinnerBids(tail);
|
||||
Assert.Equal(paid, p);
|
||||
Assert.Equal(free, f);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("42")]
|
||||
[InlineData("x|y")]
|
||||
public void Una_coda_incomprensibile_non_inventa_numeri(string tail)
|
||||
{
|
||||
var (p, f) = DataResponseParser.ParseWinnerBids(tail);
|
||||
Assert.True(p is null || f is null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_risposta_a_piu_aste_si_legge_riga_per_riga()
|
||||
{
|
||||
var list = DataResponseParser.ParseList(Fixture.Read("data-lista.txt"));
|
||||
Assert.Equal(3, list.Count);
|
||||
Assert.Equal("95216992", list[0].AuctionId);
|
||||
Assert.Equal(3.42, list[0].Price, 3);
|
||||
Assert.Equal(10, list[0].RemainingSeconds);
|
||||
Assert.Equal("OFF", list[1].Status);
|
||||
Assert.Equal("", list[2].LastBidder);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("<html><form action=\"login.php\">", true)]
|
||||
[InlineData("1764068200*[1;ON;1764068210;342;tizio]", false)]
|
||||
[InlineData("", false)]
|
||||
[InlineData("<html>manutenzione</html>", false)]
|
||||
public void Riconosce_la_pagina_di_login_al_posto_dei_dati(string body, bool expected)
|
||||
{
|
||||
Assert.Equal(expected, DataResponseParser.LooksLikeLoginPage(body));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>bid.php divide il saldo in pagate e gratuite (portato dal legacy).</summary>
|
||||
public class BidResponseTests
|
||||
{
|
||||
[Fact]
|
||||
public void Il_saldo_e_la_somma_di_pagate_e_gratuite()
|
||||
{
|
||||
var r = DataResponseParser.ParseBidResponse(Fixture.Read("bid-ok.txt"));
|
||||
Assert.True(r.Ok);
|
||||
Assert.Equal(927, r.PaidRemaining);
|
||||
Assert.Equal(480, r.FreeRemaining);
|
||||
Assert.Equal(1407, r.Remaining);
|
||||
Assert.Equal(8, r.UsedOnAuction);
|
||||
Assert.Null(r.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Una_risposta_corta_da_solo_il_totale_che_conosce()
|
||||
{
|
||||
var r = DataResponseParser.ParseBidResponse("ok|12");
|
||||
Assert.True(r.Ok);
|
||||
Assert.Equal(12, r.Remaining);
|
||||
Assert.Null(r.FreeRemaining);
|
||||
Assert.Null(r.UsedOnAuction);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("error|Timer scaduto<br>Riprova", "Timer scaduto")]
|
||||
[InlineData("no|Asta chiusa", "Asta chiusa")]
|
||||
[InlineData("", "risposta vuota")]
|
||||
[InlineData("qualcosa di strano", "non riconosciuta")]
|
||||
[InlineData("alive", "keep-alive")]
|
||||
public void Gli_errori_arrivano_puliti(string body, string expected)
|
||||
{
|
||||
var r = DataResponseParser.ParseBidResponse(body);
|
||||
Assert.False(r.Ok);
|
||||
Assert.Contains(expected, r.Error);
|
||||
Assert.DoesNotContain("<br>", r.Error);
|
||||
}
|
||||
}
|
||||
|
||||
public class AccountParserTests
|
||||
{
|
||||
private const string UserPage =
|
||||
"<html><head><script>BidooCnf.userObj.id = '6707664'; BidooCnf.userObj.username = 'utente_demo';</script></head>" +
|
||||
"<body><span id=\"divSaldoBidMobile\">1407</span> <span class=\"cbstotal\">15.00</span>" +
|
||||
"<p>una pagina abbastanza lunga da essere vera, con tanto testo in fondo per superare i cento caratteri</p></body></html>";
|
||||
|
||||
[Fact]
|
||||
public void La_pagina_del_conto_da_utente_saldo_e_credito()
|
||||
{
|
||||
var info = AccountParser.ParseUserPage(UserPage)!;
|
||||
Assert.Equal("6707664", info.UserId);
|
||||
Assert.Equal("utente_demo", info.Username);
|
||||
Assert.Equal(1407, info.RemainingBids);
|
||||
Assert.Equal(15.00, info.ShopCredit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Senza_dati_la_pagina_non_e_un_conto()
|
||||
{
|
||||
Assert.Null(AccountParser.ParseUserPage("<html>" + new string('x', 200) + "<a href=\"login.php\">Accedi</a></html>"));
|
||||
Assert.Null(AccountParser.ParseUserPage("corta"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("125", 125, null)]
|
||||
[InlineData("<span id=\"bids_count\">125</span>", 125, null)]
|
||||
[InlineData("utente_demo|1407|15.5|6707664", 1407, "utente_demo")]
|
||||
public void Il_saldo_leggero_ha_tre_formati(string body, int bids, string? user)
|
||||
{
|
||||
var info = AccountParser.ParseCreditsStatus(body)!;
|
||||
Assert.Equal(bids, info.RemainingBids);
|
||||
Assert.Equal(user, info.Username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("1", 1)]
|
||||
[InlineData(" 0 ", 0)]
|
||||
[InlineData("<html>login</html>", null)]
|
||||
[InlineData("", null)]
|
||||
public void Le_aste_da_confermare_distinguono_zero_da_non_lo_so(string body, int? expected)
|
||||
{
|
||||
Assert.Equal(expected, AccountParser.ParseAuctionsWon(body));
|
||||
}
|
||||
}
|
||||
|
||||
public class AuctionPageAndUrlTests
|
||||
{
|
||||
private const string Page = """
|
||||
<html><head><title>Buono Amazon 50 € - Bidoo</title></head><body>
|
||||
<img src="https://cdn.bidoo.com/products/f123.jpg">
|
||||
<span class="text-muted product-value"><span class="hidden-xs">Valore: </span><span class="product-value hidden-xs">50,00 €</span></span>
|
||||
<li>Spese di transazione: <span>1,00 €</span></li>
|
||||
<li>Limiti di vincita: <span>1 ogni 30 giorni</span></li>
|
||||
<div data-id-product="26283"></div>
|
||||
</body></html>
|
||||
""";
|
||||
|
||||
[Fact]
|
||||
public void La_pagina_dell_asta_da_valore_spese_e_limite()
|
||||
{
|
||||
var info = AuctionPageParser.Parse(Page)!;
|
||||
Assert.Equal("Buono Amazon 50 €", info.Name);
|
||||
Assert.Equal(50.00, info.BuyNowPrice);
|
||||
Assert.Equal(1.00, info.Shipping);
|
||||
Assert.Equal("1 ogni 30 giorni", info.WinLimit);
|
||||
Assert.Contains("/products/f123.jpg", info.ImageUrl);
|
||||
Assert.Equal(26283, info.ProductId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("85559716", "85559716", null)]
|
||||
[InlineData("https://it.bidoo.com/asta/buono-amazon-50-85559716", "85559716", "Buono Amazon 50")]
|
||||
[InlineData("https://it.bidoo.com/asta/85559716", "85559716", null)]
|
||||
[InlineData("https://it.bidoo.com/auction.php?a=Galaxy_S25_Ultra_81204324", "81204324", "Galaxy S25 Ultra")]
|
||||
public void L_indirizzo_da_id_e_nome(string input, string id, string? name)
|
||||
{
|
||||
var parsed = AuctionUrl.Parse(input)!.Value;
|
||||
Assert.Equal(id, parsed.AuctionId);
|
||||
Assert.Equal(name, parsed.ProductName);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("123")]
|
||||
[InlineData("https://example.com/asta/85559716")]
|
||||
[InlineData("non è un indirizzo")]
|
||||
public void Gli_indirizzi_sbagliati_si_rifiutano(string input)
|
||||
{
|
||||
Assert.Null(AuctionUrl.Parse(input));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Il listato del catalogo (portato dal legacy).</summary>
|
||||
public class CatalogPageParserTests
|
||||
{
|
||||
private const string Card = """
|
||||
<div id="divAsta85559716"
|
||||
class="live- auction- col-lg-2 col-md-3 col-sm-4 col-xs-6"
|
||||
data-id="85559716" data-url="474_Puntate_85559716" data-freq="5"
|
||||
data-biddable="1" data-level="0" data-type="0"
|
||||
data-credit="1" data-credit-value="474" data-id-product="26283">
|
||||
<div class="auction photo">
|
||||
<img class="img_small" src="https://cdn.example.com/products/f26283.jpg" width="160">
|
||||
<a href='auction.php?a=474_Puntate_85559716' class="name " title="">474 Puntate</a>
|
||||
</div>
|
||||
<div class="buynow-btn"><div class="btn-rapid buy-rapid-now">14,00 €</div></div>
|
||||
</div>
|
||||
""";
|
||||
|
||||
private const string SecondCard = """
|
||||
<div id="divAsta85559720" data-id="85559720" data-url="Frullatore_85559720"
|
||||
data-freq="10" data-credit="0" data-credit-value="0" data-id-product="4947">
|
||||
<a href='auction.php?a=Frullatore_85559720' class="name " title="">Frullatore Pro</a>
|
||||
</div>
|
||||
""";
|
||||
|
||||
private static string FirstPage() => $$"""
|
||||
{
|
||||
"status": "200",
|
||||
"content": [{{System.Text.Json.JsonSerializer.Serialize(Card)}}, {{System.Text.Json.JsonSerializer.Serialize(SecondCard)}}],
|
||||
"list": [85559716, 85559720],
|
||||
"auctions_attributes": {
|
||||
"85559716": {"data-url":"474_Puntate_85559716","data-freq":5,"data-credit":1,"data-credit-value":474,"data-id-product":26283},
|
||||
"85559720": {"data-url":"Frullatore_85559720","data-freq":10,"data-credit":0,"data-credit-value":0,"data-id-product":4947}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
private static string NextPage() => $$"""
|
||||
{
|
||||
"gc": [], "int": [],
|
||||
"list": [85559716],
|
||||
"items": [{{System.Text.Json.JsonSerializer.Serialize(Card)}}],
|
||||
"attributes": {
|
||||
"85559716": {"data-url":"474_Puntate_85559716","data-freq":5,"data-credit":1,"data-credit-value":474,"data-id-product":26283}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
[Fact]
|
||||
public void Legge_la_prima_pagina()
|
||||
{
|
||||
var page = CatalogPageParser.ParsePage(FirstPage())!;
|
||||
Assert.Equal(new[] { "85559716", "85559720" }, page.Ids);
|
||||
Assert.Equal(2, page.Auctions.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Legge_le_pagine_successive_con_gli_altri_nomi_di_campo()
|
||||
{
|
||||
var page = CatalogPageParser.ParsePage(NextPage())!;
|
||||
Assert.Single(page.Ids);
|
||||
Assert.Equal("474 Puntate", Assert.Single(page.Auctions).Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ricava_i_dati_della_scheda()
|
||||
{
|
||||
var a = CatalogPageParser.ParsePage(FirstPage())!.Auctions.Single(x => x.AuctionId == "85559716");
|
||||
Assert.Equal("474 Puntate", a.Name);
|
||||
Assert.Equal(5, a.TimerFrequency);
|
||||
Assert.True(a.IsCreditAuction);
|
||||
Assert.Equal(474, a.CreditValue);
|
||||
Assert.Equal(26283, a.ProductId);
|
||||
Assert.Equal(14.00m, a.BuyNowPrice);
|
||||
Assert.Equal("https://it.bidoo.com/auction.php?a=474_Puntate_85559716", a.Url);
|
||||
Assert.Contains("/products/f26283.jpg", a.ImageUrl);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Gli_attributi_hanno_la_meglio_sul_markup()
|
||||
{
|
||||
var body = """
|
||||
{"list": [1], "items": ["<div id=\"divAsta1\" data-id=\"1\" data-freq=\"99\" data-id-product=\"7\"></div>"],
|
||||
"attributes": {"1": {"data-freq": 5, "data-id-product": 26283, "data-url": "Cuffie_1"}}}
|
||||
""";
|
||||
var a = CatalogPageParser.ParsePage(body)!.Auctions.Single();
|
||||
Assert.Equal(5, a.TimerFrequency);
|
||||
Assert.Equal(26283, a.ProductId);
|
||||
Assert.Equal("https://it.bidoo.com/auction.php?a=Cuffie_1", a.Url);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("<div class=\"btn-rapid buy-rapid-now\">14,00 €</div>", 14.00)]
|
||||
[InlineData("<div class=\"buy-rapid-now\"><i class=\"fas fa-cart\"></i> 65,90 €</div>", 65.90)]
|
||||
[InlineData("<div class=\"buy-rapid-now\">200,00 €</div>", 200.00)]
|
||||
[InlineData("<div class=\"buy-rapid-now\">1.234,00 €</div>", 1234.00)]
|
||||
[InlineData("<div class=\"buy-rapid-now\">80 €</div>", 80)]
|
||||
public void Legge_il_prezzo_del_compra_subito(string markup, double expected)
|
||||
{
|
||||
var a = Assert.Single(CatalogPageParser.ParseAuctions($"<div id=\"divAsta9\" data-id=\"9\">{markup}</div>"));
|
||||
Assert.Equal((decimal)expected, a.BuyNowPrice);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Senza_compra_subito_il_prezzo_resta_ignoto()
|
||||
{
|
||||
Assert.Null(Assert.Single(CatalogPageParser.ParseAuctions("<div id=\"divAsta9\" data-id=\"9\">nessun riquadro</div>")).BuyNowPrice);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pagina_vuota_e_diversa_da_risposta_incomprensibile()
|
||||
{
|
||||
var end = CatalogPageParser.ParsePage("""{"gc":[],"int":[],"list":[],"items":[]}""")!;
|
||||
Assert.Empty(end.Ids);
|
||||
Assert.Empty(end.Auctions);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("<html>Manutenzione in corso</html>")]
|
||||
[InlineData("{\"status\":\"500\"}")]
|
||||
[InlineData("[1,2,3]")]
|
||||
public void Risposta_non_riconosciuta_restituisce_null(string body)
|
||||
{
|
||||
Assert.Null(CatalogPageParser.ParsePage(body));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Un_id_senza_scheda_resta_comunque_nell_elenco()
|
||||
{
|
||||
var page = CatalogPageParser.ParsePage("""{"list": [1, 2], "items": ["<div id=\"divAsta1\" data-id=\"1\"></div>"]}""")!;
|
||||
Assert.Equal(new[] { "1", "2" }, page.Ids);
|
||||
Assert.Single(page.Auctions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Le_entita_html5_nei_nomi_si_decodificano()
|
||||
{
|
||||
Assert.Equal("Cuffie - Pro + Max!", CatalogPageParser.DecodeHtml("Cuffie &dash; Pro + Max!"));
|
||||
Assert.Equal("Buono 5$ = 5 − sconto", CatalogPageParser.DecodeHtml("Buono 5$ = 5 − sconto"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Accetta_gli_id_scritti_come_stringa()
|
||||
{
|
||||
var page = CatalogPageParser.ParsePage("""{"list": ["85559716", 85559720], "items": []}""");
|
||||
Assert.Equal(new[] { "85559716", "85559720" }, page!.Ids);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Le_schede_ripetute_non_si_duplicano()
|
||||
{
|
||||
var body = $$"""
|
||||
{
|
||||
"list": [85559716, 85559716],
|
||||
"items": [{{System.Text.Json.JsonSerializer.Serialize(Card)}}, {{System.Text.Json.JsonSerializer.Serialize(Card)}}]
|
||||
}
|
||||
""";
|
||||
Assert.Single(CatalogPageParser.ParsePage(body)!.Auctions);
|
||||
}
|
||||
}
|
||||
|
||||
public class ReferencesTests
|
||||
{
|
||||
[Fact]
|
||||
public void Un_file_scritto_dalla_1_1_0_prende_i_codici_nuovi_del_tipo()
|
||||
{
|
||||
// I file di /config/riferimenti nati prima avevano solo bidTypeManual/bidTypeAuto.
|
||||
var r = BidooReferences.Parse("""{"parsing": {"bidTypeManual": "1", "bidTypeAuto": "3"}}""");
|
||||
Assert.Equal("Manuale", r.Parsing.BidTypeCodes["2"]);
|
||||
Assert.Equal("Auto", r.Parsing.BidTypeCodes["4"]);
|
||||
|
||||
// Un codice si corregge a mano senza toccare gli altri.
|
||||
var mine = BidooReferences.Parse("""{"parsing": {"bidTypeCodes": {"8": "Auto"}}}""");
|
||||
Assert.Equal("Auto", mine.Parsing.BidTypeCodes["8"]);
|
||||
Assert.Equal("Manuale", mine.Parsing.BidTypeCodes["1"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void I_valori_di_fabbrica_hanno_tutti_gli_indirizzi()
|
||||
{
|
||||
var r = BidooReferences.Default;
|
||||
Assert.Equal("https://it.bidoo.com", r.BaseUrl);
|
||||
Assert.Equal("https://it.bidoo.com/data.php?ALL=85559716&LISTID=0", r.Url(r.Endpoints.AuctionData, ("id", "85559716")));
|
||||
Assert.Equal("https://it.bidoo.com/bid.php?AID=85559716&sup=0&shock=0", r.Url(r.Endpoints.Bid, ("id", "85559716")));
|
||||
Assert.Equal("__stattrb", r.Recognizers.SessionCookie);
|
||||
Assert.Equal(60, r.Timing.PreCheckMs);
|
||||
Assert.Equal(3, r.Limits.BidLaneConnections);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_file_cambia_solo_le_voci_che_contiene()
|
||||
{
|
||||
var r = BidooReferences.Parse("""
|
||||
{
|
||||
// commento ammesso
|
||||
"baseUrl": "http://127.0.0.1:5555",
|
||||
"endpoints": { "bid": "/altro.php?id={id}" },
|
||||
}
|
||||
""");
|
||||
Assert.Equal("http://127.0.0.1:5555", r.BaseUrl);
|
||||
Assert.Equal("/altro.php?id={id}", r.Endpoints.Bid);
|
||||
Assert.Equal("/data.php?ALL={id}&LISTID=0", r.Endpoints.AuctionData);
|
||||
Assert.NotEmpty(r.Recognizers.RemainingBids);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Un_espressione_sbagliata_non_fa_cadere_nulla()
|
||||
{
|
||||
Assert.Null(BidooReferences.FirstGroup("testo", "([a-z"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_file_si_rilegge_a_caldo_e_un_file_rotto_lascia_il_precedente()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
using var provider = new ReferencesProvider(dir.Path, null, watch: false);
|
||||
Assert.True(File.Exists(provider.FilePath));
|
||||
Assert.Equal("https://it.bidoo.com", provider.Current.BaseUrl);
|
||||
}
|
||||
}
|
||||
|
||||
public class NetTests
|
||||
{
|
||||
[Fact]
|
||||
public void I_cookie_rinnovati_dal_server_sostituiscono_i_vecchi()
|
||||
{
|
||||
var merged = CookieText.Merge("__stattrb=vecchio; PHPSESSID=abc; x=1",
|
||||
new[] { "__stattrb=nuovo; path=/; HttpOnly", "x=deleted; expires=Thu, 01 Jan 1970 00:00:00 GMT", "y=2; path=/" });
|
||||
Assert.Equal("__stattrb=nuovo; PHPSESSID=abc; y=2", merged);
|
||||
Assert.True(CookieText.Contains(merged, "__stattrb"));
|
||||
Assert.False(CookieText.Contains(merged, "x"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_token_bucket_lascia_una_riserva_al_polling()
|
||||
{
|
||||
var bucket = new TokenBucket(10) { BackgroundReserve = 0.5 }; // capacità 10, riserva 5
|
||||
var backgroundFree = 0;
|
||||
for (var i = 0; i < 10; i++) if (bucket.Reserve(background: true) == 0) backgroundFree++;
|
||||
Assert.True(backgroundFree <= 5);
|
||||
|
||||
// Il polling trova comunque gettoni subito.
|
||||
Assert.Equal(0, new TokenBucket(10).Reserve(background: false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Senza_limite_non_si_aspetta_mai()
|
||||
{
|
||||
var bucket = new TokenBucket(0);
|
||||
for (var i = 0; i < 1000; i++) Assert.Equal(0, bucket.Reserve(background: true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Le_latenze_danno_i_percentili()
|
||||
{
|
||||
var stats = new LatencyStats(100);
|
||||
for (var i = 1; i <= 100; i++) stats.Add(i);
|
||||
Assert.Equal(50, stats.Percentile(0.5));
|
||||
Assert.Equal(99, stats.Percentile(0.99));
|
||||
Assert.Equal(50.5, stats.Average());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using BidooBidBot.Bidoo;
|
||||
using BidooBidBot.Data;
|
||||
using BidooBidBot.Engine;
|
||||
using BidooBidBot.Ml;
|
||||
using BidooBidBot.Products;
|
||||
using BidooBidBot.Settings;
|
||||
using BidooBidBot.Strategy;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
using BidooBidBot.Bidoo;
|
||||
using BidooBidBot.Config;
|
||||
using BidooBidBot.Data;
|
||||
using BidooBidBot.Logging;
|
||||
using BidooBidBot.Ml;
|
||||
using BidooBidBot.Net;
|
||||
using BidooBidBot.Session;
|
||||
using BidooBidBot.Session.Cdp;
|
||||
using BidooBidBot.Settings;
|
||||
using BidooBidBot.Simulator;
|
||||
using BidooBidBot.Telegram;
|
||||
using BidooBidBot.Web;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.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("Bidoo BidBot, 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("Bidoo BidBot, 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")]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using BidooBidBot.Settings;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>Le impostazioni che valgono solo dal prossimo avvio (<see cref="SettingsStore.RestartRequired"/>).</summary>
|
||||
public class SettingsRestartTests
|
||||
{
|
||||
private static Dictionary<string, JsonElement> Patch(string json) =>
|
||||
JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json)!;
|
||||
|
||||
private const string StartupKey = nameof(AppSettings.LearningBootstrapSecondsPerStart);
|
||||
|
||||
[Fact]
|
||||
public void Ogni_chiave_dell_elenco_del_riavvio_e_un_impostazione_vera_con_la_sua_etichetta()
|
||||
{
|
||||
Assert.NotEmpty(SettingsStore.RestartRequired);
|
||||
foreach (var key in SettingsStore.RestartRequired)
|
||||
{
|
||||
var prop = typeof(AppSettings).GetProperty(key, BindingFlags.Public | BindingFlags.Instance);
|
||||
Assert.True(prop is { CanRead: true, CanWrite: true }, $"{key} non è una proprietà di AppSettings");
|
||||
Assert.NotEqual(nameof(AppSettings.SettingsSchemaVersion), key);
|
||||
|
||||
var label = SettingsStore.RestartLabel(key);
|
||||
Assert.False(string.IsNullOrWhiteSpace(label));
|
||||
Assert.NotEqual(key, label);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lo_studio_all_avvio_vale_dal_prossimo_riavvio_e_il_resto_subito()
|
||||
{
|
||||
Assert.Contains(StartupKey, SettingsStore.RestartRequired);
|
||||
// Riapplicate a ogni salvataggio (Bot.ApplyLogSettings e Bot.OnSettingsChanged): non chiedono il riavvio.
|
||||
Assert.DoesNotContain(nameof(AppSettings.MaxLogLinesPerAuction), SettingsStore.RestartRequired);
|
||||
Assert.DoesNotContain(nameof(AppSettings.MaxGlobalLogLines), SettingsStore.RestartRequired);
|
||||
Assert.DoesNotContain(nameof(AppSettings.MaxRequestsPerSecond), SettingsStore.RestartRequired);
|
||||
// L'etichetta per una chiave fuori elenco è la chiave stessa.
|
||||
Assert.Equal("DailyBudgetEuro", SettingsStore.RestartLabel("DailyBudgetEuro"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Il_salvataggio_segnala_le_chiavi_che_chiedono_il_riavvio()
|
||||
{
|
||||
var store = new SettingsStore(null, null);
|
||||
|
||||
var mixed = await store.SaveAsync(Patch($$"""{"{{StartupKey}}": 300, "DailyBudgetEuro": 5}"""));
|
||||
Assert.True(mixed.Ok);
|
||||
Assert.Equal(new[] { StartupKey }, mixed.RestartKeys);
|
||||
Assert.Equal(300, store.Current.LearningBootstrapSecondsPerStart);
|
||||
Assert.Equal(2, mixed.Changes.Count);
|
||||
|
||||
// Solo chiavi che valgono subito: nessun avviso.
|
||||
var live = await store.SaveAsync(Patch("""{"DailyBudgetEuro": 7, "MaxLogLinesPerAuction": 800}"""));
|
||||
Assert.True(live.Ok);
|
||||
Assert.Empty(live.RestartKeys);
|
||||
|
||||
// Lo stesso valore di prima non è una modifica: niente da segnalare.
|
||||
var same = await store.SaveAsync(Patch($$"""{"{{StartupKey}}": 300}"""));
|
||||
Assert.True(same.Ok);
|
||||
Assert.Empty(same.Changes);
|
||||
Assert.Empty(same.RestartKeys);
|
||||
|
||||
// Un salvataggio rifiutato non segnala nulla.
|
||||
var bad = await store.SaveAsync(Patch($$"""{"{{StartupKey}}": "tanto"}"""));
|
||||
Assert.False(bad.Ok);
|
||||
Assert.Empty(bad.RestartKeys);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Le_chiavi_cambiate_si_confrontano_dopo_la_normalizzazione()
|
||||
{
|
||||
var before = new AppSettings();
|
||||
var after = SettingsStore.Clone(before);
|
||||
after.DailyBudgetEuro = 12;
|
||||
Assert.Empty(SettingsStore.RestartKeysChanged(before, after));
|
||||
|
||||
after.LearningBootstrapSecondsPerStart = 5; // sotto il minimo: diventa 10, sempre diverso da 120
|
||||
SettingsStore.Normalize(after);
|
||||
Assert.Equal(new[] { StartupKey }, SettingsStore.RestartKeysChanged(before, after));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_messaggio_elenca_le_etichette_della_pagina()
|
||||
{
|
||||
var msg = SettingsStore.RestartMessage(new[] { StartupKey });
|
||||
Assert.StartsWith("Salvato. Queste modifiche valgono dal prossimo riavvio: ", msg);
|
||||
Assert.Contains("Studio all'avvio (secondi)", msg);
|
||||
Assert.DoesNotContain(StartupKey, msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,837 @@
|
||||
using BidooBidBot.Bidoo;
|
||||
using BidooBidBot.Data;
|
||||
using BidooBidBot.Engine;
|
||||
using BidooBidBot.Ml;
|
||||
using BidooBidBot.Products;
|
||||
using BidooBidBot.Settings;
|
||||
using BidooBidBot.Strategy;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>Dati dell'apprendimento in memoria, per provare servizio e strategia senza PostgreSQL.</summary>
|
||||
public sealed class MemoryLearningData : ILearningData
|
||||
{
|
||||
public Dictionary<string, TrainingReader.Session> Sessions { get; } = new();
|
||||
public HashSet<string> Learned { get; } = new();
|
||||
public Dictionary<string, string> Reasons { get; } = new();
|
||||
public List<(double PWin, string Outcome)> Own { get; } = new();
|
||||
|
||||
/// <summary>Esiti delle decisioni registrate per asta (chiave del bandit, esito), per rifare il bandit.</summary>
|
||||
public Dictionary<string, List<(string ContextKey, string Outcome)>> Outcomes { get; } = new();
|
||||
|
||||
/// <summary>Se vero, leggere un'asta da studiare fallisce: lo studio si ferma con un errore.</summary>
|
||||
public bool FailLoad { get; set; }
|
||||
|
||||
public Task FlushAsync() => Task.CompletedTask;
|
||||
public Task<List<string>> PendingAuctionIdsAsync() => Task.FromResult(Sessions.Keys.Where(k => !Learned.Contains(k)).ToList());
|
||||
public Task<int> PendingCountAsync() => Task.FromResult(Sessions.Keys.Count(k => !Learned.Contains(k)));
|
||||
public Task<List<string>> ClosedAuctionIdsAsync(int max) => Task.FromResult(Sessions.Keys.ToList());
|
||||
public Task<TrainingReader.Session?> LoadSessionAsync(string id, string? me) =>
|
||||
FailLoad ? throw new InvalidOperationException("database non raggiungibile") : Task.FromResult(Sessions.GetValueOrDefault(id));
|
||||
public Task<bool> IsLearnedAsync(string id) => Task.FromResult(Learned.Contains(id));
|
||||
public void MarkLearned(string id) => Learned.Add(id);
|
||||
public Task MarkAllUnlearnedAsync() { Learned.Clear(); return Task.CompletedTask; }
|
||||
public Task<List<(double PWin, string Outcome)>> OwnBidOutcomesAsync(string? id) => Task.FromResult(id == null ? Own.ToList() : new List<(double, string)>());
|
||||
public Task<List<(string ContextKey, string Outcome)>> DecisionOutcomesAsync(string id) =>
|
||||
Task.FromResult(Outcomes.TryGetValue(id, out var rows) ? rows.ToList() : new List<(string, string)>());
|
||||
public Task<List<string>> AuctionsWithDecisionOutcomesAsync() => Task.FromResult(Outcomes.Keys.ToList());
|
||||
public Task<List<LossReasons.DecisionRow>> DecisionsForReasonAsync(string id) => Task.FromResult(new List<LossReasons.DecisionRow>());
|
||||
public Task<List<LossReasons.MyBidRow>> MyBidsForReasonAsync(string id) => Task.FromResult(new List<LossReasons.MyBidRow>());
|
||||
public void WriteLossReason(string id, string reason) => Reasons[id] = reason;
|
||||
public Task<List<ClosedAuctionRow>> ClosedAuctionsAsync(int max) => Task.FromResult(new List<ClosedAuctionRow>());
|
||||
public Task<List<(string Reason, int Count)>> LossReasonSummaryAsync(int days) => Task.FromResult(new List<(string, int)>());
|
||||
public Task<List<ShadowReport.Row>> ShadowRowsAsync(int days, bool? shadow, double cost) => Task.FromResult(new List<ShadowReport.Row>());
|
||||
}
|
||||
|
||||
internal sealed class ListLedger : IRiskLedger
|
||||
{
|
||||
public List<(string Kind, double Amount)> Rows { get; } = new();
|
||||
public void Append(string kind, double amountEuro, string? auctionId, string? note) => Rows.Add((kind, amountEuro));
|
||||
}
|
||||
|
||||
/// <summary>Il gestore del rischio (portati dal legacy, senza database).</summary>
|
||||
public class RiskManagerTests
|
||||
{
|
||||
private static AuctionInfo Auction(string id, RunMode mode = RunMode.Active, int bids = 0) =>
|
||||
new(id) { Name = "Prova", Mode = mode, SessionBidCount = bids };
|
||||
|
||||
[Fact]
|
||||
public void Lo_stop_loss_porta_in_halt_e_l_halt_resta_dopo_il_riavvio()
|
||||
{
|
||||
var docs = new MemoryDocumentStore();
|
||||
var ledger = new ListLedger();
|
||||
var risk = new RiskManager(docs, ledger);
|
||||
var s = new AppSettings { DailyStopLossEuro = 1.00 };
|
||||
|
||||
for (var i = 0; i < 4; i++) risk.NoteBidSpent("a", 0.20);
|
||||
Assert.True(risk.Authorize(Auction("a"), s, 0.20).Allowed);
|
||||
risk.NoteBidSpent("a", 0.20);
|
||||
Assert.False(risk.Authorize(Auction("a"), s, 0.20).Allowed);
|
||||
Assert.True(risk.Halted);
|
||||
Assert.True(risk.Halt!.Automatic);
|
||||
|
||||
// Un nuovo gestore sugli stessi documenti (il riavvio) vede ancora l'HALT.
|
||||
var again = new RiskManager(docs, ledger);
|
||||
Assert.True(again.Halted);
|
||||
Assert.False(again.Authorize(Auction("a"), new AppSettings(), 0.20).Allowed);
|
||||
Assert.True(again.Resume());
|
||||
Assert.True(again.Authorize(Auction("a"), new AppSettings(), 0.20).Allowed);
|
||||
Assert.Contains(ledger.Rows, r => r.Kind == "halt");
|
||||
Assert.Contains(ledger.Rows, r => r.Kind == "resume");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Vincite_drawdown_e_tetto_del_giorno()
|
||||
{
|
||||
var risk = new RiskManager(new MemoryDocumentStore(), new ListLedger());
|
||||
for (var i = 0; i < 5; i++) risk.NoteBidSpent("a", 0.20);
|
||||
risk.NoteWin("a", 3.00, "vinta");
|
||||
var n = risk.Snapshot();
|
||||
Assert.Equal(1.00, n.TodaySpent, 6);
|
||||
Assert.Equal(2.00, n.Cumulative, 6);
|
||||
Assert.True(risk.Authorize(Auction("a"), new AppSettings { DailyStopLossEuro = 1.0 }, 0.2).Allowed);
|
||||
|
||||
var dd = new RiskManager(new MemoryDocumentStore(), new ListLedger());
|
||||
dd.NoteWin("a", 5.00, "vinta");
|
||||
dd.NoteBidSpent("b", 0.20);
|
||||
dd.NoteBidSpent("b", 0.20);
|
||||
Assert.True(dd.Authorize(Auction("b"), new AppSettings { MaxDrawdownEuro = 0.50 }, 0.2).Allowed);
|
||||
dd.NoteBidSpent("b", 0.20);
|
||||
Assert.False(dd.Authorize(Auction("b"), new AppSettings { MaxDrawdownEuro = 0.50 }, 0.2).Allowed);
|
||||
|
||||
var budget = new RiskManager(new MemoryDocumentStore(), new ListLedger());
|
||||
budget.NoteBidSpent("a", 0.20);
|
||||
budget.NoteBidSpent("a", 0.20);
|
||||
Assert.False(budget.Authorize(Auction("a"), new AppSettings { DailyBudgetEuro = 0.50 }, 0.20).Allowed);
|
||||
Assert.False(budget.Halted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Le_aste_in_gioco_insieme_hanno_un_tetto()
|
||||
{
|
||||
var risk = new RiskManager(new MemoryDocumentStore(), new ListLedger());
|
||||
var all = new List<AuctionInfo> { Auction("a", bids: 3), Auction("b", bids: 1), Auction("c"), Auction("d", RunMode.Watch, bids: 9) };
|
||||
var s = new AppSettings { MaxConcurrentActiveAuctions = 2 };
|
||||
Assert.False(risk.Authorize(all[2], s, 0.2, all).Allowed);
|
||||
Assert.True(risk.Authorize(all[0], s, 0.2, all).Allowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_giorno_nuovo_azzera_la_spesa_del_giorno()
|
||||
{
|
||||
var now = new DateTime(2026, 9, 26, 23, 50, 0);
|
||||
var risk = new RiskManager(new MemoryDocumentStore(), new ListLedger(), () => now);
|
||||
risk.NoteBidSpent("a", 0.40);
|
||||
Assert.Equal(0.40, risk.Snapshot().TodaySpent, 6);
|
||||
now = now.AddMinutes(20);
|
||||
Assert.Equal(0, risk.Snapshot().TodaySpent, 6);
|
||||
Assert.Equal(-0.40, risk.Snapshot().Cumulative, 6);
|
||||
}
|
||||
}
|
||||
|
||||
public class BiddingHoursAndCleanupTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(0, true)] [InlineData(9, true)] [InlineData(10, false)] [InlineData(23, false)]
|
||||
public void La_fascia_0_10(int hour, bool quiet) => Assert.Equal(quiet, BiddingHours.IsQuiet(hour, 0, 10));
|
||||
|
||||
[Fact]
|
||||
public void Mezzanotte_ore_fuori_scala_e_filtro_spento()
|
||||
{
|
||||
Assert.True(BiddingHours.IsQuiet(23, 22, 6));
|
||||
Assert.False(BiddingHours.IsQuiet(6, 22, 6));
|
||||
for (var h = 0; h < 24; h++) Assert.False(BiddingHours.IsQuiet(h, 3, 3));
|
||||
Assert.Equal(BiddingHours.IsQuiet(1, 0, 10), BiddingHours.IsQuiet(25, 0, 10));
|
||||
Assert.Contains("00:00-10:00", BiddingHours.Explanation(0, 10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_pulizia_trattiene_cio_che_e_costato()
|
||||
{
|
||||
var o = new FinishedAuctionCleanup.Options();
|
||||
Assert.True(FinishedAuctionCleanup.Decide(true, false, 0, false, o).Remove);
|
||||
Assert.False(FinishedAuctionCleanup.Decide(false, false, 0, false, o).Remove);
|
||||
Assert.Contains("12 puntate", FinishedAuctionCleanup.Decide(true, false, 12, false, o).Reason);
|
||||
Assert.Contains("vinta", FinishedAuctionCleanup.Decide(true, true, 30, false, o).Reason);
|
||||
Assert.Contains("Attiva", FinishedAuctionCleanup.Decide(true, false, 0, true, o).Reason);
|
||||
Assert.False(FinishedAuctionCleanup.Decide(true, false, 0, false, new FinishedAuctionCleanup.Options { Enabled = false }).Remove);
|
||||
}
|
||||
}
|
||||
|
||||
public class ProductTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("SMARTPHONE XY ", "smartphone xy")]
|
||||
[InlineData("Macchina Caffè Espresso", "macchina caffe espresso")]
|
||||
[InlineData("Cuffie Wireless (Nero)", "cuffie wireless")]
|
||||
[InlineData("Set 24 Pennelli Make-Up", "set 24 pennelli make up")]
|
||||
[InlineData("Buono Amazon 50 €", "buono amazon 50")]
|
||||
public void La_chiave_prodotto_normalizza(string name, string key) => Assert.Equal(key, ProductKey.From(name));
|
||||
|
||||
[Fact]
|
||||
public void I_numeri_distinguono_i_modelli() =>
|
||||
Assert.NotEqual(ProductKey.From("PowerBank 20000"), ProductKey.From("PowerBank 10000"));
|
||||
|
||||
[Fact]
|
||||
public void Le_regole_del_prodotto_vincono_sui_predefiniti()
|
||||
{
|
||||
var s = new AppSettings { DefaultMaxPrice = 20, DefaultMaxClicks = 50, AutoAddNewAuctionState = "Osserva" };
|
||||
var none = ProductRules.Resolve(null, s, autoAdded: true);
|
||||
Assert.Equal(20, none.MaxPrice);
|
||||
Assert.Equal(RunMode.Watch, none.Mode);
|
||||
|
||||
var p = new ProductRecord { ProductKey = "x", MaxPrice = 8, MaxBids = 0, AutoState = "Attiva" };
|
||||
var own = ProductRules.Resolve(p, s, autoAdded: true);
|
||||
Assert.Equal(8, own.MaxPrice);
|
||||
Assert.Equal(0, own.MaxBids); // lo zero esplicito è una scelta vera
|
||||
Assert.Equal(RunMode.Active, own.Mode);
|
||||
Assert.Equal(RunMode.Watch, ProductRules.ParseMode("boh"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void I_paletti_scritti_vincono_sui_calcolati_che_vincono_sui_predefiniti()
|
||||
{
|
||||
var s = new AppSettings { DefaultMaxPrice = 20, DefaultMaxClicks = 50 };
|
||||
var computed = new ProductAdvice.Advice(true, 6.5, 40, 1.2, 3, 3.5, 85, false, false, 30, "calcolati");
|
||||
|
||||
var fromHistory = ProductRules.Resolve(null, s, autoAdded: true, computed);
|
||||
Assert.Equal(1.2, fromHistory.MinPrice);
|
||||
Assert.Equal(6.5, fromHistory.MaxPrice);
|
||||
Assert.Equal(40, fromHistory.MaxBids);
|
||||
Assert.Equal("calcolati", fromHistory.Source);
|
||||
Assert.True(fromHistory.FromProduct);
|
||||
|
||||
// Un paletto scritto sulla scheda vince solo per il suo campo.
|
||||
var p = new ProductRecord { ProductKey = "x", MaxPrice = 5 };
|
||||
var mixed = ProductRules.Resolve(p, s, autoAdded: true, computed);
|
||||
Assert.Equal(5, mixed.MaxPrice);
|
||||
Assert.Equal(40, mixed.MaxBids);
|
||||
Assert.Equal(1.2, mixed.MinPrice);
|
||||
Assert.Equal("scheda e calcolati", mixed.Source);
|
||||
|
||||
// Senza storico: i predefiniti, minimo a zero.
|
||||
var none = ProductRules.Resolve(null, s, autoAdded: true, new ProductAdvice.Advice(false, null, null, 0, 0, 0, 0, false, false, 2, "pochi dati"));
|
||||
Assert.Equal(0, none.MinPrice);
|
||||
Assert.Equal(20, none.MaxPrice);
|
||||
Assert.Equal("predefiniti", none.Source);
|
||||
|
||||
// Un minimo sopra il massimo fermerebbe tutto: vince il massimo.
|
||||
var wrong = ProductRules.Resolve(new ProductRecord { ProductKey = "y", MinPrice = 9, MaxPrice = 4 }, s, autoAdded: false);
|
||||
Assert.Equal(0, wrong.MinPrice);
|
||||
|
||||
// Il minimo predefinito vale solo senza uno scritto o calcolato.
|
||||
var withDefault = new AppSettings { DefaultMaxPrice = 20, DefaultMinPrice = 0.5 };
|
||||
Assert.Equal(0.5, ProductRules.Resolve(null, withDefault, autoAdded: true).MinPrice);
|
||||
Assert.Equal(1.2, ProductRules.Resolve(null, withDefault, autoAdded: true, computed).MinPrice);
|
||||
Assert.Equal(2, ProductRules.Resolve(new ProductRecord { ProductKey = "z", MinPrice = 2 }, withDefault, autoAdded: true, computed).MinPrice);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_valore_reale_scritto_vince_e_abilita_la_copertura()
|
||||
{
|
||||
Assert.Equal(11, ProductRules.ValueOf(null, 11));
|
||||
Assert.False(ProductRules.HasExplicitValue(new ProductRecord()));
|
||||
var p = new ProductRecord { MarketValue = 9.5 };
|
||||
Assert.Equal(9.5, ProductRules.ValueOf(p, 11));
|
||||
Assert.True(ProductRules.HasExplicitValue(p));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void L_orizzonte_e_l_asta_gia_cominciata()
|
||||
{
|
||||
var s = new AppSettings { AutoAddMaxStartMinutes = 60 };
|
||||
Assert.Equal(3600, ProductRules.HorizonSeconds(null, s));
|
||||
Assert.Equal(0, ProductRules.HorizonSeconds(new ProductRecord { HorizonMinutes = 0 }, s));
|
||||
Assert.Equal(180 * 60, ProductRules.HorizonSeconds(new ProductRecord { HorizonMinutes = 180 }, s));
|
||||
Assert.False(ProductRules.HasStarted(new CatalogAuction { CurrentPrice = 0.01m }));
|
||||
Assert.True(ProductRules.HasStarted(new CatalogAuction { LastBidder = "tizio" }));
|
||||
Assert.True(ProductRules.HasStarted(new CatalogAuction { CurrentPrice = 0.05m }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void I_limiti_consigliati_seguono_la_copertura_e_il_budget()
|
||||
{
|
||||
var closes = new List<double>();
|
||||
for (var i = 0; i < 100; i++) closes.Add(0.5 + i * 0.05); // 0,50 .. 5,45
|
||||
var input = new ProductAdvice.Input(closes, Enumerable.Range(10, 50).ToList(), 50, 1, 25, 0.13, 10, 0.85, 0.10);
|
||||
var advice = ProductAdvice.Suggest(input);
|
||||
Assert.True(advice.HasAdvice);
|
||||
Assert.InRange(advice.MaxPrice!.Value, 4.5, 4.8);
|
||||
Assert.InRange(advice.CoverageReached, 84, 87);
|
||||
Assert.NotNull(advice.MaxBids);
|
||||
Assert.Contains("aste concluse", advice.Explanation);
|
||||
|
||||
var tight = ProductAdvice.Suggest(input with { Value = 5, MaxBids = 40 });
|
||||
Assert.True(tight.LimitedByBudget);
|
||||
|
||||
Assert.False(ProductAdvice.Suggest(input with { FinalPrices = closes.Take(3).ToList() }).HasAdvice);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Un_budget_esaurito_ferma_le_puntate_invece_di_togliere_il_limite()
|
||||
{
|
||||
var closes = new List<double>();
|
||||
for (var i = 0; i < 100; i++) closes.Add(0.5 + i * 0.05);
|
||||
// Valore 5 € + 10%, meno 40 puntate da 0,13 € e 1 € di spedizione: −0,70 €, niente per il prezzo.
|
||||
var input = new ProductAdvice.Input(closes, Enumerable.Range(10, 50).ToList(), 5, 1, 40, 0.13, 10, 0.85, 0.10);
|
||||
var advice = ProductAdvice.Suggest(input);
|
||||
Assert.True(advice.HasAdvice);
|
||||
Assert.Equal(ProductAdvice.StopAllMaxPrice, advice.MaxPrice);
|
||||
Assert.True(advice.LimitedByBudget);
|
||||
Assert.True(advice.NotWorthwhile);
|
||||
Assert.Contains("Il budget è esaurito", advice.Explanation);
|
||||
Assert.Contains("0,01 €", advice.Explanation);
|
||||
|
||||
// Sull'asta nuova e sulla scheda vale 0,01, non «nessun limite»; il minimo sopra il massimo sparisce.
|
||||
var s = new AppSettings { DefaultMaxPrice = 0, DefaultMaxClicks = 0 };
|
||||
var resolved = ProductRules.Resolve(null, s, autoAdded: true, advice);
|
||||
Assert.Equal(0.01, resolved.MaxPrice);
|
||||
Assert.Equal(0, resolved.MinPrice);
|
||||
Assert.Equal(0.01, LimitsRecompute.Values(advice).MaxPrice);
|
||||
|
||||
// La strategia allora non punta: il prezzo è oltre il massimo.
|
||||
var docs = new MemoryDocumentStore();
|
||||
var strategy = new BidStrategy(new RiskManager(docs, new ListLedger()), new LearningService(docs, new MemoryLearningData(), () => s, null),
|
||||
new ProductStore(null), () => new AccountBalance(1407, 927, 480));
|
||||
var auction = new AuctionInfo("1") { Name = "Buono", ProductKey = "buono", BuyNowPrice = 5, Mode = RunMode.Active, MaxPrice = resolved.MaxPrice };
|
||||
var state = new AuctionState { Price = 0.37, ServerUnixSeconds = 1_788_000_019, ExpiryUnixSeconds = 1_788_000_020, Status = AuctionStatus.Running };
|
||||
Assert.Equal(LossReasons.Kind.PrezzoMassimo, strategy.Decide(auction, state, s, null, false, "io", new DateTime(2026, 9, 26, 12, 0, 0)).Kind);
|
||||
|
||||
// Un calcolo a zero (come lo davano le versioni di prima) non diventa «nessun limite»: vale il predefinito.
|
||||
var zero = advice with { MaxPrice = 0, MaxBids = 0 };
|
||||
var withDefaults = new AppSettings { DefaultMaxPrice = 20, DefaultMaxClicks = 50 };
|
||||
Assert.Equal(20, ProductRules.Resolve(null, withDefaults, autoAdded: true, zero).MaxPrice);
|
||||
Assert.Equal(50, ProductRules.Resolve(null, withDefaults, autoAdded: true, zero).MaxBids);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_coerenza_delle_puntate_del_vincitore()
|
||||
{
|
||||
Assert.True(AuctionIntegrity.CheckWinnerBids(8.38, 25).IsTrustworthy);
|
||||
Assert.False(AuctionIntegrity.CheckWinnerBids(8.38, null).IsTrustworthy);
|
||||
Assert.False(AuctionIntegrity.CheckWinnerBids(8.38, 0).IsTrustworthy);
|
||||
Assert.Contains("oltre il totale", AuctionIntegrity.CheckWinnerBids(0.10, 50).Reason);
|
||||
Assert.True(AuctionIntegrity.CheckWinnerBids(0.03, 3).IsTrustworthy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_stellina_toglie_la_scheda_solo_senza_limiti_propri()
|
||||
{
|
||||
var store = new ProductStore(null);
|
||||
store.SetFollowed("buono", "Buono", 1, true);
|
||||
Assert.True(store.Find("buono")!.Followed);
|
||||
store.SetFollowed("buono", "Buono", 1, false);
|
||||
Assert.Null(store.Find("buono"));
|
||||
|
||||
store.Upsert(new ProductRecord { ProductKey = "caro", DisplayName = "Caro", Followed = true, MaxPrice = 5 });
|
||||
store.SetFollowed("caro", "Caro", 0, false);
|
||||
Assert.NotNull(store.Find("caro"));
|
||||
|
||||
store.MarkRemoved("caro", "123");
|
||||
Assert.True(store.IsHandled("123"));
|
||||
Assert.Equal("caro", store.FindFor(new CatalogAuction { Name = "Caro", ProductId = 0 })!.ProductKey);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>La strategia: rischio solo dal vivo, poi i paletti, poi il modello.</summary>
|
||||
public class BidStrategyTests
|
||||
{
|
||||
private static (BidStrategy Strategy, LearningService Learning, ProductStore Products, RiskManager Risk) Make(AccountBalance? balance = null)
|
||||
{
|
||||
var docs = new MemoryDocumentStore();
|
||||
var settings = new AppSettings();
|
||||
var learning = new LearningService(docs, new MemoryLearningData(), () => settings, null);
|
||||
var products = new ProductStore(null);
|
||||
var risk = new RiskManager(docs, new ListLedger());
|
||||
return (new BidStrategy(risk, learning, products, () => balance ?? new AccountBalance(1407, 927, 480)), learning, products, risk);
|
||||
}
|
||||
|
||||
private static AuctionInfo Auction()
|
||||
{
|
||||
var a = new AuctionInfo("1") { Name = "Buono Amazon 50 €", ProductKey = "buono amazon 50", BuyNowPrice = 50, Mode = RunMode.Active };
|
||||
lock (a.BidsLock)
|
||||
{
|
||||
a.RecentBids.Add(new BidHistoryEntry { Price = 4.12m, Username = "marco", Timestamp = 1_788_000_010, BidType = BidHistoryEntry.TypeAuto });
|
||||
a.RecentBids.Add(new BidHistoryEntry { Price = 4.11m, Username = "lulu", Timestamp = 1_788_000_001, BidType = BidHistoryEntry.TypeManual });
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
private static AuctionState State(double price = 4.12, bool mine = false) =>
|
||||
new() { Price = price, ServerUnixSeconds = 1_788_000_019, ExpiryUnixSeconds = 1_788_000_020, Status = AuctionStatus.Running, IsMyBid = mine };
|
||||
|
||||
[Fact]
|
||||
public void Il_costo_effettivo_scala_per_la_quota_di_pagate()
|
||||
{
|
||||
var s = new AppSettings { AverageBidCostEuro = 0.20 };
|
||||
Assert.Equal(0.20 * 927 / 1407, BidStrategy.EffectiveBidCost(s, new AccountBalance(1407, 927, 480)), 9);
|
||||
Assert.Equal(0.20, BidStrategy.EffectiveBidCost(s, new AccountBalance(1407, null, null)), 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_rischio_vale_solo_dal_vivo()
|
||||
{
|
||||
var (strategy, _, _, risk) = Make();
|
||||
risk.SetHalt("prova", automatic: false);
|
||||
var live = strategy.Decide(Auction(), State(), new AppSettings(), null, shadow: false, "io", new DateTime(2026, 9, 26, 12, 0, 0));
|
||||
Assert.Equal(LossReasons.Kind.Rischio, live.Kind);
|
||||
var shadow = strategy.Decide(Auction(), State(), new AppSettings(), null, shadow: true, "io", new DateTime(2026, 9, 26, 12, 0, 0));
|
||||
Assert.NotEqual(LossReasons.Kind.Rischio, shadow.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void I_paletti_fermano_prima_del_modello()
|
||||
{
|
||||
var (strategy, _, _, _) = Make(new AccountBalance(900, 500, 400));
|
||||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||||
Assert.Equal(LossReasons.Kind.InTesta, strategy.Decide(Auction(), State(mine: true), new AppSettings(), null, true, "io", noon).Kind);
|
||||
Assert.Equal(LossReasons.Kind.PuntateResidue, strategy.Decide(Auction(), State(), new AppSettings { MinimumRemainingBids = 1000 }, null, true, "io", noon).Kind);
|
||||
|
||||
var capped = Auction();
|
||||
capped.MaxPrice = 4.00;
|
||||
Assert.Equal(LossReasons.Kind.PrezzoMassimo, strategy.Decide(capped, State(), new AppSettings(), null, true, "io", noon).Kind);
|
||||
|
||||
var quiet = new AppSettings { QuietHoursEnabled = true, QuietHoursStart = 0, QuietHoursEnd = 10 };
|
||||
Assert.Equal(LossReasons.Kind.FasciaOraria, strategy.Decide(Auction(), State(), quiet, null, true, "io", new DateTime(2026, 9, 26, 3, 0, 0)).Kind);
|
||||
|
||||
var full = Auction();
|
||||
full.MaxBids = 2;
|
||||
full.BidsUsedOnAuction = 2;
|
||||
Assert.Equal(LossReasons.Kind.PuntateAsta, strategy.Decide(full, State(), new AppSettings(), null, true, "io", noon).Kind);
|
||||
|
||||
// Sotto il prezzo minimo non si punta: a quel prezzo di solito l'asta non chiude.
|
||||
var early = Auction();
|
||||
early.MinPrice = 5.00;
|
||||
var below = strategy.Decide(early, State(price: 4.12), new AppSettings(), null, true, "io", noon);
|
||||
Assert.Equal(LossReasons.Kind.PrezzoMinimo, below.Kind);
|
||||
Assert.False(below.ShouldBid);
|
||||
Assert.NotEqual(LossReasons.Kind.PrezzoMinimo, strategy.Decide(early, State(price: 5.01), new AppSettings(), null, true, "io", noon).Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Col_modello_non_pronto_si_punta_entro_i_paletti_e_poi_decide_il_valore_atteso()
|
||||
{
|
||||
var (strategy, learning, _, _) = Make();
|
||||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||||
var early = strategy.Decide(Auction(), State(), new AppSettings(), null, true, "io", noon);
|
||||
Assert.Equal(LossReasons.Kind.NonPronto, early.Kind);
|
||||
Assert.True(early.ShouldBid);
|
||||
Assert.NotNull(early.Context);
|
||||
|
||||
learning.SetLearnedForTests(500);
|
||||
var ready = strategy.Decide(Auction(), State(), new AppSettings(), null, true, "io", noon);
|
||||
Assert.True(ready.Kind is LossReasons.Kind.Punta or LossReasons.Kind.EvNegativo);
|
||||
Assert.Equal(ready.Ev > 0, ready.ShouldBid);
|
||||
Assert.Contains("valore atteso", ready.Reason);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// I documenti lasciati da un modello della versione 2 delle variabili (86 variabili, 400 aste
|
||||
/// studiate) e un archivio di <paramref name="archive"/> aste chiuse da ristudiare.
|
||||
/// </summary>
|
||||
internal static (MemoryDocumentStore Docs, MemoryLearningData Data) AfterUpgrade(int archive)
|
||||
{
|
||||
var docs = new MemoryDocumentStore();
|
||||
docs.Set("ml/model", new OnlineLogit(86).ToJson());
|
||||
docs.Set("ml/features-version", """{"version":2}""");
|
||||
docs.Set("ml/learned", """{"count":400}""");
|
||||
var data = new MemoryLearningData();
|
||||
var rng = new Random(5);
|
||||
for (var i = 0; i < archive; i++) data.Sessions[$"s{i}"] = LearningServiceTests.Session($"s{i}", 30 + rng.Next(30), rng);
|
||||
return (docs, data);
|
||||
}
|
||||
|
||||
private static BidStrategy StrategyFor(LearningService learning, MemoryDocumentStore docs) =>
|
||||
new(new RiskManager(docs, new ListLedger()), learning, new ProductStore(null), () => new AccountBalance(1407, 927, 480));
|
||||
|
||||
[Fact]
|
||||
public async Task Dopo_un_cambio_delle_variabili_non_si_punta_finche_l_archivio_non_e_ristudiato()
|
||||
{
|
||||
var (docs, data) = AfterUpgrade(6);
|
||||
var settings = new AppSettings();
|
||||
var learning = new LearningService(docs, data, () => settings, null);
|
||||
await learning.LoadAsync();
|
||||
Assert.True(learning.RestudyingAfterUpgrade);
|
||||
Assert.Equal(0, learning.AuctionsLearned);
|
||||
|
||||
var strategy = StrategyFor(learning, docs);
|
||||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||||
|
||||
// Dal vivo e in Osserva: il modello vuoto sarebbe «non pronto» e punterebbe; invece no, e lo dice.
|
||||
foreach (var shadow in new[] { false, true })
|
||||
{
|
||||
var d = strategy.Decide(Auction(), State(), settings, null, shadow, "io", noon);
|
||||
Assert.False(d.ShouldBid);
|
||||
Assert.Equal(LossReasons.Kind.Ristudio, d.Kind);
|
||||
Assert.Equal("il modello sta ristudiando l'archivio dopo un aggiornamento: nessuna puntata finché non finisce", d.Reason);
|
||||
Assert.NotNull(d.Context);
|
||||
Assert.False(d.FromModel);
|
||||
}
|
||||
|
||||
// Anche senza stima (valore ignoto) e anche se il conto delle aste basterebbe a dirsi pronto.
|
||||
var unknown = Auction();
|
||||
unknown.BuyNowPrice = null;
|
||||
Assert.Equal(LossReasons.Kind.Ristudio, strategy.Decide(unknown, State(), settings, null, false, "io", noon).Kind);
|
||||
learning.SetLearnedForTests(500);
|
||||
Assert.False(strategy.Decide(Auction(), State(), settings, null, false, "io", noon).ShouldBid);
|
||||
learning.SetLearnedForTests(0);
|
||||
|
||||
// I paletti restano prima: il motivo di un no per il prezzo resta il prezzo.
|
||||
var capped = Auction();
|
||||
capped.MaxPrice = 4.00;
|
||||
Assert.Equal(LossReasons.Kind.PrezzoMassimo, strategy.Decide(capped, State(), settings, null, false, "io", noon).Kind);
|
||||
|
||||
// Con l'apprendimento spento il modello non conta: si punta entro i paletti, scelta dell'utente.
|
||||
Assert.Equal(LossReasons.Kind.SoloLimiti, strategy.Decide(Auction(), State(), new AppSettings { LearningEnabled = false }, null, false, "io", noon).Kind);
|
||||
|
||||
// Un riavvio a metà non perde la guardia.
|
||||
var restarted = new LearningService(docs, data, () => settings, null);
|
||||
await restarted.LoadAsync();
|
||||
Assert.True(restarted.RestudyingAfterUpgrade);
|
||||
|
||||
// Lo studio arriva in fondo: si torna al comportamento di sempre (qui: poche aste, non pronto, punta entro i paletti).
|
||||
await learning.StudyNowAsync(null, CancellationToken.None);
|
||||
Assert.False(learning.RestudyingAfterUpgrade);
|
||||
Assert.Equal(6, learning.AuctionsLearned);
|
||||
var after = strategy.Decide(Auction(), State(), settings, null, false, "io", noon);
|
||||
Assert.Equal(LossReasons.Kind.NonPronto, after.Kind);
|
||||
Assert.True(after.ShouldBid);
|
||||
|
||||
var third = new LearningService(docs, data, () => settings, null);
|
||||
await third.LoadAsync();
|
||||
Assert.False(third.RestudyingAfterUpgrade);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Senza_un_modello_di_un_altra_versione_la_guardia_non_si_alza()
|
||||
{
|
||||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||||
|
||||
// Installazione nuova, anche con un archivio da studiare: non pronto, si punta entro i paletti.
|
||||
var (_, data) = AfterUpgrade(3);
|
||||
var freshDocs = new MemoryDocumentStore();
|
||||
var fresh = new LearningService(freshDocs, data, () => new AppSettings(), null);
|
||||
await fresh.LoadAsync();
|
||||
Assert.False(fresh.RestudyingAfterUpgrade);
|
||||
Assert.Equal(LossReasons.Kind.NonPronto, StrategyFor(fresh, freshDocs).Decide(Auction(), State(), new AppSettings(), null, false, "io", noon).Kind);
|
||||
|
||||
// Cambio di versione senza archivio da ristudiare: come un'installazione nuova.
|
||||
var (docs, empty) = AfterUpgrade(0);
|
||||
var learning = new LearningService(docs, empty, () => new AppSettings(), null);
|
||||
await learning.LoadAsync();
|
||||
Assert.False(learning.RestudyingAfterUpgrade);
|
||||
var d = StrategyFor(learning, docs).Decide(Auction(), State(), new AppSettings(), null, false, "io", noon);
|
||||
Assert.Equal(LossReasons.Kind.NonPronto, d.Kind);
|
||||
Assert.True(d.ShouldBid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Se_il_ristudio_si_ferma_resta_il_lato_sicuro_fino_a_Studia_adesso()
|
||||
{
|
||||
var (docs, data) = AfterUpgrade(4);
|
||||
var settings = new AppSettings();
|
||||
var learning = new LearningService(docs, data, () => settings, null);
|
||||
await learning.LoadAsync();
|
||||
var strategy = StrategyFor(learning, docs);
|
||||
var noon = new DateTime(2026, 9, 26, 12, 0, 0);
|
||||
|
||||
data.FailLoad = true;
|
||||
await learning.BootstrapAsync(TimeSpan.Zero, CancellationToken.None);
|
||||
Assert.True(learning.RestudyingAfterUpgrade);
|
||||
Assert.True(learning.RestudyStopped);
|
||||
|
||||
var d = strategy.Decide(Auction(), State(), settings, null, false, "io", noon);
|
||||
Assert.False(d.ShouldBid);
|
||||
Assert.Equal(LossReasons.Kind.Ristudio, d.Kind);
|
||||
Assert.Contains("«Studia adesso»", d.Reason);
|
||||
|
||||
var status = await learning.GetStatusAsync(settings);
|
||||
Assert.Equal(LearningService.StudyState.DaRicalcolare, status.State);
|
||||
Assert.Contains("in Attiva non punta", status.Detail);
|
||||
Assert.Contains("il bottone con il libro («Studia adesso»)", status.Detail);
|
||||
|
||||
// Lo studio fallito non abbassa la guardia nemmeno dopo un riavvio.
|
||||
var restarted = new LearningService(docs, data, () => settings, null);
|
||||
await restarted.LoadAsync();
|
||||
Assert.True(restarted.RestudyingAfterUpgrade);
|
||||
|
||||
// «Studia adesso» arriva in fondo: la guardia si abbassa.
|
||||
data.FailLoad = false;
|
||||
await learning.StudyNowAsync(null, CancellationToken.None);
|
||||
Assert.False(learning.RestudyingAfterUpgrade);
|
||||
Assert.False(learning.RestudyStopped);
|
||||
Assert.NotEqual(LossReasons.Kind.Ristudio, strategy.Decide(Auction(), State(), settings, null, false, "io", noon).Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Senza_valore_del_prodotto_si_punta_entro_i_paletti()
|
||||
{
|
||||
var (strategy, _, _, _) = Make();
|
||||
var a = Auction();
|
||||
a.BuyNowPrice = null;
|
||||
Assert.Equal(LossReasons.Kind.SenzaStima, strategy.Decide(a, State(), new AppSettings(), null, true, "io", DateTime.Now).Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void La_correzione_sulle_mie_puntate_e_nei_limiti()
|
||||
{
|
||||
var (_, learning, _, _) = Make();
|
||||
learning.SetOwnBidsForTests(10, 3.0, 6);
|
||||
Assert.Equal(1.0, learning.OwnBidFactor);
|
||||
learning.SetOwnBidsForTests(30, 3.0, 6);
|
||||
Assert.Equal(6.5 / 3.5, learning.OwnBidFactor, 6);
|
||||
learning.SetOwnBidsForTests(30, 0.5, 30);
|
||||
Assert.Equal(4.0, learning.OwnBidFactor);
|
||||
learning.SetOwnBidsForTests(30, 30, 0);
|
||||
Assert.Equal(0.25, learning.OwnBidFactor);
|
||||
}
|
||||
}
|
||||
|
||||
public class LearningServiceTests
|
||||
{
|
||||
internal static TrainingReader.Session Session(string id, int bids, Random rng)
|
||||
{
|
||||
var list = new List<TrainingReader.Bid>();
|
||||
long t = 1_788_000_000;
|
||||
var users = new[] { "anna", "bruno", "carla", "dino" };
|
||||
for (var i = 0; i < bids; i++)
|
||||
{
|
||||
t += 2 + rng.Next(9);
|
||||
list.Add(new TrainingReader.Bid(i, users[rng.Next(users.Length)], t, rng.Next(2) == 0 ? "Auto" : "Manuale", false, (i + 1) / 100.0));
|
||||
}
|
||||
return TrainingReader.Finish(new TrainingReader.Session
|
||||
{
|
||||
AuctionId = id, ProductKey = "buono", BuyNowPrice = 50, AddedAtLocal = new DateTime(2026, 9, 7, 11, 0, 0),
|
||||
Bids = list, Winner = list[^1].User, FinalPrice = bids / 100.0, HasSummary = true
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Studia_le_aste_chiuse_e_salva_nei_documenti()
|
||||
{
|
||||
var docs = new MemoryDocumentStore();
|
||||
var data = new MemoryLearningData();
|
||||
var rng = new Random(3);
|
||||
for (var i = 0; i < 12; i++) data.Sessions[$"a{i}"] = Session($"a{i}", 30 + rng.Next(60), rng);
|
||||
|
||||
var settings = new AppSettings();
|
||||
var learning = new LearningService(docs, data, () => settings, null);
|
||||
await learning.LoadAsync();
|
||||
var (done, usable) = await learning.StudyNowAsync(null, CancellationToken.None);
|
||||
|
||||
Assert.Equal(12, done);
|
||||
Assert.Equal(12, usable);
|
||||
Assert.Equal(12, learning.AuctionsLearned);
|
||||
Assert.True(learning.ModelUpdates > 300);
|
||||
Assert.NotNull(docs.Get("ml/model"));
|
||||
Assert.Contains("\"count\":12", docs.Get("ml/learned"));
|
||||
|
||||
// Un secondo servizio sugli stessi documenti riparte da dove era.
|
||||
var again = new LearningService(docs, data, () => settings, null);
|
||||
await again.LoadAsync();
|
||||
Assert.Equal(12, again.AuctionsLearned);
|
||||
Assert.Equal(learning.ModelUpdates, again.ModelUpdates);
|
||||
|
||||
// La stessa asta chiusa non si impara due volte: il modello resta com'è, il resto
|
||||
// (profilo, bandit, motivo) si aggiorna una volta sola.
|
||||
var closed = new ClosedAuctionInfo("a0", "Buono", "buono", DateTime.UtcNow, 0.5, 50, null, null, 3, false, "anna", 10);
|
||||
var updates = again.ModelUpdates;
|
||||
Assert.StartsWith("già studiata", await again.OnAuctionClosedAsync(closed));
|
||||
Assert.Equal(updates, again.ModelUpdates);
|
||||
Assert.True(data.Reasons.ContainsKey("a0"));
|
||||
Assert.Null(await again.OnAuctionClosedAsync(closed));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cambiare_le_variabili_fa_ristudiare_tutto()
|
||||
{
|
||||
var docs = new MemoryDocumentStore();
|
||||
docs.Set("ml/model", new OnlineLogit(BidFeatures.Size).ToJson());
|
||||
docs.Set("ml/features-version", """{"version":1}""");
|
||||
docs.Set("ml/learned", """{"count":99}""");
|
||||
var data = new MemoryLearningData();
|
||||
data.Sessions["x"] = new TrainingReader.Session { AuctionId = "x", HasSummary = true };
|
||||
|
||||
var learning = new LearningService(docs, data, () => new AppSettings(), null);
|
||||
await learning.LoadAsync();
|
||||
Assert.Equal(0, learning.AuctionsLearned);
|
||||
Assert.True(learning.FullStudyPending);
|
||||
Assert.True(learning.RestudyingAfterUpgrade);
|
||||
Assert.True(learning.BanditRebuildPending);
|
||||
Assert.Contains($"\"version\":{BidFeatures.Version}", docs.Get("ml/features-version"));
|
||||
}
|
||||
|
||||
/// <summary>Un modello della versione 2 con un bandit pieno, e decisioni registrate con esito su due aste.</summary>
|
||||
private static (MemoryDocumentStore Docs, MemoryLearningData Data) UpgradeWithDecisions()
|
||||
{
|
||||
var (docs, data) = BidStrategyTests.AfterUpgrade(3);
|
||||
var old = new ThompsonBandit();
|
||||
for (var i = 0; i < 50; i++) old.Observe("vecchia|chiave", i % 2 == 0);
|
||||
docs.Set("ml/bandit", old.ToJson());
|
||||
data.Outcomes["s0"] = new() { ("g3|r1|h5|b2|a0", "won"), ("g3|r1|h5|b2|a0", "lost"), ("g1|r0|h2|b1|a1", "would_win") };
|
||||
data.Outcomes["s1"] = new() { ("g1|r0|h2|b1|a1", "missed") };
|
||||
return (docs, data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Dopo_il_cambio_delle_variabili_il_bandit_si_rifa_dalle_decisioni_registrate()
|
||||
{
|
||||
var (docs, data) = UpgradeWithDecisions();
|
||||
var learning = new LearningService(docs, data, () => new AppSettings(), null);
|
||||
await learning.LoadAsync();
|
||||
Assert.Equal(0, learning.Bandit.Observations);
|
||||
Assert.True(learning.BanditRebuildPending);
|
||||
|
||||
// Un riavvio prima dello studio d'avvio non perde il lavoro in sospeso.
|
||||
var restarted = new LearningService(docs, data, () => new AppSettings(), null);
|
||||
await restarted.LoadAsync();
|
||||
Assert.True(restarted.BanditRebuildPending);
|
||||
|
||||
// Lo studio d'avvio ristudia l'archivio e poi rifà il bandit, con le fasce di adesso.
|
||||
await learning.BootstrapAsync(TimeSpan.Zero, CancellationToken.None);
|
||||
Assert.False(learning.RestudyingAfterUpgrade);
|
||||
Assert.False(learning.BanditRebuildPending);
|
||||
Assert.Equal(3, learning.AuctionsLearned);
|
||||
Assert.Equal(4, learning.Bandit.Observations);
|
||||
Assert.Equal(2, learning.Bandit.Arms);
|
||||
Assert.Null(docs.Get("ml/upgrade"));
|
||||
|
||||
// Fatto una volta, al prossimo avvio non si rifà.
|
||||
var again = new LearningService(docs, data, () => new AppSettings(), null);
|
||||
await again.LoadAsync();
|
||||
Assert.False(again.BanditRebuildPending);
|
||||
Assert.Equal(4, again.Bandit.Observations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Dimentica_tutto_dimentica_anche_il_bandit_da_rifare()
|
||||
{
|
||||
var (docs, data) = UpgradeWithDecisions();
|
||||
var learning = new LearningService(docs, data, () => new AppSettings(), null);
|
||||
await learning.LoadAsync();
|
||||
Assert.True(learning.BanditRebuildPending);
|
||||
|
||||
await learning.ForgetAsync();
|
||||
Assert.False(learning.BanditRebuildPending);
|
||||
// Il ristudio resta dovuto: finché l'archivio non è studiato non si punta.
|
||||
Assert.True(learning.RestudyingAfterUpgrade);
|
||||
|
||||
await learning.BootstrapAsync(TimeSpan.Zero, CancellationToken.None);
|
||||
Assert.False(learning.RestudyingAfterUpgrade);
|
||||
Assert.Equal(0, learning.Bandit.Observations);
|
||||
|
||||
var restarted = new LearningService(docs, data, () => new AppSettings(), null);
|
||||
await restarted.LoadAsync();
|
||||
Assert.False(restarted.BanditRebuildPending);
|
||||
Assert.Equal(0, restarted.Bandit.Observations);
|
||||
|
||||
// Un «Dimentica tutto» senza cambio di versione non alza nessuna guardia.
|
||||
var plain = new LearningService(new MemoryDocumentStore(), data, () => new AppSettings(), null);
|
||||
await plain.LoadAsync();
|
||||
await plain.ForgetAsync();
|
||||
Assert.False(plain.RestudyingAfterUpgrade);
|
||||
Assert.False(plain.BanditRebuildPending);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Un_modello_salvato_con_la_versione_vecchia_non_si_carica_con_la_dimensione_sbagliata()
|
||||
{
|
||||
// Come li lasciava la versione 2 delle variabili: 86 variabili, 6 fasce orarie larghe.
|
||||
const int oldSize = 86;
|
||||
var docs = new MemoryDocumentStore();
|
||||
var old = new OnlineLogit(oldSize);
|
||||
var x = new double[oldSize];
|
||||
x[0] = 1;
|
||||
for (var i = 0; i < 50; i++) old.Update(x, i % 3 == 0);
|
||||
docs.Set("ml/model", old.ToJson());
|
||||
docs.Set("ml/challenger", new NeuralNet(new[] { oldSize, 32, 16, 1 }, seed: 42).ToJson());
|
||||
var bandit = new ThompsonBandit();
|
||||
bandit.Observe("g3|r1|h5|b2|a0", true);
|
||||
docs.Set("ml/bandit", bandit.ToJson());
|
||||
var profile = new AuctionProfileStats();
|
||||
profile.Observe("buono", new DateTime(2026, 9, 7, 22, 0, 0), 30, 0.1);
|
||||
docs.Set("ml/profile", profile.ToJson());
|
||||
var forecast = new AuctionForecast();
|
||||
for (var i = 0; i < 20; i++) forecast.Observe("buono", 3, 50, 5, 30, 10);
|
||||
docs.Set("ml/forecast", forecast.ToJson());
|
||||
docs.Set("ml/features-version", """{"version":2}""");
|
||||
docs.Set("ml/learned", """{"count":40}""");
|
||||
|
||||
var learning = new LearningService(docs, new MemoryLearningData(), () => new AppSettings(), null);
|
||||
await learning.LoadAsync();
|
||||
|
||||
Assert.Equal(0, learning.ModelUpdates);
|
||||
Assert.Equal(0, learning.AuctionsLearned);
|
||||
Assert.Equal(BidFeatures.Size, learning.Weights().Count);
|
||||
Assert.Equal(0, learning.Bandit.Arms);
|
||||
Assert.Equal(0, learning.ProfileAuctions);
|
||||
Assert.Equal(0, learning.ForecastObserved);
|
||||
Assert.Null(learning.Forecast(new ForecastInput("buono", 1, 50, 5, null, null, 0.13, 1, 0, 3, 0)));
|
||||
|
||||
// Il modello risponde con il vettore nuovo e i documenti hanno la dimensione nuova.
|
||||
var ctx = new BidContext(3, 0.5, 3, 0.05, 23, DayOfWeek.Friday, 0, false, 1, 120, false, "buono");
|
||||
Assert.InRange(learning.PredictUnanswered(ctx), 0, 1);
|
||||
Assert.Equal(0, OnlineLogit.FromJson(docs.Get("ml/model")!, BidFeatures.Size).Updates);
|
||||
Assert.Contains($"\"Sizes\":[{BidFeatures.Size},32,16,1]", docs.Get("ml/challenger"));
|
||||
Assert.Contains($"\"version\":{BidFeatures.Version}", docs.Get("ml/features-version"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Anche_senza_modello_profilo_e_previsioni_di_un_altra_versione_si_scartano()
|
||||
{
|
||||
var docs = new MemoryDocumentStore();
|
||||
var forecast = new AuctionForecast();
|
||||
for (var i = 0; i < 20; i++) forecast.Observe("buono", 3, 50, 5, 30, 10);
|
||||
var profile = new AuctionProfileStats();
|
||||
profile.Observe("buono", new DateTime(2026, 9, 7, 22, 0, 0), 30, 0.1);
|
||||
docs.Set("ml/forecast", forecast.ToJson());
|
||||
docs.Set("ml/profile", profile.ToJson());
|
||||
docs.Set("ml/features-version", """{"version":2}""");
|
||||
|
||||
var learning = new LearningService(docs, new MemoryLearningData(), () => new AppSettings(), null);
|
||||
await learning.LoadAsync();
|
||||
Assert.Equal(0, learning.ForecastObserved);
|
||||
Assert.Equal(0, learning.ProfileAuctions);
|
||||
Assert.Contains($"\"version\":{BidFeatures.Version}", docs.Get("ml/features-version"));
|
||||
|
||||
// Con la versione giusta invece si ricaricano com'erano.
|
||||
docs.Set("ml/forecast", forecast.ToJson());
|
||||
docs.Set("ml/profile", profile.ToJson());
|
||||
var again = new LearningService(docs, new MemoryLearningData(), () => new AppSettings(), null);
|
||||
await again.LoadAsync();
|
||||
Assert.Equal(20, again.ForecastObserved);
|
||||
Assert.Equal(1, again.ProfileAuctions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_bandit_si_rifa_con_le_fasce_di_adesso_dal_contesto_salvato()
|
||||
{
|
||||
var ctx = new BidContext(3, 0.8, 2, 0.05, 22, DayOfWeek.Monday, 21, false, 1, 120, false, "buono");
|
||||
var json = System.Text.Json.JsonSerializer.Serialize(new DecisionState { Ctx = ctx, Price = 1.2 }, new System.Text.Json.JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
|
||||
});
|
||||
|
||||
var key = DbLearningData.CurrentBanditKey(json);
|
||||
Assert.Equal(ThompsonBandit.KeyOf(ctx), key);
|
||||
Assert.Contains($"|h{BidFeatures.HourBand(22)}|", key);
|
||||
Assert.Null(DbLearningData.CurrentBanditKey(null));
|
||||
Assert.Null(DbLearningData.CurrentBanditKey("{\"price\":1.2}"));
|
||||
Assert.Null(DbLearningData.CurrentBanditKey("non json"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task L_esplorazione_ha_un_budget_al_giorno()
|
||||
{
|
||||
var learning = new LearningService(new MemoryDocumentStore(), new MemoryLearningData(), () => new AppSettings(), null);
|
||||
var s = new AppSettings { ExplorationBidsPerDay = 2 };
|
||||
Assert.True(learning.ExplorationAvailable(s));
|
||||
learning.NoteExplorationBid();
|
||||
learning.NoteExplorationBid();
|
||||
Assert.False(learning.ExplorationAvailable(s));
|
||||
Assert.False(learning.ExplorationAvailable(new AppSettings { ExplorationBidsPerDay = 0 }));
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using System.Globalization;
|
||||
using System.Runtime.CompilerServices;
|
||||
using BidooBidBot.Data;
|
||||
using Npgsql;
|
||||
using Xunit;
|
||||
|
||||
namespace BidooBidBot.Tests;
|
||||
|
||||
/// <summary>Numeri all'italiana anche nei test: i messaggi del bot si leggono così.</summary>
|
||||
internal static class TestCulture
|
||||
{
|
||||
[ModuleInitializer]
|
||||
internal static void Init()
|
||||
{
|
||||
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("it-IT");
|
||||
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("it-IT");
|
||||
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("it-IT");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Il PostgreSQL dei test, da <c>TEST_DB_HOST</c> (più <c>TEST_DB_USER</c>,
|
||||
/// <c>TEST_DB_PASSWORD</c>, <c>TEST_DB_NAME</c>). Senza la variabile i test su database
|
||||
/// saltano: in locale basta il compose di <c>tools/dev</c>, nel workflow c'è il servizio.
|
||||
/// </summary>
|
||||
public static class TestDb
|
||||
{
|
||||
public static string? Host => Environment.GetEnvironmentVariable("TEST_DB_HOST") is { Length: > 0 } h ? h : null;
|
||||
|
||||
public static DbConfig Config => new(
|
||||
Host ?? "localhost",
|
||||
5432,
|
||||
Environment.GetEnvironmentVariable("TEST_DB_USER") ?? "admin",
|
||||
Environment.GetEnvironmentVariable("TEST_DB_PASSWORD") ?? "dev",
|
||||
Environment.GetEnvironmentVariable("TEST_DB_NAME") ?? "bidbot_test");
|
||||
}
|
||||
|
||||
/// <summary>Un test su PostgreSQL: salta se <c>TEST_DB_HOST</c> non è impostata.</summary>
|
||||
public sealed class DbFactAttribute : FactAttribute
|
||||
{
|
||||
public DbFactAttribute()
|
||||
{
|
||||
if (TestDb.Host == null) Skip = "TEST_DB_HOST non impostata: test su PostgreSQL saltato";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Database di prova pulito, una volta per esecuzione: si cancella e si ricrea, poi si
|
||||
/// applicano le migrazioni. I test della collezione «Database» girano uno alla volta.
|
||||
/// </summary>
|
||||
public sealed class DatabaseFixture : IAsyncLifetime
|
||||
{
|
||||
public Db? Db { get; private set; }
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
if (TestDb.Host == null) return;
|
||||
|
||||
var cfg = TestDb.Config;
|
||||
await using (var admin = new NpgsqlConnection(cfg.Builder("postgres").ConnectionString))
|
||||
{
|
||||
await admin.OpenAsync();
|
||||
var name = cfg.Database.Replace("\"", "\"\"", StringComparison.Ordinal);
|
||||
await using (var drop = new NpgsqlCommand($"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", admin))
|
||||
await drop.ExecuteNonQueryAsync();
|
||||
await using (var create = new NpgsqlCommand($"CREATE DATABASE \"{name}\"", admin))
|
||||
await create.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
Db = new Db(cfg);
|
||||
await Migrations.ApplyAsync(Db.Writer);
|
||||
await Partitions.EnsureAsync(Db, DateTime.UtcNow);
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
if (Db != null) await Db.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Svuota le tabelle fra un test e l'altro (le partizioni restano).</summary>
|
||||
public async Task TruncateAsync()
|
||||
{
|
||||
await Db!.ExecuteAsync(
|
||||
"TRUNCATE settings, documents, items, auctions, bids, resets, my_bids, bot_decisions, auction_forecasts, " +
|
||||
"bidders, risk_ledger, products, watched_products, product_stats RESTART IDENTITY CASCADE");
|
||||
}
|
||||
}
|
||||
|
||||
[CollectionDefinition("Database")]
|
||||
public sealed class DatabaseCollection : ICollectionFixture<DatabaseFixture>
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Cartella temporanea che si cancella da sola: i test non scrivono mai altrove.</summary>
|
||||
public sealed class TempDir : IDisposable
|
||||
{
|
||||
public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "bidbot-test-" + Guid.NewGuid().ToString("N")[..10]);
|
||||
|
||||
public TempDir() => Directory.CreateDirectory(Path);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(Path, true); } catch { }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user