Files
Anubis/tests/Anubis.Tests/OverviewScreenTests.cs
T
Alby96andClaude Opus 5.5 2185a0b36b Fix the defects found by the Phase 6 review (refs #47 #48 #49 #51 #52 #54)
An independent review of the phase found nine defects. The ones that
could lose money or orders:

- Exits at the close of equity_meanrev are now planned orders written in
  the same transaction that claims the decision, so a restart can neither
  lose them nor send them twice. A sell with a deadline starts aggressive.
- Resume also finds a planned order not yet linked to its execution
  (restart between sending and linking) and closes it before re-planning.
- An account is "ready" only after adopting the guard's stops, checking
  the key, reconciling, resuming and aligning stops. Until then nothing is
  decided on it or sent to it, and the loop retries its startup each
  minute. The guard's note is deleted only when every stop it placed is in
  the ledger.
- Each account's turn is cut after 45 s (60 s for a retried startup), so a
  slow broker no longer silences the heartbeat until the guard kills a
  healthy engine; the beat is also withheld when the scheduler has been
  silent for 30 minutes.

Smaller ones: a stock decision made after the open is marked late; the
Telegram loops survive unexpected errors; a long absence is shown on the
Panoramica until "Ho visto" (SPEC 5.6); plain-http heartbeats are only
accepted to home-network addresses; the soak report gives a daily close
30 minutes to be decided before expecting it.

ADR 0012 point 12 records these choices; #51 and the two screen criteria
are ticked in the roadmap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:10:28 +01:00

176 lines
9.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO.Compression;
using System.Net;
using Anubis.Server;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The Panoramica and "Diario e sistema" screens (issue #51, mockups 01, 08 and 09).</summary>
[TestClass]
public sealed class OverviewScreenTests
{
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDemoPanoramicaShowsAccountsPositionsAndLimits()
{
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
var page = await server.TextAsync("/");
foreach (var text in new[]
{
// Adesso e dopo (F.10).
"Prossima decisione tra 7 ore e 14 minuti, all'apertura di Wall Street.", "Rimetto gli stop del giorno sulle frazioni di 6 azioni",
"Alzato lo stop di BTC a 66.180", "Apri il diario completo", "Tutte le mosse e il diario",
// The two accounts with their last 30 days (F.2).
"4.231,60", "+231,60", "2.326,50", "1.905,10", "+158,20", "3 posizioni, 3 stop attivi.",
"6.180,86", "4.344,63", "1.836,23", "+93,50", "sulle frazioni tornano alle 15:35",
// The four limits (F.10).
"Tutti i limiti rispettati", "Perdita di oggi", "nessuna", "−2,00%", "Calo dal massimo", "−15,00%", "Capitale investito", "64,1%",
"Posizione più grande (BTC)", "12,5%", "La tacca segna il calo peggiore finora: −2,82%.", "Vedi tutti i limiti",
// Positions by value, strategies, news, model, system.
"BTC/EUR", "1.299,84", "66.180", "(−7,3%)", "Vedi le altre 6",
"In simulazione, giorno 58 di 60", "In simulazione, 21 operazioni su 30", "1 posizione aperta, 21 operazioni chiuse (10 in guadagno)",
"Nessuna strategia usa soldi veri.",
"Rinviato di una settimana l'aggiornamento della rete Solana", "Negativa: per 24 ore non aumento SOL",
"Il modello osserva e impara, ma non decide ancora.", "domenica 11 ottobre, 03:00",
"connesso, 84 ms", "PostgreSQL, 1,8 GB", "ultimo messaggio alle 08:00",
})
{
StringAssert.Contains(page, text, $"Missing «{text}» on the Panoramica.");
}
Assert.IsLessThan(page.IndexOf("ETH/EUR", StringComparison.Ordinal), page.IndexOf("BTC/EUR", StringComparison.Ordinal), "Positions in order of value.");
}
finally
{
await server.DisposeAsync();
TempFolder.Delete(demoRoot);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDiaryFiltersAndSearches()
{
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
var all = await server.TextAsync("/diario");
StringAssert.Contains(all, "Oggi, venerdì 9 ottobre");
StringAssert.Contains(all, "Ieri, giovedì 8 ottobre");
StringAssert.Contains(all, "Ho cambiato una regola per 24 ore:");
StringAssert.Contains(all, "Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana.");
StringAssert.Contains(all, "href=\"/operazioni?cerca=MSFT\"");
StringAssert.Contains(all, "Perché l'ho comprata e venduta");
Assert.IsFalse(all.Contains("(con il collegamento", StringComparison.Ordinal), "The demo's note on the link is not shown.");
StringAssert.Contains(all, "Tutto regolare");
StringAssert.Contains(all, "collegato, mercato chiuso fino alle 15:30");
StringAssert.Contains(all, "Dom 03:00");
StringAssert.Contains(all, "Anubis 0.9.2 in Docker, acceso dal 12 agosto: 58 giorni senza interruzioni.");
// A kind at a time.
var orders = await server.TextAsync("/diario?tipo=ordini");
StringAssert.Contains(orders, "Alzato lo stop di BTC/EUR");
Assert.IsFalse(orders.Contains("Inviato il riepilogo del mattino", StringComparison.Ordinal));
Assert.IsFalse(orders.Contains("Controllo del modello: nessuna anomalia.", StringComparison.Ordinal));
StringAssert.Contains(await server.TextAsync("/diario?tipo=rischio"), "Nessuna voce di questo tipo finora.");
// The search ignores case and accents, and keeps the kind chosen.
var search = await server.TextAsync("/diario?cerca=MARTEDI");
StringAssert.Contains(search, "Ho messo una restrizione fino a martedì:");
Assert.IsFalse(search.Contains("Alzato lo stop", StringComparison.Ordinal));
StringAssert.Contains(search, "Una voce con «MARTEDI»");
var none = await server.TextAsync("/diario?tipo=ordini&cerca=solana");
StringAssert.Contains(none, "Nessuna voce con «solana»");
}
finally
{
await server.DisposeAsync();
TempFolder.Delete(demoRoot);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheLogsDownloadNeedsASessionAndIsAZip()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
var logs = server.Host.Config.Data.Logs;
Directory.CreateDirectory(logs);
await File.WriteAllTextAsync(Path.Combine(logs, "anubis-2099-01-01.log"), "{\"message\":\"una riga\"}\n");
await File.WriteAllTextAsync(Path.Combine(logs, "altro.txt"), "non è un registro");
using (var anonymous = await server.GetAsync("/api/registri.zip"))
{
Assert.AreEqual(HttpStatusCode.Unauthorized, anonymous.StatusCode);
}
await server.SignInFirstTimeAsync();
using (var zip = await server.GetAsync("/api/registri.zip"))
{
Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode);
Assert.AreEqual("application/zip", zip.Content.Headers.ContentType?.MediaType);
await using var stream = await zip.Content.ReadAsStreamAsync();
using var archive = new ZipArchive(stream, ZipArchiveMode.Read);
var names = archive.Entries.Select(e => e.Name).ToList();
Assert.Contains("anubis-2099-01-01.log", names);
Assert.DoesNotContain("altro.txt", names);
using var reader = new StreamReader(archive.GetEntry("anubis-2099-01-01.log")!.Open());
StringAssert.Contains(await reader.ReadToEndAsync(), "una riga");
}
// A new installation: the screens say what is missing instead of showing numbers.
var home = await server.TextAsync("/");
StringAssert.Contains(home, "La lettura delle notizie non è ancora attiva.");
StringAssert.Contains(home, "L'apprendimento non è ancora attivo.");
var diary = await server.TextAsync("/diario");
StringAssert.Contains(diary, "Come sta il sistema");
StringAssert.Contains(diary, "non configurato");
StringAssert.Contains(diary, "Il computer che lo ospita");
// SPEC 5.6: an absence longer than a day stays at the top of the Panoramica until "Ho visto".
var now = server.Host.Clock.UtcNow;
var id = Guid.NewGuid();
await server.Host.Services!.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO absences (id, started_at, ended_at, acknowledged_at, created_at) VALUES (@id, @s, @e, NULL, @e)",
CancellationToken.None, ("id", id), ("s", now.AddDays(-3).AddHours(-2)), ("e", now)));
StringAssert.Contains(await server.TextAsync("/"), "Sono stato spento per 3 giorni e 2 ore, fino a oggi alle");
using (var seen = await server.PostFormAsync("/", $"/azioni/assenza/{id}/vista"))
{
Assert.AreEqual("/", ServerHarness.Location(seen));
}
Assert.DoesNotContain("Sono stato spento", await server.TextAsync("/"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DiaryEntriesAreSplitAsTheMockupDraws()
{
var at = DateTimeOffset.UnixEpoch;
var rule = DiaryView.Entry(at, DiaryKinds.News, "demo", "Ho cambiato una regola per 24 ore: non aumento la posizione su SOL. Motivo: la rete è ferma.");
Assert.AreEqual("Ho cambiato una regola per 24 ore:", rule.Lead);
Assert.AreEqual("Motivo: la rete è ferma.", rule.Rest);
Assert.IsTrue(rule.Attention);
var long1 = DiaryView.Entry(at, DiaryKinds.Orders, "stop_moved", "Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.");
Assert.AreEqual("Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €.", string.Concat(long1.Main.Select(p => p.Text)));
Assert.AreEqual("Lo stop segue il prezzo quando sale.", long1.Rest);
Assert.IsNull(long1.Trade);
var shortOne = DiaryView.Entry(at, DiaryKinds.News, "demo", "Voce non confermata su un exchange. Nessuna azione: ricontrollo tra 2 ore.");
Assert.IsNull(shortOne.Rest, "A short entry stays on one line.");
var sale = DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni.");
Assert.AreEqual("MSFT", sale.Trade);
Assert.AreEqual("gain", sale.Main.Single(p => p.Class is not null).Class);
Assert.AreEqual("ETH", DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Venduto 0,1 ETH/EUR a 2.500 €: −12,00 € in 4 giorni.").Trade);
Assert.IsNull(DiaryView.Entry(at, DiaryKinds.Orders, "fill", "Comprate 2 AAPL a 259,80 $.").Trade, "A purchase has no closed trade to explain.");
Assert.AreEqual("Oggi, venerdì 9 ottobre", DiaryView.Heading(new DateOnly(2026, 10, 9), new DateOnly(2026, 10, 9)));
Assert.AreEqual("Mercoledì 7 ottobre", DiaryView.Heading(new DateOnly(2026, 10, 7), new DateOnly(2026, 10, 9)));
}
}