Files
Anubis/tests/Anubis.Tests/StrategyScreensTests.cs
Alby96andClaude Opus 5.5 fc5df0146e
ci / test (postgres) (push) Successful in 4m39s
ci / test (sqlite) (push) Successful in 2m57s
ci / image (push) Successful in 56s
ci / test (postgres) (pull_request) Successful in 5m27s
ci / test (sqlite) (pull_request) Successful in 3m14s
ci / image (pull_request) Successful in 10s
Prepare strategies before the host is ready; stop demo servers first (refs #44 #45)
Loading the outcomes before "ready" was not enough: on a fresh database the
strategy rows did not exist yet, so the load did nothing and CI run 220
failed the same way on PostgreSQL. The new TradingService.PrepareAsync
creates accounts and strategies, then loads the outcomes; the host runs it
before it is ready and logs a failure without blocking the interface.
StartAsync repeats it, which changes nothing.

The demo tests deleted the demo folder while the server still held its
SQLite file, which Windows refuses at random. They now stop the server
first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:19:15 +01:00

208 lines
11 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Risk;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The Operazioni, Strategie and Rischio screens and the risk part of Impostazioni (issue #45; mockups 03, 04, 07).
/// </summary>
[TestClass]
public sealed class StrategyScreensTests
{
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDemoShowsTradesStrategiesAndRiskAsInTheMockups()
{
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
// Mockup 03: the balance of the 41 trades of appendix F, and the "why" of each from the decisions.
var trades = await server.TextAsync("/operazioni");
foreach (var text in new[]
{
"1,62", "+239,27", "22 su 41", "53,7%", "+28,42", "20,31", "14,82", "Mostrate 20 di 41", "Tornata sopra la media a 5 giorni",
"Perché l'ho comprata", "Tutti i limiti di rischio rispettati", "Stop di protezione raggiunto",
})
{
StringAssert.Contains(trades, text, $"Missing {text} on Operazioni.");
}
StringAssert.Contains(await server.TextAsync("/operazioni?esito=perdite"), "Mostrate 19 di 19");
using (var csv = await server.GetAsync("/api/operazioni.csv"))
{
Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode);
Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType);
var lines = System.Text.Encoding.UTF8.GetString((await csv.Content.ReadAsByteArrayAsync())[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries);
Assert.HasCount(42, lines, "a header and the 41 trades");
}
// Mockup 04: the four stages, 58 days of 60, the same result as on Conti.
var strategies = await server.TextAsync("/strategie");
foreach (var text in new[] { "Il percorso verso i soldi veri", "Reale ridotto", "3 strategie", "+231,60", "Giorni in simulazione", "58", "Disponibile tra 2 giorni" })
{
StringAssert.Contains(strategies, text, $"Missing {text} on Strategie.");
}
Assert.IsFalse(strategies.Contains("/azioni/strategie/", StringComparison.Ordinal), "The demo changes no stage.");
// Mockup 07: no block, the limits with their use, the worst fall of the demo, the scenarios.
var risk = await server.TextAsync("/rischio");
foreach (var text in new[] { "Nessun blocco attivo", "64,1%", "2,82% il 5 set", "Se succedesse domani", "465", "Cosa il bot non può fare, mai" })
{
StringAssert.Contains(risk, text, $"Missing {text} on Rischio.");
}
var settings = await server.TextAsync("/impostazioni");
StringAssert.Contains(settings, "Perdita in un giorno (%)");
Assert.IsFalse(settings.Contains("/azioni/rischio/limiti", StringComparison.Ordinal), "No risk form in the demo.");
}
finally
{
// The server first: on Windows a database still open cannot be deleted.
await server.DisposeAsync();
TempFolder.Delete(demoRoot);
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AStrategyThatFailedItsBacktestCannotEnterTheSimulation()
{
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
await server.SignInFirstTimeAsync();
// The outcome file of crypto_trend says "not passed"; the stock ones wait for the Alpaca keys.
var page = await server.TextAsync("/strategie");
StringAssert.Contains(page, "Non supera i test");
StringAssert.Contains(page, "In attesa dei dati");
Assert.IsFalse(page.Contains("/azioni/strategie/crypto_trend/simulazione", StringComparison.Ordinal), "No button for a strategy that did not pass.");
using var refused = await server.PostFormAsync("/strategie", "/azioni/strategie/crypto_trend/simulazione");
Assert.AreEqual("/strategie?errore=backtest", ServerHarness.Location(refused));
Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(StrategyNames.CryptoTrend, CancellationToken.None))!.Stage);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task LimitsGoDownFreelyAndUpOnlyWithThePhraseWhileAStrategyUsesRealMoney()
{
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
var password = await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
var daily = RiskSettings.DailyLoss.Key;
// Not through the API: there the order of the limits and the procedure of SPEC 12.4 would be skipped.
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + RiskSettings.DrawdownStop.Key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "40" }) })
{
request.Headers.Add(csrf!["header"], csrf["token"]);
using var put = await server.Http.SendAsync(request);
Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode);
}
Assert.AreEqual("15", (await services.Settings.GetAsync(RiskSettings.DrawdownStop.Key, CancellationToken.None)).Value);
// Out of range, or the halving after the switch: nothing changes.
using (var wrong = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "50")))
{
Assert.AreEqual("/impostazioni?errore=limite#rischio", ServerHarness.Location(wrong));
}
using (var order = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (RiskSettings.DrawdownHalf.Key, "20")))
{
Assert.AreEqual("/impostazioni?errore=ordine-limiti#rischio", ServerHarness.Location(order));
}
// Lower is always allowed.
using (var lower = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1,5")))
{
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lower));
}
Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value);
// A strategy with real money: raising needs the phrase and the password, and the form asks for them.
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = @s", CancellationToken.None,
("s", StrategyNames.CryptoTrend)), CancellationToken.None);
StringAssert.Contains(await server.TextAsync("/impostazioni"), StageBook.RaisePhrase);
using (var bare = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2")))
{
Assert.AreEqual("/impostazioni?errore=frase-rischio#rischio", ServerHarness.Location(bare));
}
using (var badPassword = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", "not-it")))
{
Assert.AreEqual("/impostazioni?errore=password-rischio#rischio", ServerHarness.Location(badPassword));
}
Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value, "Refused raises change nothing.");
using (var confirmed = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", password)))
{
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(confirmed));
}
Assert.AreEqual("2", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value);
// Lowering again needs nothing, even now.
using var lowerAgain = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1"));
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lowerAgain));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task StopCloseAndRestartGoThroughTheRiskEngine()
{
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
async Task<string> StateAsync() => (await services.Settings.GetAsync(SettingsStore.BotState.Key, CancellationToken.None)).Value;
using (var stop = await server.PostFormAsync("/rischio", "/azioni/bot/ferma", ("ritorno", "/rischio")))
{
StringAssert.StartsWith(ServerHarness.Location(stop), "/rischio");
}
Assert.AreEqual("stopped", await StateAsync());
StringAssert.Contains(await server.TextAsync("/rischio"), "Riparti");
// With the STOP file in the data folder the restart is refused.
var stopFile = services.Trading!.Risk!.StopFile!;
await File.WriteAllTextAsync(stopFile, "");
using (var refused = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
{
StringAssert.Contains(ServerHarness.Location(refused), "errore=file-stop");
}
Assert.AreEqual("stopped", await StateAsync());
File.Delete(stopFile);
using (var restart = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
{
Assert.IsFalse(ServerHarness.Location(restart).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(restart));
}
Assert.AreEqual("active", await StateAsync());
// The switch tripped by itself in the simulation: the bot stays "active" elsewhere, and the page offers the restart.
await services.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, 'simulated', @j, @t, @t)",
CancellationToken.None, ("id", Guid.NewGuid()), ("j", new DbJson("{\"tripped\":true}")), ("t", DateTimeOffset.UtcNow)), CancellationToken.None);
var page = await server.TextAsync("/rischio");
StringAssert.Contains(page, "Interruttore scattato nel mondo simulato");
StringAssert.Contains(page, "Riparti");
using (var again = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
{
Assert.IsFalse(ServerHarness.Location(again).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(again));
}
Assert.IsFalse(await services.Trading.Risk.AnyTrippedAsync(CancellationToken.None));
Assert.AreEqual("active", await StateAsync());
}
}