Files
Chronos/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs
T
Alby96 13278710a2 fix(admin): follow jobs on the Library pages, cap the delete list, honest restore tooltip
Review fixes for owner review 2, phase 3 (R6 Library on the web panel):

- Trash: the worker can end an emptying before the browser has read the
  POST's 202, so its jobState arrived while the page did not know the job
  yet; Empty then stayed disabled ("being emptied") and no result showed.
  The page now keeps the last state of the jobs that ended and looks its
  job up there before following it. Any ended job also reloads the list
  (an emptying from another tab or the desktop sends no sequenceChanged),
  and a Restore answered 404 shows the trash as it is now.
- Sequence: thumbnail, proxy, verify and analysis jobs send no
  sequenceChanged, so tiles and the cover stayed placeholders and the
  status chips stale. An ended job now schedules one refresh (not pushed
  back by the next): the sequence is read again and failed images are
  asked for again under a retry address (shared retryImages).
- Library list: Esc, Ctrl+A or unticking every card left the "Select all"
  snapshot in place, hiding Select all and stopping the live refresh from
  pruning the selection. It is dropped once no selected sequence lies
  beyond the loaded rows; Clear filters clears the selection too.
- The sequences' delete dialog lists at most 500 names (blocked ones
  first, with their reasons), like the photos' dialog (shared LISTED).
- Admin.Trash.RestoreSequence.Tip promised a SHA-256 check that a sequence
  restore never makes (it moves the folder back); it now says so and names
  Verify (en, it; no other culture had the key).
- The upload test's name and comments say what it checks: upload.js is
  only imported dynamically, not loaded on click.

Tests pin each change in SystemEndpointTests; the pages were also driven
in a browser against a fake API, where the pre-fix modules fail and the
fixed ones pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 78f66082fd85543d619375574c82cc63a233b7a8)
2026-10-27 12:46:45 +01:00

