Files
Anubis/tests/Anubis.Tests/NewsScreenTests.cs
T
Alby96andClaude Opus 5.5 501c9be70e
ci / test (postgres) (push) Successful in 5m56s
ci / test (sqlite) (push) Successful in 5m5s
ci / test (postgres) (pull_request) Successful in 5m36s
ci / test (sqlite) (pull_request) Successful in 4m52s
ci / image (push) Successful in 2m6s
ci / image (pull_request) Successful in 52s
Phase 11: decisions from the numbers only, outside rules measured in the shadow
News, the economic calendar and earnings dates no longer change any decision by
default (ADR 0023). A new switch, decisions.external_rules, chooses between
"misurate" (default) and "attive" (the Phase 7 behaviour); ADR 0027 records
every choice.

- Engine: with "misurate" nothing is held, postponed or kept, no diary or note
  is written and equity_meanrev gets no earnings dates. The gate is still asked,
  per rule and with all rows on, to write one shadow case per rule, strategy,
  instrument and day. The switch is read once per decision; the one-step check
  and the release of a planned order read it as it was when the decision ran.
- Shadow: five rules measured with the existing improvement machinery, 99%
  interval, "too early" under six months, the ADR 0023 criterion; the earnings
  exit is measured by relabelling with the report date. Shown in the Laboratorio
  and in the quarterly review beside the historical restriction balance.
- Model: the seven outside clues stay out of training; a champion that uses one
  is set aside at once, without an alarm, and Sunday trains one without them.
- Settings: the switch changes only from the settings form, with the
  protections of the five rows; the API refuses it; each change writes one diary
  line. The first start of this version records "attive" until then on an
  installation that had already decided.
- Screens, demo and manual follow "misurate".

Two independent review rounds; their confirmed findings are fixed and tested.
SQLite, PostgreSQL and the image with the guard drill are green.

refs #116, refs #117

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 22:59:16 +01:00

225 lines
15 KiB
C#

