Repository navigation
Expand file tree
/
Copy pathSelfTests.cs
More file actions
444 lines (408 loc) · 17.9 KB
/
Copy pathSelfTests.cs
File metadata and controls
444 lines (408 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
namespace CodexUsageTray;
internal static class SelfTests
{
/// <summary>
/// Runs deterministic package-free checks followed by one live Codex CLI smoke read.
/// </summary>
/// <returns>Zero when every check succeeds; otherwise one.</returns>
internal static async Task<int> RunAsync()
{
try
{
DateTimeOffset now = DateTimeOffset.Now;
long reset = now.AddHours(1).ToUnixTimeSeconds();
UsageSnapshot both = Parse(
Window(25, CodexRateLimitReader.FiveHourMinutes, reset),
Window(60, CodexRateLimitReader.WeeklyMinutes, reset),
now);
Check(both.FiveHour.RemainingPercent == 75, "Five-hour remaining percentage was incorrect.");
Check(both.Weekly.RemainingPercent == 40, "Weekly remaining percentage was incorrect.");
UsageSnapshot single = Parse(
Window(10, CodexRateLimitReader.FiveHourMinutes, reset),
null,
now);
Check(single.FiveHour.State == LimitState.Available, "Single five-hour window was not available.");
Check(single.Weekly.State == LimitState.Unavailable, "Missing weekly window was not unavailable.");
UsageSnapshot weeklyOnly = Parse(
Window(15, CodexRateLimitReader.WeeklyMinutes, reset),
null,
now);
Check(weeklyOnly.FiveHour.State == LimitState.Unavailable, "Missing five-hour window was not unavailable.");
Check(weeklyOnly.Weekly.State == LimitState.Available, "Single weekly window was not available.");
UsageSnapshot reversed = Parse(
Window(30, CodexRateLimitReader.WeeklyMinutes, reset),
Window(40, CodexRateLimitReader.FiveHourMinutes, reset),
now);
Check(reversed.FiveHour.RemainingPercent == 60, "Reversed five-hour window was misclassified.");
Check(reversed.Weekly.RemainingPercent == 70, "Reversed weekly window was misclassified.");
UsageSnapshot clamped = Parse(
Window(-10, CodexRateLimitReader.FiveHourMinutes, reset),
Window(150, CodexRateLimitReader.WeeklyMinutes, reset),
now);
Check(clamped.FiveHour.RemainingPercent == 100, "Negative usage was not clamped.");
Check(clamped.Weekly.RemainingPercent == 0, "Excess usage was not clamped.");
ExpectThrows<CodexUsageException>(
() => CodexRateLimitReader.ParseUsageResponse("{", now),
"Malformed JSON was accepted.");
ExpectThrows<CodexUsageException>(
() => CodexRateLimitReader.ThrowIfProtocolError(
"""{"id":2,"error":{"message":"denied"}}"""),
"Protocol error was accepted.");
TestWeeklyDailyRates(now);
TestWeeklyEndOfDayTarget(now);
TestWeeklyLeft(now);
TestUsageHistoryPersistence(now);
TestPlotHistorySelection(now);
TestUsagePrediction(now);
TestHistoryCsv(now);
TestPopupReopen();
using (CancellationTokenSource timeout = new(TimeSpan.FromMilliseconds(20)))
{
await ExpectThrowsAsync<OperationCanceledException>(
() => CodexRateLimitReader.WaitForResponseAsync(
new BlockingTextReader(),
2,
timeout.Token),
"Cancellation did not stop a pending protocol read.").ConfigureAwait(false);
}
TestAlertPersistence(now);
TestStartupRegistration();
TestDuplicateMutex();
UsageSnapshot live = await new CodexRateLimitReader().FetchAsync().ConfigureAwait(false);
Check(
live.FiveHour.State == LimitState.Available || live.Weekly.State == LimitState.Available,
"The live Codex smoke read returned no available usage window.");
Console.WriteLine("Self-tests passed.");
return 0;
}
catch (Exception exception)
{
Console.Error.WriteLine($"Self-test failed: {exception.Message}");
return 1;
}
}
/// <summary>
/// Verifies the graph history selector switches between current-window and all-data modes.
/// </summary>
/// <param name="now">The timestamp used for deterministic history samples.</param>
private static void TestPlotHistorySelection(DateTimeOffset now)
{
DateTimeOffset windowStart = now.AddDays(-7);
DateTimeOffset windowEnd = now;
UsageHistoryPoint oldPoint = new(now.AddDays(-8), 90);
UsageHistoryPoint currentPoint = new(now.AddDays(-1), 70);
UsageHistoryPoint[] history = [currentPoint, oldPoint];
UsageHistoryPoint[] weekly = UsagePopup.SelectPlotHistory(
history,
windowStart,
windowEnd,
includeAllHistory: false);
UsageHistoryPoint[] all = UsagePopup.SelectPlotHistory(
history,
windowStart,
windowEnd,
includeAllHistory: true);
Check(weekly.Length == 1 && weekly[0] == currentPoint, "Weekly plot history selection was incorrect.");
Check(all.Length == 2 && all[0] == oldPoint, "All-data plot history selection was incorrect.");
}
/// <summary>
/// Verifies the downloadable weekly time-series CSV.
/// </summary>
/// <param name="now">The timestamp used for deterministic history samples.</param>
private static void TestHistoryCsv(DateTimeOffset now)
{
string csv = UsagePopup.BuildHistoryCsv(
[
new UsageHistoryPoint(now.AddMinutes(-5), 80),
new UsageHistoryPoint(now, 75),
]);
Check(
csv.StartsWith(
"recordedAt,remainingPercent",
StringComparison.Ordinal),
"Usage-history CSV header was incorrect.");
Check(csv.Contains(",75", StringComparison.Ordinal), "Usage-history CSV data was incorrect.");
}
/// <summary>
/// Verifies the zero-usage prediction from declining weekly samples.
/// </summary>
/// <param name="now">The timestamp used for deterministic history samples.</param>
private static void TestUsagePrediction(DateTimeOffset now)
{
UsageHistoryPoint[] declining =
[
new UsageHistoryPoint(now.AddHours(-2), 80),
new UsageHistoryPoint(now, 60),
];
Check(
UsagePopup.PredictZeroAt(declining) == now.AddHours(6),
"Weekly zero prediction was incorrect.");
Check(
UsagePopup.PredictZeroAt(
[
new UsageHistoryPoint(now.AddHours(-1), 60),
new UsageHistoryPoint(now, 60),
]) is null,
"Flat weekly history produced a zero prediction.");
}
/// <summary>
/// Verifies weekly usage-history retention and persistence.
/// </summary>
/// <param name="now">The timestamp used to create retained and expired samples.</param>
private static void TestUsageHistoryPersistence(DateTimeOffset now)
{
string directory = Path.Combine(Path.GetTempPath(), $"CodexUsageTray-{Guid.NewGuid():N}");
string path = Path.Combine(directory, "usage-history.json");
try
{
UsageHistoryStore store = new(path);
LimitReading reading = new(LimitState.Available, 80, now.AddDays(1));
store.Record(reading, now.AddDays(-8));
store.Record(reading with { RemainingPercent = 55 }, now);
Check(store.Points.Count == 1, "Expired weekly usage history was retained.");
Check(store.Points[0].RemainingPercent == 55, "Weekly usage history value was incorrect.");
Check(new UsageHistoryStore(path).Points.Count == 1, "Weekly usage history was not persisted.");
}
finally
{
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
/// <summary>
/// Verifies weekly per-day rates and unavailable reset handling.
/// </summary>
/// <param name="now">The timestamp used for deterministic rate calculations.</param>
private static void TestWeeklyDailyRates(DateTimeOffset now)
{
LimitReading reading = new(LimitState.Available, 55, now.AddDays(4));
Check(
UsagePopup.FormatWeeklyDailyRates(reading, now)
== "Per day: 15.0% used · 13.8% left",
"Weekly per-day rates were incorrect.");
Check(
UsagePopup.FormatWeeklyDailyRates(reading with { ResetsAt = null }, now)
== "Per-day rates unavailable",
"Missing weekly reset time did not make per-day rates unavailable.");
}
/// <summary>
/// Verifies the allowance target at the next whole-day weekly boundary.
/// </summary>
/// <param name="now">The timestamp used for deterministic target calculations.</param>
private static void TestWeeklyEndOfDayTarget(DateTimeOffset now)
{
LimitReading reading = new(LimitState.Available, 55, now.AddDays(5).AddHours(11));
Check(
UsagePopup.FormatWeeklyEndOfDayTarget(reading, now)
== "End of day: 71.4% left in 11h",
"Weekly end-of-day target was incorrect.");
Check(
UsagePopup.FormatWeeklyEndOfDayTarget(reading with { ResetsAt = now.AddDays(5) }, now)
== "End of day: 71.4% left now",
"Whole-day weekly target was not due now.");
Check(
UsagePopup.FormatWeeklyEndOfDayTarget(reading with { ResetsAt = null }, now)
== "End of day target unavailable",
"Missing weekly reset time did not make the end-of-day target unavailable.");
}
/// <summary>
/// Verifies the weekly allowance remaining above the next whole-day target.
/// </summary>
/// <param name="now">The timestamp used for deterministic target calculations.</param>
private static void TestWeeklyLeft(DateTimeOffset now)
{
LimitReading reading = new(LimitState.Available, 55, now.AddDays(5).AddHours(11));
double? left = UsagePopup.CalculateWeeklyLeft(reading, now);
Check(left is < 0, "Weekly allowance left was not negative.");
Check(
UsagePopup.FormatWeeklyLeft(reading, now) == "Left: -16.4%",
"Weekly allowance left was incorrect.");
Check(
TrayIconRenderer.ResolveTextColor(left) == Color.Red,
"Negative weekly allowance left did not produce red tray text.");
Check(
TrayIconRenderer.ResolveTextColor(0) == Color.LimeGreen,
"Non-negative weekly allowance left did not produce green tray text.");
Check(
TrayIconRenderer.ResolveTextColor(null) == Color.Gray,
"Unavailable weekly allowance left did not produce gray tray text.");
Check(
UsagePopup.FormatWeeklyLeft(reading with { RemainingPercent = null }, now)
== "Left unavailable",
"Missing weekly percentage did not make allowance left unavailable.");
}
/// <summary>
/// Verifies that a user close hides the reusable popup instead of disposing it.
/// </summary>
private static void TestPopupReopen()
{
using UsagePopup popup = new();
popup.Show();
popup.Close();
Check(!popup.IsDisposed, "Closing the popup disposed it.");
popup.Show();
popup.Hide();
}
/// <summary>
/// Builds and parses a general Codex response containing up to two windows.
/// </summary>
/// <param name="primary">The primary window JSON, or null.</param>
/// <param name="secondary">The secondary window JSON, or null.</param>
/// <param name="now">The refresh timestamp.</param>
/// <returns>The normalized usage snapshot.</returns>
private static UsageSnapshot Parse(string? primary, string? secondary, DateTimeOffset now)
{
List<string> properties = [];
if (primary is not null)
{
properties.Add($"\"primary\":{primary}");
}
if (secondary is not null)
{
properties.Add($"\"secondary\":{secondary}");
}
string response =
"{\"id\":2,\"result\":{\"rateLimitsByLimitId\":{\"codex\":{"
+ string.Join(',', properties)
+ "}}}}";
return CodexRateLimitReader.ParseUsageResponse(response, now);
}
/// <summary>
/// Builds one rate-limit window JSON object.
/// </summary>
/// <param name="usedPercent">The reported used percentage.</param>
/// <param name="durationMinutes">The window duration in minutes.</param>
/// <param name="reset">The Unix reset timestamp.</param>
/// <returns>The serialized window.</returns>
private static string Window(int usedPercent, long durationMinutes, long reset) =>
$"{{\"usedPercent\":{usedPercent},\"windowDurationMins\":{durationMinutes},\"resetsAt\":{reset}}}";
/// <summary>
/// Verifies alert thresholds and deduplication across store instances.
/// </summary>
/// <param name="now">The timestamp used to create reset cycles.</param>
private static void TestAlertPersistence(DateTimeOffset now)
{
string directory = Path.Combine(Path.GetTempPath(), $"CodexUsageTray-{Guid.NewGuid():N}");
string path = Path.Combine(directory, "alerts.json");
try
{
LimitReading low = new(LimitState.Available, 20, now.AddHours(1));
Check(new AlertStateStore(path).ShouldAlert("five-hour", low), "First low alert was suppressed.");
Check(!new AlertStateStore(path).ShouldAlert("five-hour", low), "Alert was not persisted.");
Check(
new AlertStateStore(path).ShouldAlert(
"five-hour",
low with { ResetsAt = now.AddHours(2) }),
"A new reset cycle was suppressed.");
Check(
!new AlertStateStore(path).ShouldAlert(
"weekly",
new LimitReading(LimitState.Available, 21, now.AddDays(1))),
"An alert above the threshold was emitted.");
}
finally
{
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
}
}
/// <summary>
/// Verifies reversible per-user startup registration with an isolated registry value.
/// </summary>
private static void TestStartupRegistration()
{
string valueName = $"CodexUsageTray.SelfTest.{Guid.NewGuid():N}";
StartupRegistration registration = new(valueName);
try
{
registration.SetEnabled(false);
Check(!registration.IsEnabled(), "Startup registration began enabled.");
registration.SetEnabled(true);
Check(registration.IsEnabled(), "Startup registration was not enabled.");
registration.SetEnabled(false);
Check(!registration.IsEnabled(), "Startup registration was not disabled.");
}
finally
{
registration.SetEnabled(false);
}
}
/// <summary>
/// Verifies that a second named mutex detects an existing application instance.
/// </summary>
private static void TestDuplicateMutex()
{
string name = $"Local\\CodexUsageTray.SelfTest.{Guid.NewGuid():N}";
using Mutex first = new(true, name, out bool firstCreated);
using Mutex second = new(true, name, out bool secondCreated);
Check(firstCreated && !secondCreated, "The duplicate-instance mutex was not detected.");
first.ReleaseMutex();
}
/// <summary>
/// Throws when a self-test condition is false.
/// </summary>
/// <param name="condition">The condition under test.</param>
/// <param name="message">The failure message.</param>
private static void Check(bool condition, string message)
{
if (!condition)
{
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Verifies that an action throws the requested exception type.
/// </summary>
/// <typeparam name="TException">The expected exception type.</typeparam>
/// <param name="action">The action under test.</param>
/// <param name="message">The failure message.</param>
private static void ExpectThrows<TException>(Action action, string message)
where TException : Exception
{
try
{
action();
}
catch (TException)
{
return;
}
throw new InvalidOperationException(message);
}
/// <summary>
/// Verifies that an asynchronous action throws the requested exception type.
/// </summary>
/// <typeparam name="TException">The expected exception type.</typeparam>
/// <param name="action">The asynchronous action under test.</param>
/// <param name="message">The failure message.</param>
private static async Task ExpectThrowsAsync<TException>(Func<Task> action, string message)
where TException : Exception
{
try
{
await action().ConfigureAwait(false);
}
catch (TException)
{
return;
}
throw new InvalidOperationException(message);
}
private sealed class BlockingTextReader : TextReader
{
/// <summary>
/// Waits indefinitely until the supplied cancellation token is canceled.
/// </summary>
/// <param name="cancellationToken">The cancellation token under test.</param>
/// <returns>No line; this operation completes only through cancellation.</returns>
public override async ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken)
{
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false);
return null;
}
}
}