Files
nofx/provider/nofxos/ai500_cache_test.go
tinkle-community 2c6e2827e8 feat(agent): surface the AI500 index board in chat, tools, and sidebar
- provider/nofxos: GetAI500ListCached — 5min TTL cache with stale
  fallback on upstream failure; ResolveClient routes through the claw402
  gateway when a wallet key is configured (user's claw402 model key ->
  CLAW402_WALLET_KEY env -> direct nofxos)
- new GET /api/ai500 endpoint serving the score-sorted board
- new get_ai500_list agent tool + prompt rule: when the user wants coin
  picks or creates a strategy without naming coins, consult AI500's
  high-scoring entries by default
- web: AI500 sidebar panel (rank, score badge, gain since entry,
  5min auto-refresh); clicking an entry asks the agent to analyze it
2026-06-11 22:11:03 +08:00

87 lines
2.2 KiB
Go

package nofxos
import (
"errors"
"testing"
"time"
)
func withStubbedAI500Fetch(t *testing.T, fn func(c *Client) ([]CoinData, error)) {
t.Helper()
original := fetchAI500ListFn
fetchAI500ListFn = fn
ai500Cache.mu.Lock()
ai500Cache.coins = nil
ai500Cache.fetchedAt = time.Time{}
ai500Cache.mu.Unlock()
t.Cleanup(func() {
fetchAI500ListFn = original
ai500Cache.mu.Lock()
ai500Cache.coins = nil
ai500Cache.fetchedAt = time.Time{}
ai500Cache.mu.Unlock()
})
}
func TestGetAI500ListCachedWithinTTL(t *testing.T) {
calls := 0
withStubbedAI500Fetch(t, func(c *Client) ([]CoinData, error) {
calls++
return []CoinData{{Pair: "BTCUSDT", Score: 95.5}}, nil
})
client := NewClient("", "")
first, err := GetAI500ListCached(client)
if err != nil {
t.Fatalf("first call: %v", err)
}
second, err := GetAI500ListCached(client)
if err != nil {
t.Fatalf("second call: %v", err)
}
if calls != 1 {
t.Fatalf("fetch calls = %d, want 1 (second call must hit cache)", calls)
}
if len(first) != 1 || len(second) != 1 || second[0].Pair != "BTCUSDT" {
t.Fatalf("unexpected results: first=%v second=%v", first, second)
}
}
func TestGetAI500ListCachedServesStaleOnError(t *testing.T) {
calls := 0
withStubbedAI500Fetch(t, func(c *Client) ([]CoinData, error) {
calls++
if calls == 1 {
return []CoinData{{Pair: "ETHUSDT", Score: 88}}, nil
}
return nil, errors.New("API returned status 429")
})
client := NewClient("", "")
if _, err := GetAI500ListCached(client); err != nil {
t.Fatalf("first call: %v", err)
}
ai500Cache.mu.Lock()
ai500Cache.fetchedAt = time.Now().Add(-2 * ai500CacheTTL)
ai500Cache.mu.Unlock()
coins, err := GetAI500ListCached(client)
if err != nil {
t.Fatalf("expected stale data instead of error, got: %v", err)
}
if len(coins) != 1 || coins[0].Pair != "ETHUSDT" {
t.Fatalf("expected stale ETH entry, got %v", coins)
}
}
func TestGetAI500ListCachedErrorsWithoutCache(t *testing.T) {
withStubbedAI500Fetch(t, func(c *Client) ([]CoinData, error) {
return nil, errors.New("upstream down")
})
if _, err := GetAI500ListCached(NewClient("", "")); err == nil {
t.Fatal("expected error when upstream fails with empty cache")
}
}