Files
magpie/internal/fx/fx_test.go
T
yetone 0fc3455e2a providers: a key's typed balance may be in yuan and refill each month or week
tenacious_eagle_96548 asked, after v0.1.3281's typed balance, to type it
in RMB and to have it refill (e.g. $10 a month, on the 1st).

- A balance may be typed in yuan ("¥100", "100元", or a bare number while
  Settings shows costs in CNY). What magpie counts spent stays in USD and
  is turned into yuan at fx.Known(): the rate internal/fx last fetched
  (cached 12h, fetched again in the background, never on a request).
  fx.Known never returns fx.Fallback, so with no rate fetched and
  something spent, what is left is unknown (left null; the card says
  why), not a guess.
- An optional refill: monthly on day 1-31 (past a month's end, its last
  day) or weekly on a weekday, at midnight in the user's local time.
  Nothing is stored on a refill: the spend counts from the last boundary
  after the balance was typed. Typing the amount again keeps the refill.
- GUI: the pill's menu gains Refills each month… (a day, in place),
  Refills each week… (the app's menu of weekdays) and Never refills;
  provider/keybalancerefill; keyownbalance takes currency cny. CLI:
  magpie provider key-balance <id> <key> [usd|¥cny|off]
  [--refill monthly[:day]|weekly[:mon…sun]|off]. Strings in zh, zh-TW,
  ja, de. docs/subsystems/providers-accounts.md updated.

Run on mote at this tree (base origin/main 350599a0f):
- go test -tags nogui -count=1 -timeout 45m ./internal/fx ./internal/provider
  ./internal/cli ./internal/gui ./internal/usage: all ok (suite lock).
- GOOS=linux go vet -tags nogui ./... ok; GOOS=windows go vet ./... ok;
  gofmt -l clean.
- key-own-balance.test.cjs 20/20 (chromium + webkit, en zh zh-TW ja de,
  900 and 400px): yuan typed posts currency cny, monthly day (40
  refused), weekly Friday, never. i18n-keys, i18n-en-no-cjk, old-webkit ok.
- Broken by hand, each red: Known returning Fallback
  (TestKnownIsNeverAGuess); refill days taken in UTC
  (TestTypedBalanceRefills, TestRefillDays); refill dropped on retype
  (TestTypedBalanceRefills).
- Full GUI suite still running at push: 3502 ok, 6 red so far, none in a
  file this touches: webkit By weight; webkit de 1100/420 Codex resets
  used by themselves; chromium en named caller keys; chromium zh-TW 420
  a key's several limits; webkit en gateway key held to its models.
  They are run on origin/main next and filed if red there.

Not tried: a live rate fetch (tests stay offline), the real app window,
WebKitGTK.

Reported-by: tenacious_eagle_96548 (Discord)
2026-11-08 09:03:00 +08:00

219 lines
6.2 KiB
Go

package fx
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
)
func TestGetFetchesAndCaches(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
Reset()
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"result":"success","rates":{"USD":1,"CNY":7.25,"EUR":0.9}}`))
}))
defer server.Close()
old := rateURL
rateURL = server.URL
defer func() { rateURL = old }()
r := Get(context.Background())
if r.CNYPerUSD != 7.25 {
t.Fatalf("rate = %v, want 7.25", r.CNYPerUSD)
}
if r.At.IsZero() || r.Stale() {
t.Fatalf("a rate just fetched should be fresh, not %+v", r)
}
if calls != 1 {
t.Fatalf("fetched %d times", calls)
}
if _, err := os.Stat(CachePath()); err != nil {
t.Fatalf("no cache file written: %v", err)
}
// a second Get, still fresh: the in-memory copy answers, the server
// isn't asked again
if r2 := Get(context.Background()); r2.CNYPerUSD != 7.25 {
t.Fatalf("second rate = %v", r2.CNYPerUSD)
}
if calls != 1 {
t.Fatalf("fetched %d times, want 1 (in-memory cache should have answered)", calls)
}
// forgetting the in-memory copy but keeping the cache file: still no
// network, the file answers
Reset()
if r3 := Get(context.Background()); r3.CNYPerUSD != 7.25 {
t.Fatalf("rate from cache file = %v", r3.CNYPerUSD)
}
if calls != 1 {
t.Fatalf("fetched %d times after Reset, want 1 (the cache file should have answered)", calls)
}
}
func TestGetFallsBackToStaleCacheWhenOffline(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
Reset()
// a cache file from well over TTL ago
old := Rate{CNYPerUSD: 6.9, At: time.Now().Add(-48 * time.Hour)}
writeCache(CachePath(), old)
badURL := rateURL
rateURL = "http://127.0.0.1:1/no-such-server"
defer func() { rateURL = badURL }()
r := Get(context.Background())
if r.CNYPerUSD != 6.9 {
t.Fatalf("rate = %v, want the stale cached 6.9", r.CNYPerUSD)
}
if !r.Stale() {
t.Fatal("a rate 48h old should read as stale")
}
}
func TestGetFallsBackToFixedDefaultWithNoCacheAndOffline(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
Reset()
badURL := rateURL
rateURL = "http://127.0.0.1:1/no-such-server"
defer func() { rateURL = badURL }()
r := Get(context.Background())
if r.CNYPerUSD != Fallback {
t.Fatalf("rate = %v, want the fixed Fallback %v", r.CNYPerUSD, Fallback)
}
if !r.At.IsZero() || !r.Stale() {
t.Fatalf("the fixed default should carry no time and read as stale: %+v", r)
}
}
func TestGetRefetchesOnceCacheIsStale(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CACHE_HOME", dir)
Reset()
// a stale cache file on disk already
stalePath := filepath.Join(dir, "magpie", "fxrate.json")
if err := os.MkdirAll(filepath.Dir(stalePath), 0o755); err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(Rate{CNYPerUSD: 6.5, At: time.Now().Add(-13 * time.Hour)})
if err := os.WriteFile(stalePath, b, 0o644); err != nil {
t.Fatal(err)
}
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
w.Write([]byte(`{"result":"success","rates":{"CNY":7.4}}`))
}))
defer server.Close()
old := rateURL
rateURL = server.URL
defer func() { rateURL = old }()
r := Get(context.Background())
if r.CNYPerUSD != 7.4 {
t.Fatalf("rate = %v, want the freshly fetched 7.4", r.CNYPerUSD)
}
if calls != 1 {
t.Fatalf("fetched %d times, want 1", calls)
}
}
func TestGetIgnoresAReplyWithNoCNYRate(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
Reset()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"result":"success","rates":{"EUR":0.9}}`))
}))
defer server.Close()
old := rateURL
rateURL = server.URL
defer func() { rateURL = old }()
r := Get(context.Background())
if r.CNYPerUSD != Fallback {
t.Fatalf("rate = %v, want Fallback %v when the reply has no CNY", r.CNYPerUSD, Fallback)
}
}
func TestGetDoesNotRetryAFailedFetchAtOnce(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
Reset()
writeCache(CachePath(), Rate{CNYPerUSD: 6.9, At: time.Now().Add(-48 * time.Hour)})
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
w.WriteHeader(http.StatusBadGateway)
}))
defer server.Close()
old := rateURL
rateURL = server.URL
defer func() { rateURL = old }()
// offline, each state() asks: the stale rate comes back without the
// network being tried again until retryAfter has passed
for i := 0; i < 3; i++ {
if r := Get(context.Background()); r.CNYPerUSD != 6.9 {
t.Fatalf("rate = %v, want the stale 6.9", r.CNYPerUSD)
}
}
if calls != 1 {
t.Fatalf("fetched %d times, want 1", calls)
}
mu.Lock()
failed = time.Now().Add(-retryAfter - time.Second)
mu.Unlock()
Get(context.Background())
if calls != 2 {
t.Fatalf("fetched %d times after retryAfter, want 2", calls)
}
}
// Known never hands out Fallback: with no rate ever learned (no cache,
// the fetch refused) it says so, and a failed fetch leaves it unknown,
// never 0, 1 or the guess. A rate learned before, however old, is known,
// and a fresh one asked for behind it.
func TestKnownIsNeverAGuess(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
Reset()
t.Cleanup(Reset)
refused := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusBadGateway)
}))
defer refused.Close()
defer SetRateURL(refused.URL)()
if r, ok := Known(); ok || r.CNYPerUSD != 0 {
t.Fatalf("no rate ever learned: %+v %v, want unknown", r, ok)
}
Settle()
if r, ok := Known(); ok || r.CNYPerUSD != 0 {
t.Fatalf("after a failed fetch: %+v %v, want unknown", r, ok)
}
if r := Soon(); r.CNYPerUSD != Fallback {
t.Fatalf("Soon still shows the guess, got %+v", r)
}
Settle()
// a stale rate in the cache is known, as it was learned
Reset()
old := Rate{CNYPerUSD: 7.1, At: time.Now().Add(-3 * TTL)}
writeCache(CachePath(), old)
if r, ok := Known(); !ok || r.CNYPerUSD != 7.1 {
t.Fatalf("a stale rate learned before: %+v %v", r, ok)
}
Settle()
if r, ok := Known(); !ok || r.CNYPerUSD != 7.1 {
t.Fatalf("a failed refresh changed the known rate: %+v %v", r, ok)
}
}