Files
Anubis/tests/Anubis.Tests/AccountsScreenTests.cs
Alby96andClaude Opus 5.5 81d6c5f667 Fix what the review of Phase 9 found in accounts, access, capital, health and publication
A position left out together with its stop kept the account prudent for good: the
stop was still asked for shares that no longer exist. The cover required now stops
at what the account holds, the stops are compared again after the choice, and where
one is still missing Align takes the excluded position up again. After the choice
the account waits for the stop with its own reason, so it returns to normal by
itself also past the 15 minutes; a new difference still gets its own 15 minutes.

A right password alone no longer clears the wrong second-factor codes: it takes
back only its own attempt.

Capital and shares are planned and written in one transaction, so overlapping
changes cannot apply twice and an interruption leaves nothing halfway; sending the
same figures again completes what an old one left. The cash that purchases under
way still hold is no longer given away, counted as the risk engine counts it.

/health said healthy when the trading engine had failed to start. It now says so at
once, or after ten minutes of a stalled start, and the host tries the start again
every minute; the guard still sees a start that does not move.

The image of the manual publication says its version and its commit, marked when
the tree is dirty, and publish.sh refuses before any login an image that does not
come from the commit of the tag.

refs #75

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

261 lines
15 KiB
C#

using System.Net;
using Anubis.Db;
using Anubis.Server;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The Conti e posizioni screen and the accounts part of Impostazioni (issue #32).</summary>
[TestClass]
public sealed class AccountsScreenTests
{
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheDemoShowsTheFiguresOfTheMockup()
{
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
var demoRoot = server.Host.Config.Data.Root;
try
{
var page = await server.TextAsync("/conti");
// Mockup 02: totals, the two cards, the stops. The ledger computes them from the seeded rows.
foreach (var figure in new[]
{
"10.412,46", "6.671,13", "3.741,33", "4.231,60", "1.905,10", "2.326,50", "+163,45", "+68,15", "14,49",
"6.180,86", "7.170,41", "1.836,23", "2.130,21", "4.344,63", "5.040,20", "+75,83", "+105,03", "0,33",
"+231,60", "+5,79%", "+180,86", "+3,01%", "22,3%", "37,5%", "4,3%", "35,9%", "59,4%", "40,6%",
})
{
StringAssert.Contains(page, figure, $"Missing {figure} on the Conti page.");
}
StringAssert.Contains(page, "Attivo, aggiornato oggi alle 02:06");
StringAssert.Contains(page, "Attivo dal 7 ottobre");
StringAssert.Contains(page, "5 stop permanenti");
StringAssert.Contains(page, "6 stop giornalieri");
StringAssert.Contains(page, "In coda per l'apertura delle 15:30");
StringAssert.Contains(page, "Registro interno coerente (controllo delle 08:20)");
StringAssert.Contains(page, "i prelievi sono disattivati");
StringAssert.Contains(page, "circa 309");
Assert.IsLessThan(page.IndexOf("Vendi 0,262", StringComparison.Ordinal), page.IndexOf("Vendi 0,0182", StringComparison.Ordinal), "The largest stop comes first.");
// The filter keeps one account; the CSV has one row per position, for a spreadsheet.
var okx = await server.TextAsync("/conti?conto=okx");
Assert.IsFalse(okx.Contains("NVDA", StringComparison.Ordinal));
using var csv = await server.GetAsync("/api/conti/posizioni.csv");
Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode);
Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType);
var bytes = await csv.Content.ReadAsByteArrayAsync();
CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3], "Excel reads the accents only with the BOM.");
var lines = System.Text.Encoding.UTF8.GetString(bytes[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries);
Assert.HasCount(11, lines);
StringAssert.StartsWith(lines[1], "BTC/EUR;Bitcoin;okx;crypto_trend;0,0182;68950;71420;EUR;1299,84;44,95;66180;", lines[1]);
var settings = await server.TextAsync("/impostazioni");
StringAssert.Contains(settings, "Conti e chiavi");
StringAssert.Contains(settings, "Nella modalità dimostrativa chiavi e capitale non si cambiano.");
Assert.IsFalse(settings.Contains("/azioni/capitale/", StringComparison.Ordinal), "No capital 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 KeysAreAskedToTheBrokerBeforeTheyAreKept()
{
var network = new FakeHttp()
.On(u => u.AbsolutePath == "/api/v5/account/config", _ => FakeHttp.Respond(Fixture.Text("okx-trading/account-config.json")))
.On(u => u.AbsolutePath == "/v2/account", _ => FakeHttp.Respond(Fixture.Text("alpaca-trading/account.json")))
.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 secrets = server.Host.Services!.Secrets;
// The documentation's OKX key may withdraw: refused, nothing saved.
using (var okx = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/okx",
("OKX_API_KEY_DEMO", "test-okx-key"), ("OKX_API_SECRET_DEMO", "test-okx-secret"), ("OKX_API_PASSPHRASE_DEMO", "test-okx-pass")))
{
Assert.AreEqual("/impostazioni?errore=prelievo#conti", ServerHarness.Location(okx));
}
Assert.IsFalse((await secrets.StatusAsync("OKX_API_KEY_DEMO")).IsSet);
// A missing field never reaches the broker.
using (var empty = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", " ")))
{
Assert.AreEqual("/impostazioni?errore=chiavi-vuote#conti", ServerHarness.Location(empty));
}
// Alpaca keys never withdraw and this account may trade: kept, encrypted, never shown again; the engine restarts with them.
using (var alpaca = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", "test-alpaca-secret")))
{
Assert.AreEqual("/impostazioni?ok=chiavi#conti", ServerHarness.Location(alpaca));
}
await server.WaitForAsync(HostMode.Ready);
secrets = server.Host.Services!.Secrets;
Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO")).IsSet);
var settings = await server.TextAsync("/impostazioni");
Assert.IsFalse(settings.Contains("test-alpaca-secret", StringComparison.Ordinal), "A saved key is never shown again.");
StringAssert.Contains(settings, "Impostata");
// Every form needs its antiforgery token, also the ones that send no field.
foreach (var path in new[] { "/azioni/chiavi/alpaca/togli", "/azioni/conti/" + Guid.NewGuid() + "/allinea" })
{
using var forged = await server.Http.PostAsync(new Uri(path, UriKind.Relative), new FormUrlEncodedContent([]));
Assert.AreEqual(HttpStatusCode.BadRequest, forged.StatusCode, path);
}
Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO")).IsSet, "A forged request removes nothing.");
// The engine starts in the background after "ready": the paper account appears within moments.
var accounts = new List<string>();
for (var i = 0; i < 100 && accounts.Count == 0; i++)
{
accounts = [.. await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT name FROM accounts WHERE environment = 'demo'", r => r.Text("name")))];
if (accounts.Count == 0)
{
await Task.Delay(100);
}
}
CollectionAssert.AreEqual(new[] { "Alpaca paper" }, accounts.ToArray());
// Capital in euro, as people type it; dollars need the ECB rate first.
using (var capital = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "1.500,50")))
{
Assert.AreEqual("/impostazioni?ok=capitale#conti", ServerHarness.Location(capital));
}
using (var usd = await server.PostFormAsync("/impostazioni", "/azioni/capitale/alpaca", ("euro", "2000")))
{
Assert.AreEqual("/impostazioni?errore=cambio#conti", ServerHarness.Location(usd));
}
using (var bad = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "molto")))
{
Assert.AreEqual("/impostazioni?errore=importo#conti", ServerHarness.Location(bad));
}
var changes = await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT broker, amount_eur FROM capital_changes", r => (r.Text("broker"), r.Money("amount_eur"))));
CollectionAssert.AreEqual(new[] { ("okx", 1500.50m) }, changes.ToArray());
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Trend crypto: quota 100%");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AMissingStopWhereAPositionWasLeftOutOffersBothChoicesAgain()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var db = server.Host.Services!.Db;
var account = Guid.NewGuid();
var now = DateTimeOffset.UtcNow;
async Task<string> PageAsync(string reason, DateTimeOffset since, params string[] excluded)
{
var differences = System.Text.Json.JsonSerializer.Serialize(new
{
Current = new[] { new AccountDifference(DifferenceKinds.Stop, "BTC-EUR", 0.00598m, 0m, "BTC-EUR: gli stop coprono 0 su 0,00598.") },
Excluded = excluded,
});
await db.WriteAsync(async s =>
{
await s.ExecuteAsync("DELETE FROM account_status");
await s.ExecuteAsync("INSERT INTO account_status (id, account_id, mode, mode_since, mode_reason, differences, last_reconciled_at, last_outcome, created_at, updated_at) " +
"VALUES (@id, @a, 'prudent', @since, @r, @d, @now, 'different', @now, @now)",
("id", Guid.NewGuid()), ("a", account), ("since", since), ("r", reason), ("d", new DbJson(differences)), ("now", now));
});
return await server.TextAsync("/conti");
}
await db.WriteAsync(s => s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX demo', 'okx', 'demo', 'EUR', @t)",
("id", account), ("t", now)));
var both = await PageAsync(Reconciler.StopReason, now.AddMinutes(-20), "position:BTC-EUR:0.00998:0.00598");
StringAssert.Contains(both, "Allinea il registro al conto");
StringAssert.Contains(both, "Lascia fuori ciò che non è del bot");
StringAssert.Contains(both, "dove avevi lasciato fuori una differenza");
// Another instrument's exclusion has nothing to do with it, and after a choice nobody is told to choose again.
var again = await PageAsync(Reconciler.StopReason, now.AddMinutes(-20), "position:ETH-EUR:1:0");
StringAssert.Contains(again, "Ricontrolla adesso");
Assert.DoesNotContain("Allinea il registro al conto", again);
var waiting = await PageAsync(Reconciler.StopReason, now.AddMinutes(-2), "position:BTC-EUR:0.00998:0.00598");
StringAssert.Contains(waiting, "torna normale da solo quando c'è");
StringAssert.Contains(await PageAsync(DifferenceKinds.Stop, now.AddMinutes(-2)), "Se entro 15 minuti si spiega da sola");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheUserSplitsTheCapitalAndWithRealMoneyOnlyThroughTheProcedure()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true);
var password = await server.SignInFirstTimeAsync();
var db = server.Host.Services!.Db;
async Task<string> SplitAsync(string momentum, string meanrev, params (string, string)[] more)
{
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/quote/alpaca",
[("quota-" + StrategyNames.EquityMomentum, momentum), ("quota-" + StrategyNames.EquityMeanrev, meanrev), .. more]);
return ServerHarness.Location(answer);
}
Task<List<decimal?>> SharesAsync() => db.ReadAsync(s => s.QueryAsync("SELECT share FROM strategy_state WHERE strategy IN (@m, @r) ORDER BY strategy DESC",
r => r.MoneyOrNull("share"), ("m", StrategyNames.EquityMomentum), ("r", StrategyNames.EquityMeanrev)));
var page = await server.TextAsync("/impostazioni");
StringAssert.Contains(page, "Ripartizione tra le strategie di Alpaca");
Assert.DoesNotContain("Ripartizione tra le strategie di OKX", page, "A single strategy has nothing to split.");
Assert.AreEqual("/impostazioni?ok=quote#conti", await SplitAsync("62,5%", "37,5"));
CollectionAssert.AreEqual(new decimal?[] { 0.625m, 0.375m }, (await SharesAsync()).ToArray());
foreach (var (momentum, meanrev) in new[] { ("60", "30"), ("110", "-10"), ("molto", "40"), ("", "") })
{
Assert.AreEqual("/impostazioni?errore=quote#conti", await SplitAsync(momentum, meanrev), momentum + "/" + meanrev);
}
using (var unknown = await server.PostFormAsync("/impostazioni", "/azioni/quote/binance", ("quota-x", "100")))
{
Assert.AreEqual("/impostazioni?errore=conto#conti", ServerHarness.Location(unknown));
}
// The old and the new value stay, in the changes and in the diary; the same split again adds nothing.
Assert.AreEqual("/impostazioni?ok=quote#conti", await SplitAsync("62,5", "37,5"));
var log = await db.ReadAsync(s => s.QueryAsync("SELECT old_value, new_value FROM config_history WHERE key = @k", r => (r.Text("old_value"), r.Text("new_value")),
("k", "strategy." + StrategyNames.EquityMomentum + ".share")));
Assert.HasCount(1, log);
StringAssert.Contains(log[0].Item2, "62,5%");
var diary = await db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'shares_changed'", r => r.Text("message")));
Assert.HasCount(1, diary);
StringAssert.Contains(diary[0], "→ 62,5%");
Assert.DoesNotContain(StrategyNames.EquityMomentum, diary[0]);
// Real money on the account: any new split needs the phrase and the password.
await db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = @s", ("s", StrategyNames.EquityMomentum)));
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Una strategia di questo conto usa soldi veri");
Assert.AreEqual("/impostazioni?errore=frase-rischio#conti", await SplitAsync("50", "50"));
Assert.AreEqual("/impostazioni?errore=password-rischio#conti", await SplitAsync("50", "50", ("frase", StageBook.RaisePhrase), ("password", "sbagliata")));
CollectionAssert.AreEqual(new decimal?[] { 0.625m, 0.375m }, (await SharesAsync()).ToArray());
Assert.AreEqual("/impostazioni?ok=quote#conti", await SplitAsync("50", "50", ("frase", StageBook.RaisePhrase), ("password", password)));
CollectionAssert.AreEqual(new decimal?[] { 0.5m, 0.5m }, (await SharesAsync()).ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow("4000", "4000")]
[DataRow("1.500", "1500")]
[DataRow("1.500,50", "1500.50")]
[DataRow("1500,5", "1500.5")]
[DataRow("1500.50", "1500.50")]
[DataRow(" 2 000 € ", "2000")]
[DataRow("10,999", "10.99")]
[DataRow("-5", null)]
[DataRow("abc", null)]
[DataRow("", null)]
public void AmountsAreReadAsPeopleTypeThem(string text, string? expected) =>
Assert.AreEqual(expected is null ? null : decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture), Forms.ParseEuro(text));
}