Nel rilascio della 1.9.3 la prova che punta in Attiva e deve vincere ha perso l'asta: su un ciclo di 4-5 s il bot puntava con 250 ms di anticipo, e un risveglio tardivo del cecchino o un orologio stimato male sul runner carico bastano a far arrivare la puntata a cronometro scaduto. Le prove della classe che giocano un'asta ora usano un anticipo fisso di 1.500 ms (minimo, massimo e predefinito uguali): la precisione la misurano altre prove, questa verifica il percorso intero. La prova del riavvio resta senza, perché controlla un anticipo manuale di 450 ms. Se l'asta non è vinta, il messaggio riporta le puntate viste dal simulatore e il registro dell'asta, così un fallimento futuro dice da solo che cosa è successo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
342 lines
16 KiB
C#
342 lines
16 KiB
C#
using Mimante.Bidoo;
|
|
using Mimante.Data;
|
|
using Mimante.Engine;
|
|
using Mimante.Logging;
|
|
using Mimante.Ml;
|
|
using Mimante.Net;
|
|
using Mimante.Products;
|
|
using Mimante.Session;
|
|
using Mimante.Settings;
|
|
using Mimante.Simulator;
|
|
using Mimante.Strategy;
|
|
using Xunit;
|
|
|
|
namespace Mimante.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();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Anticipo delle prove in tempo reale. Con quello di fabbrica (250 ms) un runner carico che ritarda il risveglio
|
|
/// del cecchino di qualche centinaio di millisecondi fa arrivare la puntata a cronometro scaduto, e la prova perde
|
|
/// un'asta che deve vincere (rilascio 1.9.3). Qui non si misura la precisione (lo fanno <c>PrecisionWaitTests</c>
|
|
/// e la prova di carico), ma il percorso intero: un secondo e mezzo di margine su un ciclo di 4 s lo rende certo.
|
|
/// </summary>
|
|
private const int TestLeadMs = 1500;
|
|
|
|
private static async Task<Rig> StartAsync(SimWorld world, AppSettings settings, Func<bool>? canBid = null, bool knownUser = true,
|
|
bool wideLead = true)
|
|
{
|
|
if (wideLead)
|
|
{
|
|
// Minimo, massimo e predefinito uguali: né il modello di latenza né l'isteresi possono spostarlo.
|
|
settings.LeadMinMs = TestLeadMs;
|
|
settings.LeadMaxMs = TestLeadMs;
|
|
settings.DefaultBidBeforeDeadlineMs = TestLeadMs;
|
|
}
|
|
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 = knownUser ? world.MyUsername : null };
|
|
var docs = new MemoryDocumentStore();
|
|
var log = new AppLog(null);
|
|
var account = new AccountState();
|
|
if (knownUser) 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));
|
|
}
|
|
|
|
/// <summary>Perché un'asta è andata così: le mie puntate viste dal simulatore e il registro dell'asta.</summary>
|
|
private static string Explain(Rig rig, AuctionInfo a)
|
|
{
|
|
var bids = rig.World.MyBids.Where(b => b.AuctionId == a.Id)
|
|
.Select(b => $"puntata {b.Result}, anticipo {b.LeadMs:0} ms");
|
|
var log = a.Log.Snapshot().Select(e => $"{e.Ts:HH:mm:ss.fff} {e.Category} {e.Message}");
|
|
return string.Join(Environment.NewLine, new[] { $"esito {a.Outcome}" }.Concat(bids).Concat(log));
|
|
}
|
|
|
|
[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.True(done.Outcome == "won", Explain(rig, done));
|
|
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 Gli_errori_ripetuti_del_motore_danno_un_solo_avviso_per_asta()
|
|
{
|
|
var world = new SimWorld(seed: 25, populate: false);
|
|
var settings = new AppSettings { EngineErrorAlertCount = 3, EngineErrorAlertMinutes = 10 };
|
|
await using var rig = await StartAsync(world, settings);
|
|
var alerts = new List<(string Id, string Last)>();
|
|
rig.Monitor.EngineErrorRepeated += (a, last) => alerts.Add((a.Id, last));
|
|
var one = new AuctionInfo("1") { Name = "Uno" };
|
|
var two = new AuctionInfo("2") { Name = "Due" };
|
|
|
|
for (var i = 1; i <= 6; i++) rig.Monitor.NoteEngineError(one, $"Errore nel polling: prova {i}", AuctionLogCategory.Polling);
|
|
rig.Monitor.NoteEngineError(two, "Errore nel cecchino: prova", AuctionLogCategory.Bid);
|
|
|
|
Assert.Equal(new[] { ("1", "Errore nel polling: prova 3") }, alerts);
|
|
// Ogni errore resta nel registro dell'asta; nel registro generale una riga sola per serie.
|
|
Assert.Equal(6, one.Log.Snapshot().Count(e => e.Level == LogLevel.Error));
|
|
var engine = rig.Log.Snapshot().Where(e => e.Tag == "MOTORE").Select(e => e.Message).ToList();
|
|
Assert.Equal(new[] { "Uno: 3 errori del motore in 10 min, l'ultimo: Errore nel polling: prova 3" }, engine);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Chi_ascolta_l_errore_ripetuto_non_ferma_il_motore()
|
|
{
|
|
var world = new SimWorld(seed: 26, populate: false);
|
|
var settings = new AppSettings { EngineErrorAlertCount = 1, EngineErrorAlertMinutes = 10 };
|
|
await using var rig = await StartAsync(world, settings);
|
|
rig.Monitor.EngineErrorRepeated += (_, _) => throw new ObjectDisposedException("Telegram");
|
|
var one = new AuctionInfo("1") { Name = "Uno" };
|
|
|
|
// NoteEngineError si chiama dai catch del motore: non deve lanciare, e la riga resta nel registro.
|
|
rig.Monitor.NoteEngineError(one, "Errore nel cecchino: prova", AuctionLogCategory.Bid);
|
|
|
|
Assert.Single(one.Log.Snapshot(), e => e.Level == LogLevel.Error);
|
|
}
|
|
|
|
[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);
|
|
|
|
// Nessuna asta giocata qui: l'anticipo largo non serve, e alzerebbe il minimo sotto cui si limita quello manuale.
|
|
string? saved;
|
|
await using (var rig = await StartAsync(world, settings, wideLead: false))
|
|
{
|
|
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, wideLead: false);
|
|
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("Accesso a Bidoo", why);
|
|
// «Può puntare: no», e non perché manchi l'utente della sessione: manca proprio la sessione.
|
|
Assert.False(rig.Monitor.CanBidNow);
|
|
Assert.False(rig.Monitor.UserPending);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Con_la_sessione_ma_senza_sapere_chi_sono_l_asta_Attiva_non_punta_e_dice_perche()
|
|
{
|
|
// Una sessione incollata non porta l'utente: finché buy_bids.php non lo dice, il bot non distinguerebbe
|
|
// le sue puntate da quelle degli altri e punterebbe contro sé stesso.
|
|
var world = new SimWorld(seed: 27, populate: false);
|
|
var settings = new AppSettings { QuietHoursEnabled = false, DefaultMaxPrice = 0, DefaultMaxClicks = 0, AutoRemoveFinished = false };
|
|
await using var rig = await StartAsync(world, settings, knownUser: false);
|
|
var target = world.AddRunningAuction(seconds: 4, freq: 4);
|
|
|
|
// L'interfaccia («Può puntare», la barriera di «Punta adesso») dice la stessa cosa della strategia.
|
|
Assert.True(rig.Monitor.CanBid);
|
|
Assert.False(rig.Monitor.CanBidNow);
|
|
Assert.True(rig.Monitor.UserPending);
|
|
|
|
var (a, _) = await rig.Monitor.AddAsync(new AddAuctionRequest(target.Id, Mode: RunMode.Active), CancellationToken.None);
|
|
Assert.False(rig.Monitor.IsShadow(a!));
|
|
var (done, _, _) = await RunToCompletionAsync(rig, a!);
|
|
|
|
Assert.Empty(world.MyBids);
|
|
Assert.NotNull(done.LastDecision);
|
|
Assert.Equal(LossReasons.Kind.SenzaUtente, done.LastDecision!.Kind);
|
|
Assert.False(done.LastDecision.Shadow);
|
|
Assert.Single(done.Log.Snapshot(), e => e.Message.StartsWith("Non punto: utente della sessione non ancora riconosciuto", StringComparison.Ordinal));
|
|
|
|
var (ok, why) = await rig.Monitor.BidNowAsync(target.Id, CancellationToken.None);
|
|
Assert.False(ok);
|
|
Assert.Contains("non ancora riconosciuto", why);
|
|
Assert.Empty(world.MyBids);
|
|
}
|
|
|
|
[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));
|
|
}
|
|
}
|