Files
Chronos/tests/Titano.Server.Tests/Api/AdminTests.cs
T
Claude bdcd4e42ae test(server): the busy-log test writes a line a millisecond, never in a tight loop
Engine code of every test server in the process logs through the last server
started (Log.SetSink is process-wide), so the busy-log test's file lock is
shared with the classes running alongside: a loop that re-took it at once kept
a job engine of JobApiTests waiting to log a failure, and its job "running"
past the 15 s deadline (once in 40 loaded runs). The test now fills the log
with a few megabytes up front, so sending it takes a while, and adds a line
about every millisecond during the downloads; it still fails every run against
the old endpoint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-06 22:03:31 +00:00

133 lines
7.3 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Nodes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Titano.Protocol;
using Titano.Server.Hosting;
using Titano.Testing;
namespace Titano.Server.Tests.Api;
[Category("server")]
public sealed class AdminTests(TestContext context)
{
[Test]
public async Task TheDashboardSummarisesTheServer()
{
await using var server = await TestServer.StartAsync(context, o => o.ServerName = "Studio NAS");
var (editor, _, _) = await server.UserAsync("alberto", "editor");
await Uploads.UploadAsync(editor, Uploads.Photo(4000, 61));
var admin = await server.AdminAsync();
using var response = await admin.GetAsync("/api/v1/server/dashboard");
await response.ExpectAsync(HttpStatusCode.OK);
var dashboard = await response.ReadAsync(ProtocolJson.Default.DashboardDto);
Assert.Equal(("Studio NAS", 2, 1L, 1L), (dashboard.ServerName, dashboard.Users, dashboard.Archive.Sequences, dashboard.Archive.Photos));
Assert.True(dashboard.Database.StartsWith("SQLite ", StringComparison.Ordinal), dashboard.Database);
Assert.Equal(1L, dashboard.Uploads.Single().Frames);
Assert.Contains(dashboard.Activity, a => a.Action == "user_created");
Assert.True(dashboard.Archive.CapacityBytes > 0);
}
[Test]
public async Task SettingsAreSavedAndRestartOnlyValuesFlagged()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/server/settings");
var settings = await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
Assert.False(settings.RestartRequired);
var edited = settings with { ServerName = "Rooftop", Discovery = true, HttpPort = 18080, HttpsPort = 18443 };
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto))
Assert.True((await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).RestartRequired);
// Name and discovery apply at once; ports wait for the restart.
Assert.Equal(("Rooftop", true, 0), (server.Options.ServerName, server.Options.Discovery, server.Options.HttpPort));
using (var again = await admin.GetAsync("/api/v1/server/settings"))
Assert.Equal(18080, (await again.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).HttpPort);
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
Assert.Equal(("Rooftop", 18080), (file["ServerName"]!.GetValue<string>(), file["HttpPort"]!.GetValue<int>()));
Assert.False(file.ContainsKey("AdminPassword"));
using var invalid = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Language = "tlh" }, ProtocolJson.Default.ServerSettingsDto);
Assert.Equal("Language", (await invalid.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_setting")).Details);
}
[Test]
public async Task LogsAreReadableButOnlyByName()
{
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = Microsoft.Extensions.Logging.LogLevel.Information);
var admin = await server.AdminAsync();
using var tail = await admin.GetAsync("/api/v1/logs?lines=20");
var lines = await tail.ReadAsync(ProtocolJson.Default.LogTailDto);
Assert.NotEmpty(lines.Lines);
Assert.True(lines.Lines.Count <= 20);
using var files = await admin.GetAsync("/api/v1/logs/files");
var name = (await files.ReadAsync(ProtocolJson.Default.ListLogFileDto)).First().Name;
using (var download = await admin.GetAsync($"/api/v1/logs/files/{name}")) await download.ExpectAsync(HttpStatusCode.OK);
using var traversal = await admin.GetAsync("/api/v1/logs/files/..%2Fserver.json");
await traversal.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
[Test]
public async Task TheCurrentLogDownloadsWhileTheServerKeepsLogging()
{
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = Microsoft.Extensions.Logging.LogLevel.Information);
var admin = await server.AdminAsync();
using var files = await admin.GetAsync("/api/v1/logs/files");
var name = (await files.ReadAsync(ProtocolJson.Default.ListLogFileDto)).First().Name;
// Jobs, uploads and sign-ins keep writing to the file an administrator downloads: a log of a few megabytes takes
// a while to send, and a line lands about every millisecond meanwhile. Only to the file and never in a tight loop:
// engine code of every test server in this process logs through the last one started, so this server's console
// and file lock are shared with the tests running alongside.
var logger = server.Services.GetServices<ILoggerProvider>().OfType<FileLoggerProvider>().Single().CreateLogger("Titano.Server.Tests");
var block = new string('x', 64 * 1024);
for (var i = 0; i < 32; i++) logger.LogInformation("{Block}", block);
using var stop = new CancellationTokenSource();
var logging = Task.Factory.StartNew(() =>
{
while (!stop.IsCancellationRequested)
{
logger.LogInformation("Busy");
Thread.Sleep(1);
}
}, TaskCreationOptions.LongRunning);
try
{
for (var i = 0; i < 5; i++)
{
using var download = await admin.GetAsync($"/api/v1/logs/files/{name}");
await download.ExpectAsync(HttpStatusCode.OK);
Assert.Equal(download.Content.Headers.ContentLength, (await download.Content.ReadAsByteArrayAsync()).LongLength);
}
}
finally
{
await stop.CancelAsync();
await logging;
}
}
[Test]
public async Task ArchiveSettingsValidateTemplatesAndJobsNeedHandlers()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
using var read = await admin.GetAsync("/api/v1/archive/settings");
var archive = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
Assert.Equal(Path.GetFullPath(server.Options.ArchivePath), archive.RootPath);
using (var bad = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { FolderTemplate = "{year/{date" }, ProtocolJson.Default.ArchiveSettingsDto))
Assert.Equal("folderTemplate", (await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
using (var good = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { Name = "Studio", ProxyLongEdge = 2560 }, ProtocolJson.Default.ArchiveSettingsDto))
{
var saved = await good.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
Assert.Equal(("Studio", 2560), (saved.Name, saved.ProxyLongEdge));
}
using var scan = await admin.PostAsync("/api/v1/archive/scan", null);
await scan.ExpectErrorAsync(HttpStatusCode.Conflict, "job_unavailable");
using var stats = await admin.GetAsync("/api/v1/archive/stats");
await stats.ExpectAsync(HttpStatusCode.OK);
}
}