using System.Net;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.News;
namespace Anubis.Tests;
/// <summary>The Notizie e mercato screen and the news part of Impostazioni (issue #60; SPEC 13.5, 13.6, mockup 05).</summary>
[TestClass]
public sealed class NewsScreenTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
/// <summary>
/// Each story of the last 24 hours says what the bot did, or why it did nothing; the effects still in force come
/// first, and an older restriction still in force stays on the list. Switching a rule off ends its restriction.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheBoardSaysWhatTheBotDidAboutEachStoryAndWhy()
{
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var clock = new ManualClock(Now);
var specs = new[] { "ETH-EUR", "SOL-EUR", "ADA-EUR", "BTC-EUR" }.ToDictionary(s => s[..3], s => MarketDataStoreTests.Okx(s));
var catalog = new InstrumentCatalog(test.Db, clock);
await catalog.SyncAsync(Venues.Okx, [.. specs.Values], complete: false, _none).ConfigureAwait(false);
var sol = (await catalog.ListAsync(Venues.Okx, _none).ConfigureAwait(false)).Single(i => i.Symbol == "SOL-EUR").Id;
await test.Db.WriteAsync(async s =>
{
var account = Ids.NewId(clock);
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t)",
_none, ("id", account), ("t", Now)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at, created_at, updated_at) " +
"VALUES (@id, @a, @i, 'crypto_trend', 2, 130, 128, 120, @t, @t, @t)", _none, ("id", Ids.NewId(clock)), ("a", account), ("i", sol), ("t", Now)).ConfigureAwait(false);
}, _none).ConfigureAwait(false);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana upgrade delayed by a week", Now.AddHours(-2), 3, -0.7, "CoinDesk", trusted: true,
seen: Now.AddHours(-2)).ConfigureAwait(false);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["ADA"], "Cardano exchange hacked", Now.AddHours(-1), 4, -0.9, "CoinDesk", trusted: true, seen: Now.AddHours(-1))
.ConfigureAwait(false);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["ETH"], "Ether rallies on ETF inflows", Now.AddHours(-3), 2, 0.5, "CoinDesk", trusted: true, seen: Now.AddHours(-3))
.ConfigureAwait(false);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["BTC"], "Bitcoin slips as traders take profit", Now.AddHours(-4), 2, -0.4, "CoinDesk", trusted: true,
seen: Now.AddHours(-4)).ConfigureAwait(false);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana validators report outage", Now.AddMinutes(-30), 3, -0.8, "The Block", trusted: false)
.ConfigureAwait(false);
var market = await NewsRulesTests.StoryAsync(test.Db, clock, specs["ETH"], "Fed minutes show caution on cuts", Now.AddHours(-5), 1, -0.5, "Federal Reserve", trusted: true,
seen: Now.AddHours(-5)).ConfigureAwait(false);
await test.Db.WriteAsync(s => s.ExecuteAsync("UPDATE news_links SET scope = 'market', target = 'market' WHERE story_id = @id", _none, ("id", (object?)market)), _none).ConfigureAwait(false);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["ETH"], "Ether bridge exploited", Now.AddHours(-30), 3, -0.8, "CoinDesk", trusted: true, seen: Now.AddHours(-30))
.ConfigureAwait(false);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["BTC"], "Bitcoin exchange halts withdrawals after hack", Now.AddHours(-50), 4, -0.9, "CoinDesk", trusted: true,
seen: Now.AddHours(-50)).ConfigureAwait(false);
// SOL is held: the watcher writes its notes. ADA and BTC are neither held nor candidates: the board says the rule all the same.
await new NewsWatcher(test.Db, clock).RunOnceAsync(_none).ConfigureAwait(false);
var settings = new SettingsStore(test.Db, clock, new EventBus());
var board = await new NewsBoard(test.Db, clock, settings).LoadAsync(_none).ConfigureAwait(false);
Assert.AreEqual(6, board.Read, "The six stories first seen in the last 24 hours.");
Assert.AreEqual(3, board.Active, "SOL for 24 hours, ADA and BTC for 72.");
Assert.AreEqual(3, board.OnPositions, "The two stories on SOL and the one on the market.");
CollectionAssert.AreEqual(new[]
{
"Cardano exchange hacked", "Solana upgrade delayed by a week", "Bitcoin exchange halts withdrawals after hack",
"Solana validators report outage", "Ether rallies on ETF inflows", "Bitcoin slips as traders take profit", "Fed minutes show caution on cuts",
}, board.Rows.Select(r => r.Title).ToList(), "Effects in force first, then the latest; the restriction that ended 6 hours ago is gone.");
var rows = board.Rows.ToDictionary(r => r.Title);
Assert.AreEqual("Per 24 ore non aumento la posizione su SOL.", rows["Solana upgrade delayed by a week"].Action);
Assert.AreEqual("Per 72 ore niente nuovi acquisti di ADA.", rows["Cardano exchange hacked"].Action);
Assert.AreEqual("Niente, perché nessun'altra fonte la riportava. La ricontrollo alle 13:00.", rows["Solana validators report outage"].Action);
Assert.AreEqual("Negativa, non confermata", rows["Solana validators report outage"].Tone);
Assert.IsTrue(rows["Solana validators report outage"].SingleSource);
Assert.AreEqual("Niente. Le notizie positive non mi fanno comprare: servono solo a evitare guai.", rows["Ether rallies on ETF inflows"].Action);
Assert.AreEqual("Leggermente positiva", rows["Ether rallies on ETF inflows"].Tone);
Assert.AreEqual(1, rows["Ether rallies on ETF inflows"].Direction);
Assert.AreEqual("Niente. Le notizie solo leggermente negative non creano restrizioni.", rows["Bitcoin slips as traders take profit"].Action);
Assert.AreEqual("Niente. Riguarda il mercato nel suo insieme: le restrizioni valgono per un singolo strumento.", rows["Fed minutes show caution on cuts"].Action);
Assert.AreEqual("Mercato", rows["Fed minutes show caution on cuts"].About);
Assert.AreEqual("SOL", rows["Solana upgrade delayed by a week"].About);
Assert.AreEqual(-1, rows["Solana upgrade delayed by a week"].Direction);
// The user switches the negative row off: SOL's restriction no longer holds, ADA's (a serious event) still does.
await settings.SetAsync(NewsRuleSettings.Negative.Key, NewsRuleSettings.Off, "test", _none).ConfigureAwait(false);
var off = (await new NewsBoard(test.Db, clock, settings).LoadAsync(_none).ConfigureAwait(false)).Rows.ToDictionary(r => r.Title);
Assert.IsFalse(off["Solana upgrade delayed by a week"].Active);
StringAssert.EndsWith(off["Solana upgrade delayed by a week"].Action, "Ora la regola è spenta: la restrizione non vale più.");
Assert.IsTrue(off["Cardano exchange hacked"].Active);
}
/// <summary>The demo of appendix F.9 as in the mockup: rows, filters, mood, calendar, sources and spending.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDemoShowsTheNewsAndTheMarketAsInTheMockup()
{
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
var page = await server.TextAsync("/notizie");
foreach (var text in new[]
{
"312 notizie lette nelle ultime 24 ore, 2 su cui una regola avrebbe agito.", "Con una regola, 2", "Archivio: le notizie non cambiano nessuna decisione.", "Sulle tue posizioni, 9", "Tutte, 312",
"Oggi 06:10, da CoinDesk", "Cosa avrebbe fatto la regola:</strong> avrebbe fermato per 24 ore gli aumenti della posizione su SOL/EUR. Solo registrato.",
"Neutra, evento in arrivo", "con le regole attive niente nuovi acquisti di mean reversion su JPM prima dei conti. Solo registrato.",
"Mercato USA", "Una sola fonte", "Negativa, non confermata", "Leggermente positiva", "Importanza 3 su 5", "Importanza 2 su 5",
"niente. Riguarda il mercato nel suo insieme: le restrizioni valgono per un singolo strumento.", "Mostra le altre 3",
"Crypto: paura o avidità", "su 100, paura", "17,8", "calmo", "+0,006%", "nella norma",
"Oggi, 16:00", "Fiducia dei consumatori USA", "Impatto medio: nessun blocco",
"Martedì 13 ottobre, prima dell'apertura", "Riguarda JPM: con le regole attive niente mean reversion fino a martedì. Solo registrato.",
"Mercoledì 14 ottobre, 14:30", "Impatto alto: con le regole attive nessun nuovo ingresso dalle 14:00 alle 15:00. Solo registrato.",
"Mercoledì 28 ottobre, 19:00", "Impatto alto: con le regole attive nessun nuovo ingresso dalle 18:30 alle 20:00. Solo registrato.",
"Alpaca News", "in tempo reale", "14 testate e banche centrali", "Comunicati alla SEC", "aggiornato alle 08:00",
"oggi è costato 0,04 € su un tetto di 0,50 €",
})
{
StringAssert.Contains(page, text, $"Missing {text} on Notizie e mercato.");
}
// The order of the mockup: the two effects in force, then the latest.
var order = new[] { "Rinviato di una settimana", "JPMorgan pubblica i conti", "I verbali della banca centrale", "Un analista alza", "Un exchange segnala", "Richieste di sussidi" }
.Select(t => page.IndexOf(t, StringComparison.Ordinal)).ToList();
CollectionAssert.AreEqual(order.Order().ToList(), order, "Rows in the order of the mockup.");
Assert.IsTrue(order.All(i => i >= 0));
var active = await server.TextAsync("/notizie?filtro=effetto");
StringAssert.Contains(active, "Rinviato di una settimana");
Assert.IsFalse(active.Contains("Un analista alza", StringComparison.Ordinal), "Only the effects in force.");
var settings = await server.TextAsync("/impostazioni");
StringAssert.Contains(settings, "Notizie e calendario");
StringAssert.Contains(settings, NewsRuleSettings.Severe.Label);
Assert.IsFalse(settings.Contains("/azioni/notizie/fonti/", StringComparison.Ordinal), "The demo changes no source.");
Assert.IsFalse(settings.Contains("/azioni/chiavi-dati/", StringComparison.Ordinal), "The demo takes no key.");
}
finally
{
// The server first: on Windows a database still open cannot be deleted.
await server.DisposeAsync();
TempFolder.Delete(demoRoot);
}
}
/// <summary>The news part of Impostazioni: sources, rows of 10.5, cap and keys; every change in the change log, no key ever shown.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheSettingsChangeSourcesRulesCapAndKeys()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
// A new installation without market data: the screen says what is missing.
var empty = await server.TextAsync("/notizie");
StringAssert.Contains(empty, "0 notizie lette nelle ultime 24 ore, nessuna su cui una regola avrebbe agito.");
StringAssert.Contains(empty, "Non leggo ancora notizie");
var store = new NewsStore(services.Db, server.Host.Clock);
await store.EnsureDefaultsAsync(_none);
var coindesk = (await store.ListSourcesAsync(_none)).Single(s => s.Name == "CoinDesk");
Assert.IsTrue(coindesk.Trusted);
using (var response = await server.PostFormAsync("/impostazioni", $"/azioni/notizie/fonti/{coindesk.Id}", ("attiva", "on")))
{
Assert.AreEqual("/impostazioni?ok=fonte#notizie", ServerHarness.Location(response));
}
var after = (await store.ListSourcesAsync(_none)).Single(s => s.Name == "CoinDesk");
Assert.IsTrue(after.Enabled);
Assert.IsFalse(after.Trusted, "The unchecked box takes the trust away.");
var history = await services.Settings.HistoryAsync(null, 10, _none);
Assert.IsTrue(history.Any(h => h.Key == "news.source:CoinDesk"), "The change is in the change log.");
using (var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{NewsRuleSettings.Severe.Key}", ("valore", "off"), ("ritorno", "/impostazioni#notizie")))
{
Assert.AreEqual("/impostazioni#notizie", ServerHarness.Location(response));
}
Assert.IsFalse((await NewsRuleSettings.LoadAsync(services.Settings, _none)).Severe);
using (var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{NewsModelSettings.DailyCap.Key}", ("valore", "0,75"), ("ritorno", "/impostazioni#notizie")))
{
Assert.AreEqual("/impostazioni#notizie", ServerHarness.Location(response));
}
Assert.AreEqual(0.75m, await NewsModelSettings.CapAsync(services.Settings, _none));
using (var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{NewsModelSettings.DailyCap.Key}", ("valore", "tanto"), ("ritorno", "/impostazioni#notizie")))
{
StringAssert.Contains(ServerHarness.Location(response), "errore=tetto");
}
const string typed = "chiave-di-prova-finnhub";
using (var response = await server.PostFormAsync("/impostazioni", "/azioni/chiavi-dati/FINNHUB_API_KEY", ("chiave", typed)))
{
Assert.AreEqual("/impostazioni?ok=chiave#notizie", ServerHarness.Location(response));
}
Assert.AreEqual(typed, await services.Secrets.RevealAsync("FINNHUB_API_KEY", _none));
var page = await server.TextAsync("/impostazioni");
Assert.IsFalse(page.Contains(typed, StringComparison.Ordinal), "A saved key is never shown again.");
StringAssert.Contains(page, "Chiave di Finnhub</strong>: Impostata");
using (var response = await server.PostFormAsync("/impostazioni", "/azioni/chiavi-dati/FRED_API_KEY", ("chiave", "with space")))
{
StringAssert.Contains(ServerHarness.Location(response), "errore=chiave");
}
using (var response = await server.PostFormAsync("/impostazioni", "/azioni/chiavi-dati/OKX_API_KEY", ("chiave", "abc")))
{
StringAssert.Contains(ServerHarness.Location(response), "errore=impostazione", "Broker keys go through their own form, with the withdrawal check.");
}
using (var response = await server.PostFormAsync("/impostazioni", "/azioni/chiavi-dati/FINNHUB_API_KEY/togli"))
{
Assert.AreEqual("/impostazioni?ok=chiave-tolta#notizie", ServerHarness.Location(response));
}
Assert.IsNull(await services.Secrets.RevealAsync("FINNHUB_API_KEY", _none));
Assert.AreEqual(HttpStatusCode.OK, (await server.GetAsync("/notizie")).StatusCode);
}
}