using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using Encelado.Core.Baskets;
using Encelado.Core.Baskets.History;
using Encelado.Core.Baskets.Learning;
using Encelado.Core.Broker;
using Encelado.Core.Notifications;
using Encelado.Engine;
using Encelado.Engine.Baskets;
using Encelado.Engine.Configuration;
using Encelado.Etoro;
using Encelado.Server.Web;
namespace Encelado.Tests;
///
/// The engine's published picture and what feeds it (decision E1): pure readers, the HTTP
/// layer's own numbers, the health words, the background feed refresh (E5), the sample data
/// (E6) and the log window indexed by sequence.
///
public sealed class EngineViewTests
{
private static readonly DateTime Epoch = SampleData.Anchor(new DateTime(2026, 9, 30, 10, 0, 0, DateTimeKind.Utc));
private static BasketStrategyConfig Factory() => BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _);
// -----------------------------------------------------------------------
// Pure readers
// -----------------------------------------------------------------------
/// A panel refreshed every second must not queue forecasts nor flip the EWMA/HAR choice (5.0 did both).
[Fact]
public void ReadingTheVolatilityForecasterChangesNothing()
{
VolForecaster v = new(horizonBars: 8, ewmaSpan: 100);
Random rng = new(42);
DateTime t = new(2026, 9, 1, 0, 0, 0, DateTimeKind.Utc);
for (int i = 0; i < 700; i++)
{
v.Observe((rng.NextDouble() - 0.5) * 0.002, t.AddMinutes(15 * i));
if (i % 3 == 0)
{
v.Forecast();
}
}
VolStats before = v.Stats();
string model = v.ActiveModel;
for (int i = 0; i < 50; i++)
{
_ = v.Stats();
_ = v.Describe();
}
VolStats after = v.Stats();
Assert.Equal(before.Pending, after.Pending);
Assert.Equal(model, v.ActiveModel);
Assert.Equal(before, after);
Assert.Equal(700, after.Bars);
Assert.True(double.IsFinite(after.ForecastSigma));
Assert.True(after.Scored > 0);
Assert.NotNull(after.LastHarFitUtc);
}
[Fact]
public void EveryFeatureHasAnItalianLabel()
{
Assert.Equal(LearningFeatures.Names.Length, LearningFeatures.Labels.Length);
Assert.All(LearningFeatures.Labels, static l => Assert.False(string.IsNullOrWhiteSpace(l)));
Assert.Equal("z-score del cross", LearningFeatures.LabelOf("z"));
Assert.Equal("sconosciuta", LearningFeatures.LabelOf("sconosciuta"));
}
[Fact]
public void ABasketsCurrenciesAreItsFlags()
{
Assert.Equal(["EUR", "USD", "CHF"], SyntheticCross.Currencies("EURUSD", "USDCHF"));
Assert.Equal(["NZD", "USD", "EUR"], SyntheticCross.Currencies("NZDUSD", "EURNZD"));
Assert.Equal(["EUR", "AUD", "CAD"], SyntheticCross.Currencies("eurAUD", "AUDCAD"));
}
// -----------------------------------------------------------------------
// The HTTP layer's numbers
// -----------------------------------------------------------------------
[Fact]
public void TheLatencyWindowAveragesTheLastMinuteOnly()
{
LatencyWindow w = new(TimeSpan.FromMinutes(1));
Assert.True(double.IsNaN(w.Last));
Assert.True(double.IsNaN(w.Average(0)));
w.Add(100, 0);
w.Add(200, 30_000);
Assert.Equal(150, w.Average(30_000), 6);
Assert.Equal(200, w.Last);
Assert.Equal(200, w.Average(70_000), 6);
Assert.True(double.IsNaN(w.Average(200_000)));
}
private sealed class ScriptedHandler(Func> answer) : HttpMessageHandler
{
private int _calls;
protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
answer(request, Interlocked.Increment(ref _calls));
}
/// The latency of the Sistema page is the HTTP exchange alone: the pause a 429 imposes on the limiter is not in it.
[Fact]
public async Task TheHttpLayerMeasuresTheRoundTripAloneAndCountsThe429()
{
ScriptedHandler handler = new(static async (_, n) =>
{
if (n == 1)
{
HttpResponseMessage busy = new((HttpStatusCode)429);
busy.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(1));
return busy;
}
await Task.Delay(60);
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{}") };
});
using EtoroHttp http = new(new EtoroOptions(), handler);
EtoroResponse first = await http.SendAsync(HttpMethod.Get, "api/v1/me", null, EtoroQuota.Lookup, CancellationToken.None, retries: 0);
Assert.Equal(429, (int)first.Status);
EtoroHttpStats afterFirst = http.Stats();
QuotaUsage lookup = afterFirst.Quotas.Single(static q => q.Name == "lookup");
Assert.Equal(1, lookup.Count429);
Assert.NotNull(lookup.PausedUntilUtc);
Assert.Contains("429", afterFirst.LastError!.Message, StringComparison.Ordinal);
Assert.Equal(1, afterFirst.ConsecutiveFailures);
Stopwatch sw = Stopwatch.StartNew();
EtoroResponse second = await http.SendAsync(HttpMethod.Get, "api/v1/me", null, EtoroQuota.Lookup, CancellationToken.None, retries: 0);
sw.Stop();
EtoroHttpStats s = http.Stats();
Assert.True(second.IsSuccess);
Assert.True(sw.ElapsedMilliseconds >= 800, $"il limitatore ha trattenuto la chiamata per {sw.ElapsedMilliseconds} ms");
Assert.InRange(s.LastLatencyMs, 40, 700);
Assert.Equal(0, s.ConsecutiveFailures);
Assert.Equal(2, s.Requests);
Assert.Equal(7, s.Quotas.Count);
Assert.Null(s.Quotas.Single(static q => q.Name == "market-data").PausedUntilUtc);
}
// -----------------------------------------------------------------------
// Health words
// -----------------------------------------------------------------------
[Fact]
public void TheApiIconSaysOffOkDegradedOrError()
{
DateTime now = Epoch.AddSeconds(30);
EngineView v = SampleData.View(Epoch, now, Factory());
Assert.Equal("off", HealthRules.Api(null, now, 3));
Assert.Equal("ok", HealthRules.Api(v, now, 3));
Assert.Equal("degraded", HealthRules.Api(v with { Api = v.Api with { ConsecutiveErrors = 1, State = "errore" } }, now, 3));
Assert.Equal("degraded", HealthRules.Api(v with { Api = v.Api with { LastQuoteUtc = now.AddMinutes(-2) } }, now, 3));
Assert.Equal("error", HealthRules.Api(v with { Api = v.Api with { ConsecutiveErrors = 3, State = "errore" } }, now, 3));
Assert.Equal(21 / 110.0, HealthRules.QuotaPeak(v)!.Value, 1);
}
[Fact]
public void TheFeedsIconSaysOffErrorStaleOrOk()
{
DateTime now = Epoch;
FeedSourceState Calendar(DateTime? ok, int failures) => new("cal", "calendar", string.Empty, "h", now, ok, failures, null, true, string.Empty);
FeedSourceState Rss(DateTime? ok, int failures) => new("rss", "rss", string.Empty, "h", now, ok, failures, null, true, string.Empty);
Assert.Equal("off", HealthRules.Feeds(ContextView.Empty, now));
Assert.Equal("error", HealthRules.Feeds(new ContextView { Feeds = [Calendar(now, 2), Rss(now, 1)] }, now));
Assert.Equal("stale", HealthRules.Feeds(new ContextView { Feeds = [Calendar(now.AddHours(-5), 0), Rss(now, 0)] }, now));
Assert.Equal("ok", HealthRules.Feeds(new ContextView { Feeds = [Calendar(now.AddMinutes(-20), 0), Rss(now.AddMinutes(-5), 1)] }, now));
}
[Fact]
public void TheTelegramIconSaysOffErrorQueueOrOk()
{
TelegramStatus ok = new(true, true, true, true, true, true, true, 21, "1", 0, 5, 0, Epoch, string.Empty);
Assert.Equal("off", TelegramStatus.Off.Health);
Assert.Equal("ok", ok.Health);
Assert.Equal("queue", (ok with { Queued = 2 }).Health);
Assert.Equal("error", (ok with { LastError = "403 Forbidden" }).Health);
Assert.Equal("off", (ok with { Usable = false, LastError = "x" }).Health);
}
// -----------------------------------------------------------------------
// The log window
// -----------------------------------------------------------------------
[Fact]
public void TheLogWindowIsIndexedBySequenceAndKeepsEveryMessageOnOneLine()
{
LogBuffer log = new(100);
for (int i = 1; i <= 130; i++)
{
log.Add(Epoch.AddSeconds(i), i % 10 == 0 ? "error" : "info", "BasketEngine", $"riga {i}");
}
Assert.Equal(130, log.LastSeq);
Assert.Equal(100, log.Count);
(long last, List delta) = log.After(125, 100);
Assert.Equal(130, last);
Assert.Equal([126, 127, 128, 129, 130], delta.Select(static r => r.Seq));
// Older than the window: what is left; more than asked: the newest.
Assert.Equal(31, log.After(0, 1000).Rows[0].Seq);
Assert.Equal([129L, 130L], log.After(0, 2).Rows.Select(static r => r.Seq));
Assert.Empty(log.After(130, 10).Rows);
LogRow multi = log.Add(Epoch, "error", "BasketEngine", "prima riga\r\nseconda riga\nterza");
Assert.Equal("prima riga ⏎ seconda riga ⏎ terza", multi.Message);
Assert.Equal(131, multi.Seq);
(_, List errors) = log.Read("error", null, 5);
Assert.All(errors, static r => Assert.Equal("error", r.Level));
Assert.Equal(131, errors[^1].Seq);
Assert.Equal([130L, 131L], log.Read("tutti", null, 10, afterSeq: 129).Rows.Select(static r => r.Seq));
Assert.Equal("riga 120", Assert.Single(log.Read(null, "riga 120", 10).Rows).Message);
log.Resize(100);
log.Resize(150);
Assert.Equal(131, log.LastSeq);
Assert.Equal(100, log.Count);
Assert.Equal(131, log.After(130, 5).Rows.Single().Seq);
}
[Fact]
public void AnEventRowKeepsItsTimeAndSource()
{
LogBuffer log = new(100);
log.Add(new EventRow("10:00:00", "warn", "a\nb") { TimeUtc = Epoch, Source = "Feeds" });
LogRow row = log.Read(null, null, 1).Rows.Single();
Assert.Equal(Epoch, row.TimeUtc);
Assert.Equal("Feeds", row.Source);
Assert.Equal("a ⏎ b", row.Message);
Assert.Equal("una riga", Encelado.Engine.Logging.Log.SingleLine("una riga"));
}
// -----------------------------------------------------------------------
// The background refresh of the feeds (decision E5)
// -----------------------------------------------------------------------
private sealed class SlowProvider : IContextProvider
{
public readonly ManualResetEventSlim Gate = new(false);
public int Refreshes;
public int Sentiments;
public ContextView View => ContextView.Empty;
public Task RefreshAsync(DateTime nowUtc, CancellationToken ct)
{
Interlocked.Increment(ref Refreshes);
// Blocks before any await, like thirteen sources with a dead network would.
Gate.Wait(ct);
return Task.CompletedTask;
}
public void RefreshSentiment(DateTime nowUtc) => Interlocked.Increment(ref Sentiments);
public BasketContextFeatures For(string longCurrency, string shortCurrency, string commonCurrency, DateTime nowUtc) => BasketContextFeatures.Unknown;
public bool JustOpened(DateTime nowUtc, int openDelayMinutes) => false;
public ContextRow Row(DateTime nowUtc) => ContextView.Empty.ToRow(nowUtc, string.Empty, string.Empty, string.Empty);
}
///
/// The decision loop only calls : a download that hangs
/// costs the loop nothing — twenty ticks of a loop take milliseconds while the feeds block —,
/// a second one is never started while the first runs, and the sentiment of the minute
/// is still recomputed meanwhile.
///
[Fact]
public async Task TheFeedRefreshNeverHoldsUpTheDecisionLoop()
{
SlowProvider provider = new();
ContextRefresher refresher = new(provider, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(1));
DateTime t0 = Epoch;
Stopwatch loop = Stopwatch.StartNew();
refresher.Tick(t0, CancellationToken.None, force: true);
for (int i = 1; i <= 20; i++)
{
refresher.Tick(t0.AddMinutes(i), CancellationToken.None);
}
loop.Stop();
Assert.True(loop.ElapsedMilliseconds < 500, $"venti tick del ciclo in {loop.ElapsedMilliseconds} ms");
using CancellationTokenSource wait = new(TimeSpan.FromSeconds(5));
while (Volatile.Read(ref provider.Refreshes) == 0)
{
await Task.Delay(10, wait.Token);
}
Assert.True(refresher.IsRunning);
Assert.Equal(1, refresher.Started);
Assert.Equal(1, Volatile.Read(ref provider.Refreshes));
Assert.Equal(20, Volatile.Read(ref provider.Sentiments));
provider.Gate.Set();
await refresher.Completion.WaitAsync(TimeSpan.FromSeconds(5));
Assert.False(refresher.IsRunning);
refresher.Tick(t0.AddMinutes(30), CancellationToken.None);
Assert.Equal(2, refresher.Started);
await refresher.Completion.WaitAsync(TimeSpan.FromSeconds(5));
}
/// The provider publishes its picture at once from the archive on disk: the Mercato page has the calendar before any download.
[Fact]
public void TheContextProviderPublishesTheArchiveOnDiskAtOnce()
{
string dir = Path.Combine(Path.GetTempPath(), "encelado-context-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Path.Combine(dir, "calendar"));
Directory.CreateDirectory(Path.Combine(dir, "news"));
DateTime now = DateTime.UtcNow;
string recent = now.AddHours(3).ToString("O", System.Globalization.CultureInfo.InvariantCulture);
string old = now.AddDays(-30).ToString("O", System.Globalization.CultureInfo.InvariantCulture);
File.WriteAllLines(Path.Combine(dir, "calendar", "events.jsonl"),
[
$"{{\"title\":\"Core PCE\",\"country\":\"USD\",\"date\":\"{recent}\",\"impact\":\"High\",\"forecast\":\"0.2%\",\"previous\":\"0.3%\",\"actual\":\"\"}}",
$"{{\"title\":\"Vecchio\",\"country\":\"EUR\",\"date\":\"{old}\",\"impact\":\"Low\",\"forecast\":\"\",\"previous\":\"\",\"actual\":\"\"}}",
]);
File.WriteAllLines(Path.Combine(dir, "news", $"news_{now:yyyyMM}.jsonl"),
[
$"{{\"hash\":\"x\",\"published\":\"{now.AddHours(-1):O}\",\"source\":\"FXStreet\",\"title\":\"Dollar rallies as Fed signals hikes\",\"summary\":\"USD\",\"link\":\"https://example.org/a\"}}",
]);
try
{
using FeedContextProvider provider = new(dir, "Encelado-test");
ContextView view = provider.View;
Assert.Equal("Core PCE", Assert.Single(view.Events).Title);
Assert.Single(view.News);
Assert.Equal(8, view.Sentiment.Count);
Assert.Equal(13, view.Feeds.Count);
Assert.Equal(1, view.Feeds.Count(static f => f.Kind == "calendar"));
Assert.All(view.Feeds, static f => Assert.Equal(0, f.Failures));
int published = 0;
provider.Published += _ => published++;
provider.RefreshSentiment(now.AddMinutes(1));
Assert.Equal(1, published);
Assert.NotSame(view, provider.View);
Assert.Same(view.Events, provider.View.Events);
}
finally
{
try
{
Directory.Delete(dir, recursive: true);
}
catch (IOException)
{
// Cleaned later.
}
}
}
// -----------------------------------------------------------------------
// The sample (decision E6) and the 5.0 picture adapted from a view
// -----------------------------------------------------------------------
[Fact]
public void TheSampleIsInternallyConsistent()
{
DateTime now = Epoch.AddSeconds(90);
BasketStrategyConfig strategy = Factory();
(List history, _) = SampleData.History(Epoch, now);
EngineView v = SampleData.View(Epoch, now, strategy, history);
Assert.Equal(5, v.Baskets.Count);
Assert.Equal(1, v.OpenBaskets);
Assert.Equal(1, v.PendingBaskets);
Assert.Equal(v.PendingOrders, v.PendingOrderList.Count);
Assert.Equal(1, v.PendingOrders);
Assert.Equal(1, v.OrphanLegs);
Assert.Equal(2, v.ForeignPositions);
Assert.Equal(v.Positions.Rows.Count(static r => r.Origin == PositionOrigin.OrphanBot), v.OrphanLegs);
Assert.Equal(v.Positions.Rows.Count(static r => r.Origin == PositionOrigin.Foreign), v.ForeignPositions);
// The account is priced on the same quotes as the positions page.
Assert.Equal(v.Funds.Balance + v.Positions.Rows.Sum(static r => r.Position.UnrealizedPnl), v.Funds.Equity, 6);
Assert.Equal(v.Positions.Rows.Sum(static r => r.Position.Margin), v.Funds.UsedMargin, 6);
// "P&L oggi" is the Storico's "oggi".
PeriodStats today = HistoryBuilder.Period("oggi", now.Date, now.Date.AddDays(1), history);
Assert.Equal(today.PnlNetto, v.Funds.TodayPnl, 6);
// The open basket's legs are the basket positions of the account.
BasketView open = v.Baskets.Single(static b => b.IsOpen);
long[] legIds = [.. open.Position!.A.PositionIds, .. open.Position.B.PositionIds];
Assert.Equal(legIds.Order(), v.Positions.Rows.Where(static r => r.Origin == PositionOrigin.Basket).Select(static r => r.Position.PositionId).Order());
Assert.NotNull(open.Position.A.Venue);
double pnl = open.Position.A.PnlUsd + open.Position.B.PnlUsd - open.Position.A.EntryFeesUsd - open.Position.B.EntryFeesUsd - open.Position.AccruedFeesUsd;
Assert.Equal(pnl, open.Evaluation.PnlOpenUsd, 6);
// The pending entry is the order of the register, and the same-cross basket waits for it.
Assert.Equal(v.PendingOrderList.Single().Basket, v.Baskets.Single(static b => b.Pending is not null).Name);
Assert.Contains("same_cross", v.Baskets.Single(static b => b.Name == "USDCAD/EURUSD").LastDecision!.ReasonCodes);
// Numbers drift, the structure does not.
EngineView later = SampleData.View(Epoch, now.AddSeconds(1), strategy, history);
Assert.NotEqual(v.Funds.Equity, later.Funds.Equity);
Assert.Equal(v.Baskets.Select(static b => b.State), later.Baskets.Select(static b => b.State));
// A basket switched off in the settings is disabled in the sample too.
strategy.Baskets[1].Enabled = false;
EngineView off = SampleData.View(Epoch, now, strategy, history);
Assert.Equal("Disabled", TickWriter.StateOf(off.Baskets[1]));
Assert.Equal("Open", TickWriter.StateOf(off.Baskets[0]));
}
[Fact]
public void TheSampleCalendarBlacksOutTheBasketsOfTheNextRelease()
{
DateTime now = Epoch.AddSeconds(90);
ContextView ctx = SampleData.Context(Epoch, now);
BasketContextFeatures f = ContextFeatures.For(ctx, "EUR", "USD", "NZD", now);
Assert.InRange(f.MinutesToNextHigh, 35, 38);
Assert.Contains("Core PCE", f.NextEventLabel, StringComparison.Ordinal);
Assert.True(f.NewsCount > 0);
Assert.True(double.IsFinite(f.NetSentimentDiff1h));
EngineView v = SampleData.View(Epoch, now, Factory());
BasketView blocked = v.Baskets.Single(static b => b.Name == "NZDUSD/EURNZD");
Assert.Contains("blackout_before", blocked.LastDecision!.ReasonCodes);
}
[Fact]
public void TheConsoleAndTelegramPictureComesFromTheView()
{
DateTime now = Epoch.AddSeconds(90);
EngineView v = SampleData.View(Epoch, now, Factory());
BotSnapshot s = SnapshotAdapter.FromView(v, SampleData.Context(Epoch, now), BotState.Running, null, v.StartedUtc, [], "Telegram: ok", "EUR", now);
Assert.Equal(5, s.Baskets.Count);
Assert.Equal(1, s.OpenBaskets);
Assert.Equal(v.Funds.Equity, s.Equity, 6);
Assert.Equal("MODERATE", s.Preset);
Assert.Equal("DEMO", s.Mode);
Assert.Contains("quote/min", s.Counters, StringComparison.Ordinal);
Assert.NotNull(s.Context);
Assert.NotEmpty(s.Context!.NextEvents);
string hourly = TelegramReports.Hourly(s, "Telegram: ok");
Assert.Contains("Basket aperti 1/3", hourly, StringComparison.Ordinal);
Assert.DoesNotContain("NaN", hourly, StringComparison.Ordinal);
}
// -----------------------------------------------------------------------
// The supervisor hands out the published picture
// -----------------------------------------------------------------------
private sealed class ViewEngine(EngineView view) : IEngine
{
public EngineView? View => view;
public Task RunAsync(CancellationToken ct) => Task.Delay(Timeout.Infinite, ct);
public Task ExecuteAsync(EngineCommand command, CancellationToken ct) => Task.FromResult(new CommandResult(true, "ok"));
public BotSnapshot Snapshot(BotState state, string? error, DateTime? startedUtc, EventRow[] events) => SampleSnapshot.Minimal(state);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
[Fact]
public async Task TheSupervisorHandsOutThePublishedPictureAndKeepsTheLastOne()
{
string dir = Path.Combine(Path.GetTempPath(), "encelado-status-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
string configPath = Path.Combine(dir, "encelado.json");
File.WriteAllText(configPath, ConfigDefaults.Json);
BotConfig config = ConfigLoader.Load(configPath, out _);
EngineView view = SampleData.View(Epoch, Epoch.AddSeconds(5), Factory());
SectionVersions versions = new();
await using BotSupervisor supervisor = new(config, (_, _) => new ViewEngine(view), null, versions);
Assert.Equal(BotState.Stopped, supervisor.Status().State);
Assert.Null(supervisor.Status().Live);
long positions = versions[Section.Positions];
Assert.True((await supervisor.StartAsync()).Ok);
EngineStatus running = supervisor.Status();
Assert.Equal(BotState.Running, running.State);
Assert.Same(view, running.Live);
Assert.NotNull(running.StartedUtc);
Assert.True(versions[Section.Positions] > positions);
await supervisor.StopAsync();
EngineStatus stopped = supervisor.Status();
Assert.Equal(BotState.Stopped, stopped.State);
Assert.Null(stopped.Live);
Assert.Null(stopped.StartedUtc);
Assert.Same(view, stopped.LastView);
}
// -----------------------------------------------------------------------
// Sections on demand
// -----------------------------------------------------------------------
[Fact]
public void ASectionIsBuiltOncePerKeyAndItsTagFollowsTheBytes()
{
SectionCache cache = new();
int builds = 0;
byte[] Build()
{
builds++;
return Encoding.UTF8.GetBytes("{\"a\":1}");
}
(byte[] json, string etag) one = cache.Get("k|1", TimeSpan.FromMinutes(1), Build);
(byte[] json, string etag) two = cache.Get("k|1", TimeSpan.FromMinutes(1), Build);
Assert.Equal(1, builds);
Assert.Same(one.json, two.json);
(_, string three) = cache.Get("k|2", TimeSpan.FromMinutes(1), Build);
Assert.Equal(2, builds);
Assert.Equal(one.etag, three);
cache.Get("k|1", TimeSpan.Zero, Build);
Assert.Equal(3, builds);
Assert.NotEqual(one.etag, SectionCache.ETagOf("{\"a\":2}"u8));
Microsoft.AspNetCore.Http.DefaultHttpContext http = new();
http.Request.Headers.IfNoneMatch = $"\"x\", W/{one.etag}";
Assert.True(SectionCache.Matches(http.Request, one.etag));
http.Request.Headers.IfNoneMatch = "*";
Assert.True(SectionCache.Matches(http.Request, one.etag));
http.Request.Headers.IfNoneMatch = "\"x\"";
Assert.False(SectionCache.Matches(http.Request, one.etag));
}
// -----------------------------------------------------------------------
// Embedded files
// -----------------------------------------------------------------------
[Fact]
public void EmbeddedFilesAreServedAtTheirPathWithTheirType()
{
Assert.Equal("/js/pages/dashboard.js", StaticFiles.PublicPath("wwwroot/js\\pages\\dashboard.js"));
Assert.Equal("/css/app.css", StaticFiles.PublicPath("wwwroot/css/app.css"));
Assert.Null(StaticFiles.PublicPath("Encelado.Server.Something.resources"));
Assert.Null(StaticFiles.PublicPath("wwwroot/"));
Assert.Equal("text/javascript; charset=utf-8", StaticFiles.ContentTypeOf("/js/app.js"));
Assert.Equal("text/css; charset=utf-8", StaticFiles.ContentTypeOf("/css/app.css"));
Assert.Equal("image/svg+xml", StaticFiles.ContentTypeOf("/icon.svg"));
Assert.Equal("application/manifest+json", StaticFiles.ContentTypeOf("/manifest.webmanifest"));
Assert.Equal("image/png", StaticFiles.ContentTypeOf("/img/x.png"));
// The names the contract fixes (docs/API.md): the shell, the login, the icon and the manifest,
// and the files of the nested folders (a page module, a page stylesheet) at their public paths.
foreach (string path in new[] { "/index.html", "/login.html", "/icon.svg", "/manifest.webmanifest", "/css/tokens.css", "/js/app.js", "/js/pages/dashboard.js", "/css/pages/dashboard.css" })
{
Assert.True(StaticFiles.All.ContainsKey(path), path);
}
Assert.Same(StaticFiles.All["/index.html"], StaticFiles.Find("/"));
Assert.Same(StaticFiles.All["/login.html"], StaticFiles.Find("/login"));
Assert.Null(StaticFiles.Find("/../secrets.enc"));
Assert.StartsWith("\"", StaticFiles.All["/index.html"].ETag, StringComparison.Ordinal);
Assert.All(StaticFiles.All.Keys, static k => Assert.DoesNotContain('\\', k));
Assert.Equal(Encoding.UTF8.GetString(StaticFiles.All["/login.html"].Bytes), Encoding.UTF8.GetString(WebHost.Asset("wwwroot/login.html")!));
}
}