Files
Anubis/tests/Anubis.Tests/AccountsScreenTests.cs
T
Alby96andClaude Opus 5.5 1a0912e436
ci / test (postgres) (push) Successful in 3m9s
ci / test (sqlite) (push) Successful in 2m28s
ci / test (postgres) (pull_request) Successful in 4m1s
ci / test (sqlite) (pull_request) Failing after 2m31s
ci / image (pull_request) Skipped
ci / image (push) Successful in 1m34s
Fix the defects found by the Phase 3 review (refs #33 #26 #27 #28 #29 #30 #31 #32)
- Splits multiply only the shares held before the ex-date. Old splits in
  the table no longer inflate positions bought later; the simulator's book
  follows the same split once, together with the ledger.
- Dividends pay the simulator once on the ex-date holdings, and each
  payment is marked in the same write, so a failure never pays twice.
- Positions are marked to market before every equity photograph; until
  now equity, drawdown and the Conti screen stayed at the last fill.
- A sale with no price keeps its broker stops until it can really leave;
  a purchase with no price is dropped.
- A refused sale is retried with pauses of 1, 2, 4, 8 and 15 minutes
  instead of every tick, and one failing execution no longer stops the
  stop alignment of the whole account.
- On Alpaca a purchase clears the sell stops of every strategy on the
  symbol and holds them until it ends.
- OKX order lookups treat only 51603 as unknown; any other failure is an
  error, so a lost order is never sent twice.
- The reconcile choice and key removal forms now require the antiforgery
  token; the choice re-runs the comparison and is only offered after the
  15 minutes; stale differences are dropped.
- A replaced key that cannot withdraw releases the prudent mode.
- Re-entering the same euro capital for Alpaca changes nothing; a new
  amount converts only the euro difference at today's rate.

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

162 lines
8.6 KiB
C#

using System.Net;
using Anubis.Db;
using Anubis.Server;
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()
{
await using 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
{
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.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));
}