447 lines
26 KiB
C#

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Protocol;
using Chronos.Server.Hosting;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
[Category("server")]
public sealed partial class SystemEndpointTests(TestContext context)
{
[Test]
public async Task HealthReportsOk()
{
await using var server = await TestServer.StartAsync(context);
var health = await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus);
Assert.Equal("ok", Assert.NotNull(health).Status);
Assert.Equal("ok", health.Checks["archive"]);
}
[Test]
public async Task ServerInfoCarriesFingerprintAndApiHeader()
{
await using var server = await TestServer.StartAsync(context);
using var response = await server.Client.GetAsync("/api/v1/server/info");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("1", response.Headers.GetValues(ApiVersion.Header).Single());
var info = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo);
Assert.Equal(1, Assert.NotNull(info).ApiVersion);
Assert.Equal(95, Assert.NotNull(info.TlsFingerprint).Length); // 32 bytes as XX: pairs
}
[Test]
public async Task HttpsServesTheAdvertisedCertificate()
{
await using var server = await TestServer.StartAsync(context);
var info = await server.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo);
string? seen = null;
using var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, cert, _, _) =>
{
seen = cert is null ? null : string.Join(':', cert.GetCertHash(System.Security.Cryptography.HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)));
return true;
},
};
using var https = new HttpClient(handler) { BaseAddress = Assert.NotNull(server.HttpsBase) };
using var response = await https.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(Assert.NotNull(info).TlsFingerprint, seen);
}
[Test]
public async Task CertificateIsReusedAcrossRestarts()
{
var root = context.CreateTempDirectory("restart");
string? first;
await using (var a = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data")))
first = (await a.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint;
await using var b = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data"));
var second = (await b.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint;
Assert.Equal(first, second);
}
[Test]
public async Task UnknownApiRouteReturnsJsonError()
{
await using var server = await TestServer.StartAsync(context);
using var response = await server.Client.GetAsync("/api/v1/does-not-exist");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError);
Assert.Equal("not_found", Assert.NotNull(error).Code);
}
[Test]
public async Task AdminPanelIsServedWithEtags()
{
await using var server = await TestServer.StartAsync(context);
using var redirect = await new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = server.HttpBase }.GetAsync("/admin");
Assert.Equal(HttpStatusCode.Redirect, redirect.StatusCode);
using var page = await server.Client.GetAsync("/admin/");
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
Assert.Contains("app.js", await page.Content.ReadAsStringAsync());
var etag = page.Headers.ETag;
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin/");
request.Headers.IfNoneMatch.Add(Assert.NotNull(etag));
using var cached = await server.Client.SendAsync(request);
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
}
[Test]
public async Task AdminPanelFilesAreRevalidatedSoAnUpgradeNeverMixesOldAndNewModules()
{
// A browser that kept app.js from before an upgrade must not run it next to a new ui.js: every file is kept but
// asked for again before each use, and its ETag follows its content, so only what the upgrade changed is sent.
await using var server = await TestServer.StartAsync(context);
foreach (var path in new[] { "/admin/", "/admin/app.js", "/admin/ui.js", "/admin/admin.css", "/admin/icons.js", "/admin/pages/library.js", "/admin/upload.js" })
{
using var response = await server.Client.GetAsync(path);
Assert.Equal(HttpStatusCode.OK, response.StatusCode, path);
var cache = Assert.NotNull(response.Headers.CacheControl);
Assert.True(cache.NoCache && cache.MaxAge is null && !cache.Public, $"{path}: {cache}");
var etag = Assert.NotNull(response.Headers.ETag);
Assert.False(etag.IsWeak, path);
var bytes = await response.Content.ReadAsByteArrayAsync();
Assert.Equal($"\"{Convert.ToHexString(SHA256.HashData(bytes).AsSpan(0, 12))}\"", etag.Tag, path);
foreach (var sent in new[] { etag, new EntityTagHeaderValue(etag.Tag, isWeak: true), EntityTagHeaderValue.Any })
{
using var again = new HttpRequestMessage(HttpMethod.Get, path);
again.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"0123\""));
again.Headers.IfNoneMatch.Add(sent);
using var notModified = await server.Client.SendAsync(again);
Assert.Equal(HttpStatusCode.NotModified, notModified.StatusCode, $"{path} with {sent}");
Assert.Equal(etag, notModified.Headers.ETag, path);
Assert.True(Assert.NotNull(notModified.Headers.CacheControl).NoCache, path);
}
// A file the browser holds from another build has another ETag: the new content comes back.
using var stale = new HttpRequestMessage(HttpMethod.Get, path);
stale.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"0123456789ABCDEF01234567\""));
using var fresh = await server.Client.SendAsync(stale);
Assert.Equal(HttpStatusCode.OK, fresh.StatusCode, path);
var resent = await fresh.Content.ReadAsByteArrayAsync();
Assert.BytesEqual(bytes, resent, path);
}
}
[Test]
public async Task PlainHttpFromAnotherMachineGoesToThePublicHttpsPort()
{
// The container listens on 8443, published on the host as 18443 (BRIEF §19.6: the template's ports are editable).
await using var server = await TestServer.StartAsync(context, o => o.PublicHttpsPort = 18443);
var kestrel = server.Services.GetRequiredService<IServer>();
var request = AdminRequest(IPAddress.Parse("10.0.0.7"));
Assert.Equal("https://10.0.0.5:18443/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
server.Options.PublicHttpsPort = null;
Assert.Equal($"https://10.0.0.5:{Assert.NotNull(server.HttpsBase).Port}/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
Assert.Null(AdminPanel.HttpsLocation(AdminRequest(IPAddress.Loopback), server.Options, kestrel));
}
private static DefaultHttpContext AdminRequest(IPAddress from)
{
var request = new DefaultHttpContext();
request.Connection.RemoteIpAddress = from;
request.Request.Scheme = "http";
request.Request.Host = new HostString("10.0.0.5", 18080);
request.Request.Path = "/admin/";
request.Request.QueryString = new QueryString("?page=jobs");
return request;
}
[Test]
public async Task AdminPanelRunsUnderAStrictPolicyAndIsNeverFramed()
{
await using var server = await TestServer.StartAsync(context);
foreach (var path in new[] { "/admin/", "/admin/app.js", "/admin/admin.css" })
{
using var response = await server.Client.GetAsync(path);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var policy = string.Join(' ', response.Headers.GetValues("Content-Security-Policy"));
foreach (var directive in new[] { "default-src 'self'", "script-src 'self'", "style-src 'self'", "frame-ancestors 'none'" })
Assert.Contains(directive, policy);
Assert.True(!policy.Contains("unsafe-inline", StringComparison.Ordinal), policy);
Assert.Equal("DENY", response.Headers.GetValues("X-Frame-Options").Single());
}
}
[Test]
public async Task AdminPanelModulesAllResolve()
{
await using var server = await TestServer.StartAsync(context);
var index = await server.Client.GetStringAsync("/admin/");
// The page container is not a live region: only toasts and form errors announce themselves.
Assert.True(!index.Contains("aria-live", StringComparison.Ordinal), index);
var seen = await ModulesAsync(server);
Assert.True(seen.Count >= 20, string.Join(", ", seen.Keys));
// The Library's views (owner review 2, R6) are modules of their own under pages/library; the web upload (R3) is the
// dialog, its hash worker and the in-house SHA-256 the worker imports.
foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js", "upload.js", "hash-worker.js", "sha256.js" })
Assert.True(seen.ContainsKey(module), module);
}
[Test]
public async Task AdminPanelListsTheLibraryAndImportsTheWebUploadOnlyDynamically()
{
// Owner review 2, R6: the Library comes right after the Dashboard. The web upload (R3) is a module of its own that
// only the Library list and a sequence import, and only dynamically (never statically): the other pages never load
// it, and the Library still works, without Upload and Add photos, when the module does not load.
await using var server = await TestServer.StartAsync(context);
var app = await server.Client.GetStringAsync("/admin/app.js");
var top = MenuPages(app)[0];
Assert.SequenceEqual(["dashboard", "library"], top.Take(2));
var icons = await server.Client.GetStringAsync("/admin/icons.js");
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
foreach (var page in MenuPages(app).SelectMany(group => group))
{
Assert.Contains($" {page}: `<svg", icons);
var name = $"Admin.Nav.{char.ToUpperInvariant(page[0])}{page[1..]}";
Assert.True(strings.ContainsKey(name) && strings.ContainsKey(name + ".Tip"), name);
}
var modules = await ModulesAsync(server);
Assert.Contains(@"import(""../upload.js"")", modules["pages/library.js"]);
foreach (var (module, source) in modules)
{
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in StaticImport().Matches(source))
Assert.True(Resolve(folder, import.Groups[1].Value) != "upload.js", $"{module} imports upload.js statically");
}
// The module the dynamic import names is there (no 404 in the browser) and exports what the Library calls.
Assert.Equal("upload.js", Resolve("pages/", "../upload.js"));
Assert.True(Regex.IsMatch(modules["upload.js"], @"export (?:async )?function openUpload\(\{ api, sequence, onDone \}"), "upload.js exports openUpload({ api, sequence, onDone })");
Assert.Contains("openUpload({ api, onDone: ", modules["pages/library.js"]);
Assert.Contains("openUpload({ api, sequence: seq, onDone: ", modules["pages/library/sequence.js"]);
}
[Test]
public async Task TheTrashPageSeesAnEmptyingThatEndedBeforeItsPostAnswered()
{
// The worker claims an emptying as soon as it is queued and can end it before the browser has read the 202: the page
// keeps the last state of the jobs that ended and looks its own job up there before it starts following it.
await using var server = await TestServer.StartAsync(context);
var trash = await server.Client.GetStringAsync("/admin/pages/library/trash.js");
Assert.Contains("ended.set(e.jobId, e)", trash);
var lookedUp = trash.IndexOf("ended.get(job.id)", StringComparison.Ordinal);
var followed = trash.IndexOf("emptyJob = job.id", StringComparison.Ordinal);
Assert.True(lookedUp > 0 && followed > lookedUp, "the queued job is looked up among the ended ones before it is followed");
// An emptying started elsewhere sends no sequenceChanged: any job that ends shows the trash again, and a restore
// of an entry that is gone (404) does too.
Assert.True(Regex.IsMatch(trash, @"e\.type === ""jobState"" && JOB_ENDED\.has\(e\.state\)"), "every ended job is seen");
Assert.True(Regex.IsMatch(trash, @"if \(err\.status === 404\) await load\(\);"), "a restore of a gone entry reloads the trash");
}
[Test]
public async Task ASequencePageRefreshesAfterJobsAndAsksAgainForMissingThumbnails()
{
// Thumbnail, proxy, verify and analysis jobs send no sequenceChanged: when any job ends, the sequence page reads the
// sequence again (facts, status chips) and asks again, past the browser's first answer, for the images that failed.
await using var server = await TestServer.StartAsync(context);
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
var shared = await server.Client.GetStringAsync("/admin/pages/library/shared.js");
Assert.True(Regex.IsMatch(sequence, @"e\.type === ""jobState""\) \{\s+(//[^\n]*\s+)*if \(JOB_ENDED\.has\(e\.state\) && jobTimer === null\) jobTimer = setTimeout\(afterJob"),
"an ended job schedules one refresh, not pushed back by the next");
Assert.True(Regex.IsMatch(sequence, @"async function afterJob\(\) \{[^}]*await reload\(false\);[^}]*retryImages\(root\);", RegexOptions.Singleline),
"the refresh reads the sequence again, then retries the cover and the photos");
Assert.Contains(@"export const JOB_ENDED = new Set([""done"", ""failed"", ""cancelled""]);", shared);
Assert.True(Regex.IsMatch(shared, @"export function retryImages\(root\) \{\s+root\.querySelectorAll\(""img\.failed""\)[^}]*searchParams\.set\(""retry"",", RegexOptions.Singleline),
"a retried image gets an address the browser has not tried");
}
[Test]
public async Task TheTrashsRestoreTooltipsSayWhatIsChecked()
{
// A photo entry is hashed against its record before it goes back; a sequence entry is moved back as a folder and
// nothing is hashed (SequenceTrash.RestoreAsync), so its tooltip must not promise a check.
await using var server = await TestServer.StartAsync(context);
foreach (var (culture, verify) in new[] { ("en", "Verify"), ("it", "Verifica") })
{
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync($"/api/v1/i18n/{culture}", ProtocolJson.Default.DictionaryStringString));
Assert.Contains("SHA-256", strings["Admin.Trash.RestorePhotos.Tip"]);
var sequence = strings["Admin.Trash.RestoreSequence.Tip"];
Assert.False(sequence.Contains("SHA-256", StringComparison.Ordinal), $"{culture}: {sequence}");
// The check it does not make is named, with the job that makes it.
Assert.Contains(verify, sequence);
}
}
[Test]
public async Task TheLibraryListDropsSelectAllWhenNoUnloadedSequenceStaysSelectedAndCapsItsDeleteList()
{
await using var server = await TestServer.StartAsync(context);
var library = await server.Client.GetStringAsync("/admin/pages/library.js");
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
var shared = await server.Client.GetStringAsync("/admin/pages/library/shared.js");
// Esc and Ctrl+A in the grid change the selection through onChange: once no selected sequence lies beyond the loaded
// rows, "Select all" no longer holds, so its button comes back and a live refresh prunes the selection again.
Assert.True(Regex.IsMatch(library, @"onChange: \(\) => \{.*?if \(matching\) \{.*?\[\.\.\.selection\.ids\]\.every\(\(id\) => loaded\.has\(id\)\)\) matching = null;.*?syncSelection\(\);", RegexOptions.Singleline),
"the grid's onChange drops matching");
Assert.True(Regex.IsMatch(library, @"function clearFilters\(\) \{(?:(?!\n \}).)*selection\.clear\(\);\s+matching = null;", RegexOptions.Singleline),
"clearing the filters clears the selection as setFilter does");
// A delete of thousands of sequences or photos lists at most LISTED names (the dialog's title counts them all); the
// sequences that stay come first, with their reasons.
Assert.True(Regex.IsMatch(shared, @"export const LISTED = 500;"), "LISTED");
Assert.True(Regex.IsMatch(library, @"list: listed\(\[\.\.\.blocked\.map\("), "the sequences' delete list is capped, blocked first");
Assert.Contains("list: listed(names),", sequence);
Assert.False(Regex.IsMatch(library + sequence, @"list: \[\.\.\."), "an uncapped delete list");
}
/// <summary>The admin panel's modules from app.js and the menu's pages along their static imports, with their source.</summary>
private static async Task<Dictionary<string, string>> ModulesAsync(TestServer server)
{
var app = await server.Client.GetStringAsync("/admin/app.js");
// The upload dialog is a module the Library imports dynamically (owner review 2, R3); its hash worker is named by a URL.
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("upload.js").Prepend("app.js"));
var seen = new Dictionary<string, string>(StringComparer.Ordinal);
while (pending.TryDequeue(out var module))
{
if (seen.ContainsKey(module)) continue;
using var response = await server.Client.GetAsync("/admin/" + module);
Assert.Equal(HttpStatusCode.OK, response.StatusCode, module);
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType, module);
var source = await response.Content.ReadAsStringAsync();
seen[module] = source;
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in ModuleReference().Matches(source))
pending.Enqueue(Resolve(folder, import.Groups[1].Value));
}
return seen;
}
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
private static partial Regex StaticImport();
/// <summary>A module's static imports and the module workers it starts (<c>new URL("./…", import.meta.url)</c>).</summary>
[GeneratedRegex(@"(?:from |new URL\()""(\.{1,2}/[^""]+)""")]
private static partial Regex ModuleReference();
[Test]
public async Task TheUploadDialogsHashWorkerRunsUnderThePanelPolicy()
{
await using var server = await TestServer.StartAsync(context);
using var page = await server.Client.GetAsync("/admin/");
// CSP 3: a worker is allowed by worker-src, else child-src, else script-src, else default-src.
var policy = Directives(page);
var workers = new[] { "worker-src", "child-src", "script-src", "default-src" }.Select(d => policy.GetValueOrDefault(d)).First(v => v is not null);
Assert.SequenceEqual(["'self'"], Assert.NotNull(workers));
using var worker = await server.Client.GetAsync("/admin/hash-worker.js");
Assert.Equal(HttpStatusCode.OK, worker.StatusCode);
Assert.Equal("text/javascript", worker.Content.Headers.ContentType?.MediaType);
Assert.Equal("nosniff", worker.Headers.GetValues("X-Content-Type-Options").First());
// The worker runs under its own response's policy, which lets it import the hash from the same origin.
Assert.SequenceEqual(["'self'"], Assert.NotNull(Directives(worker).GetValueOrDefault("script-src")));
Assert.Contains(@"from ""./sha256.js""", await worker.Content.ReadAsStringAsync());
var upload = await server.Client.GetStringAsync("/admin/upload.js");
Assert.Contains(@"new Worker(new URL(""./hash-worker.js"", import.meta.url), { type: ""module"" })", upload);
Assert.Contains("api.putBytes(", upload);
// No folder picking on the web: importing a whole folder is a desktop feature (owner review 2, R9).
foreach (var picker in new[] { "webkitdirectory", "showDirectoryPicker", "mozdirectory" })
Assert.True(!upload.Contains(picker, StringComparison.OrdinalIgnoreCase), picker);
// The panel has no inline handlers for the policy to block (and none to allow).
Assert.True(!Regex.IsMatch(upload, @"\son[a-z]+="""), "inline handler");
}
/// <summary>The directives of a response's Content-Security-Policy, each with its sources.</summary>
private static Dictionary<string, string[]> Directives(HttpResponseMessage response) =>
string.Join(';', response.Headers.GetValues("Content-Security-Policy"))
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(d => d.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(d => d[0], d => d[1..], StringComparer.OrdinalIgnoreCase);
[Test]
public async Task AdminPanelDocksSettingsAtTheFootAndFoldsAboutIntoIt()
{
// Owner review 2: Settings below the other pages, About its last group; old #/about bookmarks open it there.
await using var server = await TestServer.StartAsync(context);
var app = await server.Client.GetStringAsync("/admin/app.js");
var groups = MenuPages(app);
Assert.Count(2, groups);
Assert.SequenceEqual(new[] { "settings" }, groups[1]);
Assert.DoesNotContain("about", groups[0]);
Assert.Contains(@"about: ""settings?group=about""", app);
using var about = await server.Client.GetAsync("/admin/pages/about.js");
Assert.Equal(HttpStatusCode.NotFound, about.StatusCode);
var settings = await server.Client.GetStringAsync("/admin/pages/settings.js");
Assert.Contains(@"id=""about-title""", settings);
// The page draws before the dashboard aggregate answers; these two rows fill in afterwards.
Assert.Contains(@"id=""about-database""", settings);
Assert.Contains(@"id=""about-uptime""", settings);
}
/// <summary>The menu's page groups as app.js lists them: the top pages, then the ones docked at the foot.</summary>
private static List<string[]> MenuPages(string app) =>
[.. Regex.Matches(app, @"const (?:top|bottom)Pages = \[([^\]]*)\]")
.Select(m => m.Groups[1].Value.Split(',').Select(p => p.Trim().Trim('"')).ToArray())];
private static string Resolve(string folder, string relative)
{
var parts = (folder + relative).Split('/').ToList();
for (var i = 0; i < parts.Count; i++)
{
if (parts[i] == ".") parts.RemoveAt(i--);
else if (parts[i] == ".." && i > 0) parts.RemoveRange(--i, 2);
}
return string.Join('/', parts.Where(p => p.Length > 0));
}
[Test]
public async Task I18nEndpointFallsBackToEnglish()
{
await using var server = await TestServer.StartAsync(context);
var it = await server.Client.GetFromJsonAsync("/api/v1/i18n/it-IT", ProtocolJson.Default.DictionaryStringString);
Assert.Equal("Accedi", Assert.NotNull(it)["Admin.Login.SignIn"]);
var unknown = await server.Client.GetFromJsonAsync("/api/v1/i18n/xx", ProtocolJson.Default.DictionaryStringString);
Assert.Equal("Sign in", Assert.NotNull(unknown)["Admin.Login.SignIn"]);
}
[Test]
public async Task I18nEndpointMarksRightToLeftLanguages()
{
await using var server = await TestServer.StartAsync(context);
foreach (var (culture, rtl) in new[] { ("ar", "true"), ("he", "true"), ("it", "false"), ("en", "false") })
{
var strings = Assert.NotNull(await server.Client.GetFromJsonAsync($"/api/v1/i18n/{culture}", ProtocolJson.Default.DictionaryStringString));
Assert.Equal((culture, rtl), (strings["$culture"], strings["$rtl"]));
// Count strings reach the panel in their plural forms.
Assert.True(strings.ContainsKey("Admin.Users.Accounts.one") && strings.ContainsKey("Admin.Users.Accounts.other"), culture);
}
}
[Test]
public void LinuxRefusesSqlite()
{
if (OperatingSystem.IsWindows()) TestContext.Skip("SQLite is allowed on Windows");
var options = new Chronos.Server.Configuration.ServerOptions { Database = Chronos.Server.Configuration.DatabaseKind.Sqlite };
Assert.Throws<InvalidOperationException>(options.Validate);
}
[Test]
public void EnvironmentOverridesDefaults()
{
var root = context.CreateTempDirectory("env");
var env = new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
["CHRONOS_HTTP_PORT"] = "9090",
["CHRONOS_TLS_MODE"] = "proxy",
["CHRONOS_DB"] = "postgres",
["CHRONOS_SERVER_NAME"] = "Studio NAS",
};
var options = Chronos.Server.Configuration.ServerOptions.Load(env);
Assert.Equal(9090, options.HttpPort);
Assert.Equal(Chronos.Server.Configuration.TlsMode.Proxy, options.TlsMode);
Assert.Equal("Studio NAS", options.ServerName);
}
}