Files
magpie/internal/provider/key_spend_test.go
T
yetone 5241308212 settings: a day can start at 0 to 6 o'clock (ssharpcc on X)
Settings > Usage > "Day starts at" (dayStart, 0 to 6, default 0; also
magpie settings set dayStart 4). With 4, a call at 01:30 counts toward the
day before: the Usage page (summary, charts, heatmap, ledger day filter,
hour labels of Today) and the daily and monthly key caps (access.Window,
provider.SpendCap.Window).

internal/dayzone makes a time.Location whose midnight is the real day's
hour:00 (TZif built from the zone's own offsets, same DST instants), so
every place that cuts days by a Zone's midnight follows without edits;
usage.Zone returns it and the "now" reads use it too.

Run (mote): go test usage, settings, settingsapi, access, provider, gui,
dayzone, also with TZ=UTC and TZ=Pacific/Kiritimati; gofmt; go vet darwin,
linux nogui and windows; day-start, currency, number-units and i18n-keys
GUI files in chromium and webkit, en zh zh-TW ja de; TestCoreScriptBudget.
Broken by hand: TestDayStartsAfterMidnight red with 9 failures when the
hour is ignored. New tests: dayzone over 5 zones x hours 1/4/6 x two years
of days, usage, limit window, spend-cap window, day-start GUI.
Not tried: a real log history in a real window.
Not shifted, filed as #6314: the Sessions page, TUI sessions filter,
davsync shared per-day files, gateway_sessions day keys, credits_daily.
Rows are never stored in the shifted zone.
2026-11-12 18:31:50 +08:00

165 lines
6.3 KiB
Go

package provider
import (
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// A key's spend cap (sparkling_lemur_62868 on Discord) is set by the key's
// id or name, kept by its fingerprint in lower case, and taken off with
// nil. A cap in all counts from when it was set, and keeps that start
// while it stays one in all, its amount changed; a cap a day or a month
// keeps none. A key the provider hasn't and a cap out of range are
// refused, and a key's value replaced keeps its cap.
func TestKeySpendCapSet(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: "https://relay.test/v1", Key: "sk-first", KeyName: "Team",
Keys: []KeyAccount{{Name: "Spare", Key: "sk-spare"}}}); err != nil {
t.Fatal(err)
}
first, spare := keyID("sk-first"), keyID("sk-spare")
capOf := func(ref string) (SpendCap, bool) {
t.Helper()
p, err := Find("relay")
if err != nil {
t.Fatal(err)
}
return p.KeySpendCap(ref)
}
if err := SetKeySpendCap("relay", "Team", &SpendCap{USD: 20, Period: SpendDay}); err != nil {
t.Fatal(err)
}
if c, ok := capOf(strings.ToUpper(first)); !ok || c.USD != 20 || c.Period != SpendDay || !c.Since.IsZero() {
t.Fatalf("Team's cap %+v %v", c, ok)
}
if _, ok := capOf(spare); ok {
t.Fatal("Spare got a cap it wasn't given")
}
before := time.Now().UTC().Truncate(time.Second)
if err := SetKeySpendCap("relay", spare, &SpendCap{USD: 100, Period: SpendTotal}); err != nil {
t.Fatal(err)
}
c, ok := capOf(spare)
if !ok || c.Period != SpendTotal || c.Since.Before(before) || c.Since.After(time.Now()) {
t.Fatalf("Spare's cap in all %+v %v", c, ok)
}
// set in all a while back, raised: it still counts from then
p, _ := Find("relay")
since := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
p.KeySpendCaps[spare] = SpendCap{USD: 100, Period: SpendTotal, Since: since}
if err := Save(*p); err != nil {
t.Fatal(err)
}
if err := SetKeySpendCap("relay", "Spare", &SpendCap{USD: 150, Period: SpendTotal}); err != nil {
t.Fatal(err)
}
if c, _ := capOf(spare); c.USD != 150 || !c.Since.Equal(since) {
t.Fatalf("raised in all, it counts from %v, not %v: %+v", c.Since, since, c)
}
// a month: no start of its own; in all again counts from now
if err := SetKeySpendCap("relay", spare, &SpendCap{USD: 150, Period: SpendMonth}); err != nil {
t.Fatal(err)
}
if c, _ := capOf(spare); c.Period != SpendMonth || !c.Since.IsZero() {
t.Fatalf("a month's cap %+v", c)
}
for _, bad := range []SpendCap{{USD: 0, Period: SpendDay}, {USD: -1, Period: SpendDay}, {USD: MaxSpendCap + 1, Period: SpendDay}, {USD: 5, Period: "week"}} {
if err := SetKeySpendCap("relay", spare, &bad); err == nil {
t.Fatalf("%+v was taken", bad)
}
}
if err := SetKeySpendCap("relay", "nobody", &SpendCap{USD: 1, Period: SpendDay}); err == nil {
t.Fatal("a key the provider hasn't got a cap")
}
// the value replaced, the cap goes with the key
if _, _, err := ReplaceKey("relay", first, "sk-first-2"); err != nil {
t.Fatal(err)
}
if c, ok := capOf(keyID("sk-first-2")); !ok || c.USD != 20 {
t.Fatalf("replaced, Team's cap %+v %v", c, ok)
}
if err := SetKeySpendCap("relay", "Team", nil); err != nil {
t.Fatal(err)
}
if _, ok := capOf(keyID("sk-first-2")); ok {
t.Fatal("the cap taken off is still there")
}
}
// A day's cap counts from local midnight to the next, a month's from the
// 1st to the next month's, and one in all from its Since, never renewing.
func TestSpendCapWindow(t *testing.T) {
loc := time.FixedZone("far", 13*3600)
now := time.Date(2026, 12, 31, 23, 30, 0, 0, loc)
s, r := SpendCap{USD: 1, Period: SpendDay}.Window(now)
if !s.Equal(time.Date(2026, 12, 31, 0, 0, 0, 0, loc)) || !r.Equal(time.Date(2027, 1, 1, 0, 0, 0, 0, loc)) {
t.Fatalf("day %v %v", s, r)
}
s, r = SpendCap{USD: 1, Period: SpendMonth}.Window(now)
if !s.Equal(time.Date(2026, 12, 1, 0, 0, 0, 0, loc)) || !r.Equal(time.Date(2027, 1, 1, 0, 0, 0, 0, loc)) {
t.Fatalf("month %v %v", s, r)
}
since := time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC)
s, r = SpendCap{USD: 1, Period: SpendTotal, Since: since}.Window(now)
if !s.Equal(since) || !r.IsZero() {
t.Fatalf("in all %v %v", s, r)
}
}
// The CLI's words for a cap: an amount, $ or not, a period by any of its
// names, a day when none; off for none; anything else refused.
func TestParseSpendCap(t *testing.T) {
for _, c := range []struct {
amount, period string
want *SpendCap
}{
{"20", "", &SpendCap{USD: 20, Period: SpendDay}},
{"$12.5", "monthly", &SpendCap{USD: 12.5, Period: SpendMonth}},
{"100", "total", &SpendCap{USD: 100, Period: SpendTotal}},
{"100", "all", &SpendCap{USD: 100, Period: SpendTotal}},
{"off", "", nil},
} {
got, err := ParseSpendCap(c.amount, c.period)
if err != nil || (got == nil) != (c.want == nil) || got != nil && *got != *c.want {
t.Fatalf("%q %q: %+v %v", c.amount, c.period, got, err)
}
}
for _, bad := range [][2]string{{"--help", ""}, {"twenty", ""}, {"0", ""}, {"-5", ""}, {"5", "week"}, {"NaN", ""}, {"2000000", ""}} {
if _, err := ParseSpendCap(bad[0], bad[1]); err == nil {
t.Fatalf("%q %q was taken", bad[0], bad[1])
}
}
}
// A day that starts at 4 moves a spend cap's day and month: at 02:00 on the
// 15th the cap's day began at 04:00 on the 14th.
func TestSpendCapWindowFollowsTheDayStart(t *testing.T) {
t.Cleanup(func() { s := settings.Load(); s.DayStart = 0; settings.Save(s) })
loc := time.FixedZone("X", 8*3600)
at := func(m time.Month, d, h int) time.Time { return time.Date(2026, m, d, h, 0, 0, 0, loc) }
for hour, want := range map[int][2]time.Time{0: {at(9, 15, 0), at(9, 16, 0)}, 4: {at(9, 14, 4), at(9, 15, 4)}} {
s := settings.Load()
s.DayStart = hour
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
from, to := SpendCap{USD: 1, Period: SpendDay}.Window(at(9, 15, 2))
if !from.Equal(want[0]) || !to.Equal(want[1]) || from.Location() != loc {
t.Errorf("start %d: day window %v..%v, want %v..%v", hour, from, to, want[0], want[1])
}
}
st := settings.Load()
st.DayStart = 4
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
from, to := SpendCap{USD: 1, Period: SpendMonth}.Window(at(10, 1, 2))
if !from.Equal(at(9, 1, 4)) || !to.Equal(at(10, 1, 4)) {
t.Errorf("month window %v..%v, want September from 04:00", from, to)
}
}