Files
Anubis/tests/Anubis.Tests/NewsScreenTests.cs
T
Alby96andClaude Opus 5.5 959fe6ccba
ci / test (postgres) (pull_request) Successful in 9m38s
ci / test (sqlite) (pull_request) Successful in 5m26s
ci / image (pull_request) Successful in 2m23s
ci / test (postgres) (push) Successful in 9m28s
ci / test (sqlite) (push) Successful in 5m3s
ci / image (push) Successful in 1m56s
Show the news and the market, and set news and calendar from the settings (refs #60)
The news screen of SPEC 13 lists what the bot read in the last 24 hours and
what it did about each story, with the three filters of the mockup, the mood
of the market, the calendar with the effect of each event, the sources and
the spending of the day. Each note of the bot now keeps its action sentence
and the end of its restriction, so the screen shows the decision as it was.

Settings gain a news section: the rows of SPEC 10.5, the sources (enable and
trust), the key and daily cap of the language model, the Finnhub and FRED
keys and the central bank meetings. The demo seeds the F.9 data and matches
the mockup; the overview tile now shows the real news that matter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:43:09 +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 con un effetto in corso.", "Con effetto, 2", "Sulle tue posizioni, 9", "Tutte, 312",
"Oggi 06:10, da CoinDesk", "Cosa ho fatto:</strong> per 24 ore non aumento la posizione su SOL. Lo stop resta dov'è.",
"Neutra, evento in arrivo", "niente nuovi acquisti di mean reversion su JPM fino a martedì. La posizione di momentum resta.",
"Mercato USA", "Una sola fonte", "Negativa, non confermata", "Leggermente positiva", "Importanza 3 su 5", "Importanza 2 su 5",
"niente, perché nessun'altra fonte la riportava. Ricontrollata alle 18:20: rientrata.", "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: niente mean reversion fino a martedì",
"Mercoledì 14 ottobre, 14:30", "Impatto alto: nessun nuovo ingresso dalle 14:00 alle 15:00",
"Mercoledì 28 ottobre, 19:00", "Impatto alto: nessun nuovo ingresso dalle 18:30 alle 20:00",
"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 con un effetto in corso.");
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);
}
}