Files
FinalToken/tests/FinalToken.StreamDeck.Tests/PluginTests.cs
T
Florian Schmidt fd30dfcea4
agent-review agent review: pass
fix: address the first agent review of PR #2
Blocking findings:
1. A Codex RPC error or early exit threw past LimitProbe and stopped the
   refresh loop, so Claude stopped updating too (D2). Every probe failure
   is now a failed probe result, the loop records an unexpected tick
   failure and keeps ticking, shutdown cancellation still propagates,
   the app reports failed operations, and the CLI exits 1 instead of
   crashing. Fake app-server modes in the GUI process host test errors,
   EOF and garbage.
2. Totals converted local midnight directly and threw where midnight
   does not exist (Cairo, Santiago, Beirut). Today and the week start
   through CalendarDays now.
3. Daily chart labels used UTC dates for local-day buckets; labels and
   tooltips now share the local date.

Review notes fixed as well: Claude Code installed with npm on Windows is
found through its native binary or cli.js; the plugin ends cleanly on a
bad host frame; Linux autostart honours XDG_CONFIG_HOME; the unused stub
installer and the worker names in docs are gone.

Refs #1
2026-10-14 21:50:09 +02:00

166 lines
8.9 KiB
C#

using System.Text.Json;
using System.Xml.Linq;
using FinalToken.Core;
using Xunit;
namespace FinalToken.StreamDeck.Tests;
public sealed class PluginTests
{
[Fact]
public async Task InvalidHostFrameEndsConnectionWithoutLoggingFrameText()
{
var socket = new FakeSocket { ReceiveFailure = new InvalidDataException("synthetic private frame") };
var session = new PluginSession(socket, _ => Task.FromResult(false));
Assert.Null(await session.ReceiveAsync(TestContext.Current.CancellationToken));
Assert.Equal("connection-ended", session.ConnectionEndCode);
}
[Theory]
[InlineData("{}", "Claude", "SessionPercent", "")]
[InlineData("{\"provider\":\"Codex\"}", "Codex", "SessionPercent", "")]
[InlineData("{\"metric\":\"TokensToday\",\"future\":1}", "Claude", "TokensToday", "")]
public void PartialStatSettingsKeepConstructorDefaults(string json, string provider, string metric, string window)
{
var settings = JsonSerializer.Deserialize(json, PluginJsonContext.Default.StatSettings)!;
Assert.Equal(new StatSettings(provider, metric, window), settings);
Assert.True(settings.IsValid);
}
private static readonly DateTimeOffset Now = new(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
private static Snapshot Snapshot(PaceState state = PaceState.Ahead) => new()
{
MadeAt = Now, RefreshInterval = TimeSpan.FromMinutes(1), AppPath = "app.exe",
Providers = [new(Provider.Claude, ProviderStatus.Available, null,
[new(new(Provider.Claude, "session", "Session", 65, Now.AddHours(2), TimeSpan.FromHours(5), Now, "test"), new(state, .6, 5)),
new(new(Provider.Claude, "week", "Week", 42, Now.AddDays(2), TimeSpan.FromDays(7), Now, "test"), new(state, .5, -8))],
new(Total: 12345), null, new(Total: 2345678))]
};
[Fact]
public async Task RegistersAndSettingsRoundTripWithDeduplicatedDrawing()
{
var socket = new FakeSocket();
var session = new PluginSession(socket, _ => Task.FromResult(true));
await session.RegisterAsync(new(1234, "registration-id", "registerPlugin"), TestContext.Current.CancellationToken);
Assert.Equal("registerPlugin", Read(socket.Sent[0], "event"));
Assert.Equal("registration-id", Read(socket.Sent[0], "uuid"));
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
await session.HandleAsync("""{"event":"willAppear","action":"de.finalfactory.finaltoken.stat","context":"key","payload":{"settings":{}}}""", Now, TestContext.Current.CancellationToken);
var count = socket.Sent.Count;
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
Assert.Equal(count, socket.Sent.Count);
await session.HandleAsync("""{"event":"sendToPlugin","context":"key","payload":{"settings":{"provider":"Claude","metric":"TokensWeek","window":"week"}}}""", Now, TestContext.Current.CancellationToken);
using var settings = JsonDocument.Parse(socket.Sent.Single(s => Read(s, "event") == "setSettings"));
Assert.Equal("TokensWeek", settings.RootElement.GetProperty("payload").GetProperty("metric").GetString());
Assert.Equal("sendToPropertyInspector", Read(socket.Sent[^1], "event"));
await session.HandleAsync("""{"event":"willDisappear","context":"key"}""", Now, TestContext.Current.CancellationToken);
count = socket.Sent.Count;
await session.UpdateAsync(new(null, true, null), Now, TestContext.Current.CancellationToken);
Assert.Equal(count, socket.Sent.Count);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task KeyPressLaunchesSnapshotAppAndAlertsFailure(bool success)
{
string? path = null;
var socket = new FakeSocket();
var session = new PluginSession(socket, value => { path = value; return Task.FromResult(success); });
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
await session.HandleAsync("""{"event":"keyDown","context":"key"}""", Now, TestContext.Current.CancellationToken);
Assert.Equal("app.exe", path);
Assert.Equal(success ? 0 : 1, socket.Sent.Count);
if (!success) Assert.Equal("showAlert", Read(socket.Sent[0], "event"));
}
[Theory]
[InlineData("SessionPercent", "65%")]
[InlineData("WeekPercent", "42%")]
[InlineData("PaceDelta", "+5pp")]
[InlineData("TimeToReset", "2h 0m")]
[InlineData("TokensToday", "12.3k")]
[InlineData("TokensWeek", "2.3M")]
public void RendersEveryMetric(string metric, string value)
{
var svg = StatRenderer.Render(new(Snapshot(), false, null), new(Metric: metric), Now);
Assert.Contains(value, svg);
Assert.Equal("svg", XDocument.Parse(svg).Root!.Name.LocalName);
}
[Theory]
[InlineData(PaceState.Ahead, "#ef6461")]
[InlineData(PaceState.Behind, "#69a7ff")]
[InlineData(PaceState.OnTrack, "#58d6a0")]
[InlineData(PaceState.Unknown, "#a0a7b4")]
public void RendersPaceColorAndMarker(PaceState state, string color)
{
var svg = StatRenderer.Render(new(Snapshot(state), false, null), new(), Now);
Assert.Contains(color, svg);
Assert.Contains("M42 56v11", svg);
}
[Fact]
public void StaleMissingAndUnknownWindowAreExplicit()
{
Assert.Contains("offline", StatRenderer.Render(new(Snapshot(), true, null), new(), Now));
Assert.Contains("offline", StatRenderer.Render(new(null, true, null), new(), Now));
Assert.Contains("—", StatRenderer.Render(new(Snapshot(), false, null), new(Window: "removed"), Now));
}
[Fact]
public void NullNestedSnapshotContentShowsOffline()
{
var snapshot = Snapshot() with { Providers = [new(Provider.Claude, ProviderStatus.Available, null, null!, new(), null, new())] };
Assert.Contains("offline", StatRenderer.Render(new(snapshot, false, null), new(), Now));
}
[Fact]
public void PaceAndResetUseAvailableWeekWhenNoSessionExists()
{
var provider = Snapshot().Providers[0];
provider = provider with { Windows = [provider.Windows[1]] };
Assert.Equal("week", StatRenderer.SelectWindow(provider, new(Metric: "PaceDelta"))?.Window.Id);
Assert.Equal("week", StatRenderer.SelectWindow(provider, new(Metric: "TimeToReset"))?.Window.Id);
Assert.Null(StatRenderer.SelectWindow(provider, new()));
}
[Fact]
public async Task MalformedAndInvalidSettingsDoNotChangeKeys()
{
var socket = new FakeSocket();
var session = new PluginSession(socket, _ => Task.FromResult(false));
foreach (var json in new[] { "{", "[]", "null", """{"event":"willAppear","context":"key","payload":{"settings":{"provider":"Unknown"}}}""" })
await session.HandleAsync(json, Now, TestContext.Current.CancellationToken);
Assert.Empty(socket.Sent);
}
[Fact]
public void RegistrationValidatesArguments()
{
Assert.NotNull(Registration.Parse(["-port", "1234", "-pluginUUID", "x", "-registerEvent", "registerPlugin", "-info", "{}"]));
Assert.Null(Registration.Parse(["-port", "0"]));
}
[Fact]
public void ManifestHasExpectedContractAndLocalAssets()
{
var folder = Path.Combine(AppContext.BaseDirectory, "plugin");
using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(folder, "manifest.json")));
var root = manifest.RootElement;
Assert.Equal(2, root.GetProperty("SDKVersion").GetInt32());
Assert.Equal("de.finalfactory.finaltoken", root.GetProperty("UUID").GetString());
Assert.Equal("FinalToken.StreamDeck.exe", root.GetProperty("CodePathWin").GetString());
Assert.Equal("FinalToken.StreamDeck", root.GetProperty("CodePathLin").GetString());
Assert.True(Version.TryParse(root.GetProperty("Version").GetString(), out _));
Assert.Single(root.GetProperty("Actions").EnumerateArray());
Assert.Equal(PluginSession.Action, root.GetProperty("Actions")[0].GetProperty("UUID").GetString());
Assert.True(File.Exists(Path.Combine(folder, root.GetProperty("PropertyInspectorPath").GetString()!)));
Assert.True(File.Exists(Path.Combine(folder, root.GetProperty("Icon").GetString()! + ".svg")));
}
private static string? Read(string json, string property)
{
using var doc = JsonDocument.Parse(json);
return doc.RootElement.GetProperty(property).GetString();
}
private sealed class FakeSocket : IPluginSocket
{
public Exception? ReceiveFailure { get; init; }
public List<string> Sent { get; } = [];
public Task SendAsync(string json, CancellationToken cancellationToken) { Sent.Add(json); return Task.CompletedTask; }
public Task<string?> ReceiveAsync(CancellationToken cancellationToken) => ReceiveFailure is { } error
? Task.FromException<string?>(error) : Task.FromResult<string?>(null);
}
}