Files
Anubis/tests/Anubis.Tests/CoreTests.cs
T
Alby96andClaude Opus 5.5 1f0c4b322f
ci / test (postgres) (push) Successful in 6m6s
ci / test (sqlite) (push) Successful in 4m57s
ci / test (postgres) (pull_request) Successful in 5m59s
ci / test (sqlite) (pull_request) Successful in 4m49s
ci / image (push) Successful in 1m37s
ci / image (pull_request) Successful in 53s
Judge the scheduler test on the reading it saw
LoopWaitsOnTheInjectedClock failed once on the CI (run 586) in 38 ms,
although its wait lasts up to five seconds. WaitUntil read the
condition in its loop and then read it again for the assertion. The
scheduler's first round registers a wait on the clock and drops it at
once, because the job added before RunAsync has already signalled a
change, so the loop could see the clock waited on and the assertion
could see it no longer waited on.

The test run 3,000 times in parallel failed 20 times before the fix
and never in 18,000 runs after it. WaitUntil now judges the reading it
saw, and AStateSeenOnceIsEnoughForTheWait, which fails with the old
helper, keeps it that way. The scheduler itself is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:50:14 +01:00

316 lines
14 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Anubis.Core;
namespace Anubis.Tests;
[TestClass]
public sealed class CoreTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void IdsAreVersion7AndFollowTheInjectedClock()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
var first = Ids.NewId(clock);
clock.Advance(TimeSpan.FromMilliseconds(5));
var second = Ids.NewId(clock);
Assert.AreEqual(7, first.Version);
Assert.IsLessThan(0, string.CompareOrdinal(first.ToString(), second.ToString()), "gli identificativi seguono il tempo");
Assert.AreNotEqual(Ids.NewToken(), Ids.NewToken());
// In the same millisecond they still come out in order (two lots of one order, LIFO), with the clock's time.
var burst = Enumerable.Range(0, 5000).Select(_ => Ids.NewId(clock).ToString()).ToList();
CollectionAssert.AreEqual(burst.Order(StringComparer.Ordinal).ToList(), burst);
Assert.AreEqual(burst.Count, burst.Distinct().Count());
var time = Convert.ToInt64(burst[0].Replace("-", "", StringComparison.Ordinal)[..12], 16);
Assert.AreEqual(clock.UtcNow.ToUnixTimeMilliseconds(), time);
Assert.AreEqual(7, Guid.Parse(burst[^1]).Version);
Assert.AreEqual(0x8, Guid.Parse(burst[^1]).Variant & 0xC);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ManualClockReleasesWaitersOnlyWhenMoved()
{
var clock = new ManualClock(DateTimeOffset.UnixEpoch);
var waiting = clock.WaitUntilAsync(DateTimeOffset.UnixEpoch.AddMinutes(5), CancellationToken.None);
clock.Advance(TimeSpan.FromMinutes(4));
Assert.IsFalse(waiting.IsCompleted);
clock.Advance(TimeSpan.FromMinutes(1));
await waiting.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task BusDeliversToEachSubscriberAndDropsOldestWhenFull()
{
var bus = new EventBus();
using var all = bus.Subscribe<object>();
using var small = bus.Subscribe<string>(capacity: 2);
bus.Publish("a");
bus.Publish("b");
bus.Publish("c");
bus.Publish(42);
var received = new List<string>();
while (small.TryRead(out var message))
{
received.Add(message!);
}
CollectionAssert.AreEqual(new[] { "b", "c" }, received, "un lettore lento perde i più vecchi, non blocca chi pubblica");
var count = 0;
while (all.TryRead(out _))
{
count++;
}
Assert.AreEqual(4, count);
all.Dispose();
Assert.AreEqual(1, bus.SubscriberCount);
await Task.CompletedTask.ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void RedactorRemovesKeysSignaturesAndHeaders()
{
Redactor.Register("registered-secret-value-123");
var samples = new Dictionary<string, string>
{
["OK-ACCESS-SIGN: " + "abc123signature=="] = "abc123signature",
["APCA-API-SECRET-KEY: " + "Sk1234567890abcdef"] = "Sk1234567890abcdef",
["Authorization: Bearer " + "eyJhbGciOiJIUzI1NiJ9.payload"] = "eyJhbGciOiJIUzI1NiJ9",
["{\"api_key\": \"" + "AK12345678\"}"] = "AK12345678",
["password=" + "hunter2hunter2&x=1"] = "hunter2hunter2",
["postgres://anubis:" + "S3cretPw@db:5432/anubis"] = "S3cretPw",
["bot" + "123456789:" + "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq"] = "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq",
["value registered-secret-value-123 in text"] = "registered-secret-value-123",
};
foreach (var (input, secret) in samples)
{
var output = Redactor.Redact(input);
Assert.IsFalse(output.Contains(secret, StringComparison.Ordinal), $"Segreto rimasto in: {output}");
Assert.Contains(Redactor.Mask, output);
}
Assert.AreEqual("Ordine eseguito: 2 AAPL a 259,80 $", Redactor.Redact("Ordine eseguito: 2 AAPL a 259,80 $"));
}
}
/// <summary>The scheduler with a fake calendar (issue #10): fixed times, intervals, open and close, sleeps.</summary>
[TestClass]
public sealed class SchedulerTests
{
private static readonly TimeZoneInfo _rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
private static readonly TimeZoneInfo _newYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
/// <summary>New York, 09:30–16:00 on weekdays, 13:00 close on the day after Thanksgiving 2026, closed on 3 July.</summary>
private sealed class FakeCalendar : IMarketCalendar
{
public MarketSession? SessionOn(DateOnly day)
{
if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday || day == new DateOnly(2026, 7, 3))
{
return null;
}
var close = day == new DateOnly(2026, 11, 27) ? new TimeOnly(13, 0) : new TimeOnly(16, 0);
return new MarketSession(day, At(day, new TimeOnly(9, 30)), At(day, close));
}
private static DateTimeOffset At(DateOnly day, TimeOnly time)
{
var local = day.ToDateTime(time);
return new DateTimeOffset(local, _newYork.GetUtcOffset(local)).ToUniversalTime();
}
}
private static DateTimeOffset Rome(int y, int mo, int d, int h, int mi)
{
var local = new DateTime(y, mo, d, h, mi, 0);
return new DateTimeOffset(local, _rome.GetUtcOffset(local));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void MarketTimesFollowTheExchangeNotItalianTime()
{
var calendar = new FakeCalendar();
var afterOpen = Schedule.Market(MarketAnchor.Open, TimeSpan.FromMinutes(5), calendar);
// Normal week: 09:35 in New York is 15:35 in Rome.
Assert.AreEqual(Rome(2026, 10, 9, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 8, 21)));
// 16 March 2026: the USA already moved to summer time, Europe not yet: 09:35 NY is 14:35 in Rome.
Assert.AreEqual(Rome(2026, 3, 16, 14, 35), afterOpen.NextAfter(Rome(2026, 3, 16, 8, 0)));
// Friday after the open: the next run is Monday.
Assert.AreEqual(Rome(2026, 10, 12, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 16, 0)));
// Holiday skipped (Friday 3 July): Monday 6 July.
Assert.AreEqual(Rome(2026, 7, 6, 15, 35), afterOpen.NextAfter(Rome(2026, 7, 2, 16, 0)));
// Early close: 5 minutes before a 13:00 close is 12:55 in New York, 18:55 in Rome.
var beforeClose = Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(-5), calendar);
Assert.AreEqual(Rome(2026, 11, 27, 18, 55), beforeClose.NextAfter(Rome(2026, 11, 27, 9, 0)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DailyAndIntervalSchedules()
{
var backup = Schedule.Daily(new TimeOnly(3, 30), _rome);
Assert.AreEqual(Rome(2026, 10, 10, 3, 30), backup.NextAfter(Rome(2026, 10, 9, 8, 21)));
// The night summer time ends (25 October 2026) 03:30 exists once, in winter time.
Assert.AreEqual(Rome(2026, 10, 25, 3, 30), backup.NextAfter(Rome(2026, 10, 24, 12, 0)));
// 02:30 does not exist on 29 March 2026 in Rome: it moves to 03:00.
var skipped = Schedule.Daily(new TimeOnly(2, 30), _rome);
Assert.AreEqual(new DateTimeOffset(2026, 3, 29, 1, 0, 0, TimeSpan.Zero), skipped.NextAfter(Rome(2026, 3, 28, 12, 0)));
var crypto = Schedule.Daily(new TimeOnly(0, 5), TimeZoneInfo.Utc);
Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 0, 5, 0, TimeSpan.Zero), crypto.NextAfter(Rome(2026, 10, 9, 8, 21)));
var every5 = Schedule.Every(TimeSpan.FromMinutes(5));
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero)));
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 30, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task RunsDueJobsOnceAndSkipsRunsMissedDuringASleep()
{
var clock = new ManualClock(Rome(2026, 10, 9, 8, 21));
var bus = new EventBus();
using var runs = bus.Subscribe<JobRun>();
var scheduler = new Scheduler(clock, bus);
var count = 0;
scheduler.Add(new ScheduledJob("backup", "Salvataggio", Schedule.Daily(new TimeOnly(3, 30), _rome), _ =>
{
count++;
return Task.CompletedTask;
}));
scheduler.Add(new ScheduledJob("broken", "Rotto", Schedule.Daily(new TimeOnly(3, 30), _rome), _ => throw new InvalidOperationException("guasto")));
Assert.HasCount(2, scheduler.Upcoming());
clock.Set(Rome(2026, 10, 10, 3, 30));
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count);
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count, "un lavoro già eseguito non riparte");
// The computer slept two days: the 03:30 run is found late by hours and is skipped, not run blindly.
clock.Set(Rome(2026, 10, 11, 9, 0));
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count);
var outcomes = new List<JobRun>();
while (runs.TryRead(out var run))
{
outcomes.Add(run!);
}
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Completed));
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Skipped));
Assert.IsTrue(outcomes.Any(r => r.Name == "broken" && r.Outcome == JobOutcome.Failed && r.Error == "guasto"));
Assert.AreEqual(Rome(2026, 10, 12, 3, 30), scheduler.Upcoming().Single(u => u.Name == "backup").DueUtc);
}
/// <summary>A long job beside the queue (the news) never delays the others, never runs twice at once, and is waited for.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AJobBesideTheQueueNeverDelaysTheOthers()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
var bus = new EventBus();
using var runs = bus.Subscribe<JobRun>();
var scheduler = new Scheduler(clock, bus);
int slow = 0, quick = 0;
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
scheduler.Add(new ScheduledJob("a-notizie", "Lunga", Schedule.Every(TimeSpan.FromMinutes(1)), async ct =>
{
Interlocked.Increment(ref slow);
await release.Task.WaitAsync(ct).ConfigureAwait(false);
})
{ Beside = true });
scheduler.Add(new ScheduledJob("rischio", "Breve", Schedule.Every(TimeSpan.FromMinutes(1)), _ =>
{
quick++;
return Task.CompletedTask;
}));
for (var minute = 22; minute <= 24; minute++)
{
clock.Set(new DateTimeOffset(2026, 10, 9, 6, minute, 0, TimeSpan.Zero));
await scheduler.RunDueAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
}
await WaitUntil(() => Volatile.Read(ref slow) == 1).ConfigureAwait(false);
Assert.AreEqual((1, 3), (slow, quick));
release.SetResult();
await scheduler.BesideAsync().WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
clock.Set(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero));
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
await scheduler.BesideAsync().WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
Assert.AreEqual(2, slow);
var done = new List<JobRun>();
while (runs.TryRead(out var run))
{
done.Add(run!);
}
Assert.AreEqual(2, done.Count(r => r.Name == "a-notizie" && r.Outcome == JobOutcome.Completed));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task LoopWaitsOnTheInjectedClock()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
var scheduler = new Scheduler(clock, new EventBus());
var ran = new TaskCompletionSource();
scheduler.Add(new ScheduledJob("tick", "Prova", Schedule.Every(TimeSpan.FromMinutes(5)), _ =>
{
ran.TrySetResult();
return Task.CompletedTask;
}));
using var cts = new CancellationTokenSource();
var loop = scheduler.RunAsync(cts.Token);
await WaitUntil(() => clock.Waiting > 0).ConfigureAwait(false);
Assert.IsFalse(ran.Task.IsCompleted, "nessun lavoro prima dell'orario");
clock.Set(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero));
await ran.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
Assert.IsNotNull(scheduler.LastBeatUtc);
await cts.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => loop).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task AStateSeenOnceIsEnoughForTheWait()
{
// A state that holds for an instant (CI run 586): the wait judges the reading it saw, it does not ask again.
var readings = 0;
await WaitUntil(() => Interlocked.Increment(ref readings) == 2).ConfigureAwait(false);
Assert.AreEqual(2, readings);
}
internal static async Task WaitUntil(Func<bool> condition)
{
// One reading per round, and the reading seen is the one judged. Asking again for the assertion failed the test
// when the state held only for an instant: the scheduler's first round registers a wait on the clock and drops it
// at once, because the job added before RunAsync has already signalled a change.
var met = condition();
for (var i = 0; i < 500 && !met; i++)
{
await Task.Delay(10).ConfigureAwait(false);
met = condition();
}
Assert.IsTrue(met, "condizione non raggiunta in tempo");
}
}