Files
Chronos/tests/Chronos.Server.Tests/Hosting/AdminProjectsTests.cs
T
Alby96andClaude Opus 5.5 353024fc71 fix(panel): projects table fits narrow widths, keeps loaded versions on refresh, skips settings
The projects table sits in a min-width-0 host so fitColumns can drop columns.
A live refresh re-reads only the changed, expanded projects and keeps as many
versions as were shown (Load more included). Version pages ask for the summary
form, so the panel no longer downloads settings it never shows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:31:51 +01:00

205 lines
13 KiB
C#

using System.Globalization;
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
/// <summary>
/// The projects of a sequence on the admin panel (owner review 2, R8; <c>Admin/web/pages/library/projects.js</c>): the
/// sequence page's Projects section, what it lists and offers (Rename and Delete, never for Main, nothing that edits
/// settings), its strings, and the requests it writes, sent through the cookie session as <c>api.js</c> sends them and read
/// back by the names the page reads.
/// </summary>
[Category("server")]
public sealed partial class AdminProjectsTests(TestContext context)
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
[Test]
public async Task TheSequencePageListsItsProjectsAndManagesThoseOtherThanMain()
{
await using var server = await TestServer.StartAsync(context);
var page = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
Assert.Contains(@"import { projectsSection } from ""./projects.js"";", page);
Assert.Contains(@"<h2 id=""projects-title"" data-i18n=""Admin.Projects.Title""></h2>", page);
Assert.Contains("projects.onEvent(e);", page);
using var response = await server.Client.GetAsync("/admin/pages/library/projects.js");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType);
var projects = await response.Content.ReadAsStringAsync();
Assert.True(Regex.IsMatch(projects, @"export function projectsSection\(host, meta, \{ api, sequenceId \}\)"), "projects.js exports projectsSection");
var imports = StaticImport().Matches(projects).Select(m => m.Groups[1].Value).ToList();
Assert.SequenceEqual(["../../i18n.js", "../../ui.js"], imports);
Assert.True(!Regex.IsMatch(projects, @"\son[a-z]+="""), "inline handler");
// It lists, opens versions, renames and deletes: no push, no restore, no settings (R6: the panel manages, never edits).
Assert.Contains("projects = await api.get(base);", projects);
// Versions are read without their settings, which the panel never shows (a large sequence's are megabytes each).
Assert.Contains("api.get(`${base}/${encodeURIComponent(id)}/versions?limit=${limit}${before}&summary=true`)", projects);
// A live refresh reads again only the opened projects an event named (every one after a reconnection), as many
// versions as are shown: the pages Load more read stay.
Assert.Contains("const again = [...expanded].filter((id) => stale === null || stale.has(id));", projects);
Assert.Contains("return loadVersions(id, false, Math.min(MAX_PAGE, Math.max(VERSION_PAGE, shown)));", projects);
Assert.Contains("else changed?.add(e.projectId);", projects);
// The table's wrapper may be narrower than the table (a grid item of the panel), so its columns fit on a phone.
Assert.Contains(@"<div id=""projects"" class=""table-host""></div>", page);
Assert.Contains(".panel > .table-host { min-width: 0; }", await server.Client.GetStringAsync("/admin/admin.css"));
Assert.Contains("await api.patch(`${base}/${encodeURIComponent(project.id)}`, { name });", projects);
Assert.Contains("await api.del(`${base}/${encodeURIComponent(project.id)}`);", projects);
Assert.False(projects.Contains("api.post(", StringComparison.Ordinal), "the panel pushes or makes nothing");
Assert.False(projects.Contains("settingsJson", StringComparison.Ordinal), "the panel reads no settings");
// Main is marked and never renamed or deleted here.
Assert.Contains(@"const actions = p.isMain ? """" : `", projects);
Assert.Contains("if (!project || project.isMain) return;", projects);
Assert.Contains("p.isMain && p.name === MAIN_NAME ? t(\"Admin.Projects.Main\") : p.name", projects);
// A deletion is confirmed first, naming the project.
Assert.Contains("title: t(\"Admin.Projects.DeleteTitle\", project.name),", projects);
Assert.Contains("const confirmed = await confirmDialog({", projects);
// The list follows projectChanged of this sequence, and a reconnection.
Assert.Contains(@"(e.type === ""projectChanged"" && e.sequenceId === sequenceId) || e.type === ""reconnected""", projects);
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
var keys = Regex.Matches(projects + page, @"""(Admin\.Projects\.[A-Za-z.]+)""").Select(m => m.Groups[1].Value).Distinct().ToList();
Assert.True(keys.Count > 20, $"{keys.Count} keys");
foreach (var kind in new[] { "Commit", "Merge", "Restore", "Imported", "External" }) keys.AddRange([$"Admin.Projects.Kind.{kind}", $"Admin.Projects.Kind.{kind}.Tip"]);
foreach (var key in keys)
{
var name = en.ContainsKey(key) ? key : key + ".other";
Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key);
}
Assert.Equal("Principale", it["Admin.Projects.Main"]);
Assert.Equal("Modifica esterna", it["Admin.Projects.Kind.External"]);
}
[Test]
public async Task ThePagesRequestsListRenameAndDeleteProjects()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
Guid sid = default;
for (var i = 0; i < 2; i++) sid = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "pier")).SequenceId;
await UntilIdleAsync(server);
var browser = await Browser.SignInAsync(server);
var url = $"/api/v1/sequences/{sid}/projects";
// Made on a PC (the panel makes none): a project the page lists after Main.
using (var created = await editor.PostAsJsonAsync(url, new CreateProjectRequest("Vertical social"), ProtocolJson.Default.CreateProjectRequest))
await created.ExpectAsync(HttpStatusCode.Created);
Guid vertical;
using (var list = await browser.SendAsync(HttpMethod.Get, url))
{
await list.ExpectAsync(HttpStatusCode.OK);
using var json = JsonDocument.Parse(await list.Content.ReadAsStringAsync());
var items = json.RootElement.EnumerateArray().ToList();
Assert.Count(2, items);
var main = items[0];
Assert.Equal((true, "Main", 1), (main.GetProperty("isMain").GetBoolean(), main.GetProperty("name").GetString(), main.GetProperty("headNumber").GetInt32()));
var project = items[1];
Assert.False(project.GetProperty("isMain").GetBoolean());
vertical = project.GetProperty("id").GetGuid();
// The names the page reads for the last change.
Assert.Equal(("imported", "alberto"), (project.GetProperty("headKind").GetString(), project.GetProperty("headAuthor").GetString()));
Assert.True(project.TryGetProperty("headStoredAt", out _) && project.TryGetProperty("updatedAt", out _) && project.TryGetProperty("headVersionId", out _));
}
using (var versions = await browser.SendAsync(HttpMethod.Get, $"{url}/{vertical}/versions?limit=20"))
{
await versions.ExpectAsync(HttpStatusCode.OK);
using var json = JsonDocument.Parse(await versions.Content.ReadAsStringAsync());
var first = json.RootElement.GetProperty("items").EnumerateArray().Single();
Assert.Equal((1, "imported"), (first.GetProperty("number").GetInt32(), first.GetProperty("kind").GetString()));
Assert.True(first.TryGetProperty("storedAt", out _) && first.TryGetProperty("createdAt", out _) && first.TryGetProperty("clientName", out _));
Assert.False(json.RootElement.GetProperty("more").GetBoolean());
Assert.NotEqual(string.Empty, first.GetProperty("settingsJson").GetString());
}
// The page's own form: the same versions, without their settings.
using (var versions = await browser.SendAsync(HttpMethod.Get, $"{url}/{vertical}/versions?limit=20&summary=true"))
{
await versions.ExpectAsync(HttpStatusCode.OK);
using var json = JsonDocument.Parse(await versions.Content.ReadAsStringAsync());
var first = json.RootElement.GetProperty("items").EnumerateArray().Single();
Assert.Equal((1, "imported", string.Empty), (first.GetProperty("number").GetInt32(), first.GetProperty("kind").GetString(),
first.GetProperty("settingsJson").GetString()));
Assert.Equal(64, first.GetProperty("contentHash").GetString()!.Length);
}
using (var renamed = await browser.SendAsync(HttpMethod.Patch, $"{url}/{vertical}", Json("""{"name":"Vertical"}""")))
{
await renamed.ExpectAsync(HttpStatusCode.OK);
using var json = JsonDocument.Parse(await renamed.Content.ReadAsStringAsync());
Assert.Equal("Vertical", json.RootElement.GetProperty("name").GetString());
}
// Refusals carry the page's language, which its toast shows.
using (var taken = await browser.SendAsync(HttpMethod.Patch, $"{url}/{vertical}", Json("""{"name":"main"}""")))
Assert.Equal(Loc.Get("Server.Error.NameTaken", CultureInfo.GetCultureInfo("it")), (await taken.ExpectErrorAsync(HttpStatusCode.Conflict, "name_taken")).Message);
var mainId = (await server.Database.Projects.GetMainAsync(sid))!.Id;
using (var kept = await browser.SendAsync(HttpMethod.Delete, $"{url}/{mainId}"))
await kept.ExpectErrorAsync(HttpStatusCode.Conflict, "main_cannot_be_deleted");
using (var deleted = await browser.SendAsync(HttpMethod.Delete, $"{url}/{vertical}")) await deleted.ExpectAsync(HttpStatusCode.NoContent);
using (var list = await browser.SendAsync(HttpMethod.Get, url))
{
using var json = JsonDocument.Parse(await list.Content.ReadAsStringAsync());
Assert.SequenceEqual([mainId], json.RootElement.EnumerateArray().Select(p => p.GetProperty("id").GetGuid()));
}
}
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
private static partial Regex StaticImport();
private static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json");
private static async Task UntilIdleAsync(TestServer server)
{
var until = DateTime.UtcNow + Wait;
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
{
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50);
}
}
}
private static byte[] Photo(int seed)
{
const int width = 96, height = 64;
var pixels = new byte[width * height * 3];
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
}
private sealed class Browser(HttpClient client, string csrfToken)
{
public static async Task<Browser> SignInAsync(TestServer server)
{
await server.AdminAsync();
var cookies = new CookieContainer();
var client = server.NewCookieClient(cookies);
using var login = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true),
ProtocolJson.Default.LoginRequest);
await login.ExpectAsync(HttpStatusCode.OK);
return new Browser(client, Assert.NotNull(cookies.GetCookies(Assert.NotNull(server.HttpsBase))["chronos_csrf"]).Value);
}
/// <summary>JSON accepted, the page's language (Italian here), and the CSRF header on every call but a GET.</summary>
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string url, HttpContent? content = null)
{
using var request = new HttpRequestMessage(method, url) { Content = content };
request.Headers.Accept.ParseAdd("application/json");
request.Headers.AcceptLanguage.ParseAdd("it");
if (method != HttpMethod.Get) request.Headers.Add("X-CSRF-Token", csrfToken);
return await client.SendAsync(request);
}
}
}