-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinternal_test.go
More file actions
162 lines (144 loc) · 4.88 KB
/
internal_test.go
File metadata and controls
162 lines (144 loc) · 4.88 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
package colony
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
// TestRateLimitDelayAllBranches exercises every branch of rateLimitDelay
// synchronously — faster than reaching them via the iterator path.
func TestRateLimitDelayAllBranches(t *testing.T) {
// 1. Not a RateLimitError.
if got := rateLimitDelay(errors.New("not a rle")); got != 0 {
t.Errorf("non-RLE should yield 0, got %v", got)
}
// 2. RateLimitError with RetryAfter > 0.
rle := &RateLimitError{RetryAfter: 5}
if got := rateLimitDelay(rle); got != 5*time.Second {
t.Errorf("RLE with RetryAfter=5 should yield 5s, got %v", got)
}
// 3. RateLimitError with RetryAfter = 0 (default-delay branch).
rleZero := &RateLimitError{}
if got := rateLimitDelay(rleZero); got != 2*time.Second {
t.Errorf("RLE with RetryAfter=0 should yield 2s default, got %v", got)
}
}
// TestTokenCacheLifecycle covers getCachedToken's three paths: miss, expired
// (auto-evicted), and hit.
func TestTokenCacheLifecycle(t *testing.T) {
key := "col_cache_test"
baseURL := "https://cache.example"
defer clearCachedToken(key, baseURL)
// Miss: nothing stored yet.
if _, ok := getCachedToken(key, baseURL); ok {
t.Error("expected miss before store")
}
// Store, then hit.
setCachedToken(key, baseURL, "jwt-one")
tok, ok := getCachedToken(key, baseURL)
if !ok || tok != "jwt-one" {
t.Errorf("expected hit with jwt-one, got ok=%v tok=%q", ok, tok)
}
// Expired entry: manually overwrite with a past-expiry entry.
globalTokenCache.Store(tokenCacheKey(key, baseURL), &tokenEntry{
token: "jwt-stale",
expiry: time.Now().Add(-1 * time.Second),
})
if _, ok := getCachedToken(key, baseURL); ok {
t.Error("expected miss after expiry")
}
// Evicted: subsequent load should be a miss too.
if _, hit := globalTokenCache.Load(tokenCacheKey(key, baseURL)); hit {
t.Error("expected key evicted from sync.Map after expiry miss")
}
}
// TestSharedTokenCacheBetweenClients covers the "instance cache miss, global
// cache hit" path in ensureToken — two clients with the same credentials
// should share the cached JWT.
func TestSharedTokenCacheBetweenClients(t *testing.T) {
var tokenCalls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/auth/token" && r.Method == http.MethodPost {
tokenCalls.Add(1)
_ = json.NewEncoder(w).Encode(map[string]string{"access_token": "shared-jwt"})
return
}
if r.URL.Path == "/users/me" {
_ = json.NewEncoder(w).Encode(map[string]any{
"id": "me", "username": "me", "user_type": "agent",
"created_at": "2026-01-01T00:00:00Z",
})
return
}
http.NotFound(w, r)
}))
t.Cleanup(srv.Close)
key := "col_shared_" + t.Name()
defer clearCachedToken(key, srv.URL)
c1 := NewClient(key,
WithBaseURL(srv.URL),
WithRetry(RetryConfig{MaxRetries: 0, RetryOn: map[int]bool{}}),
)
if _, err := c1.GetMe(context.Background()); err != nil {
t.Fatal(err)
}
c2 := NewClient(key,
WithBaseURL(srv.URL),
WithRetry(RetryConfig{MaxRetries: 0, RetryOn: map[int]bool{}}),
)
if _, err := c2.GetMe(context.Background()); err != nil {
t.Fatal(err)
}
if got := tokenCalls.Load(); got != 1 {
t.Errorf("expected a single /auth/token call (shared cache), got %d", got)
}
}
// TestExtractErrorEmptyMap covers extractError with a body that has none of
// the recognised keys.
func TestExtractErrorEmptyMap(t *testing.T) {
code, msg := extractError(map[string]any{"unrecognised": "value"})
if code != "" || msg != "" {
t.Errorf("expected empty code+msg, got code=%q msg=%q", code, msg)
}
}
// TestNewAPIErrorDefaultBranch covers the status-code fallthrough in
// newAPIError (e.g. a 3xx status that doesn't match any typed branch).
func TestNewAPIErrorDefaultBranch(t *testing.T) {
err := newAPIError(302, "", "redirect", nil, nil)
base, ok := err.(*APIError)
if !ok {
t.Fatalf("expected plain *APIError for 302, got %T", err)
}
if base.Status != 302 {
t.Errorf("expected Status=302, got %d", base.Status)
}
}
// TestNewAPIErrorNetworkBranch covers the status-0 NetworkError path
// synchronously.
func TestNewAPIErrorNetworkBranch(t *testing.T) {
err := newAPIError(0, "", "dial failed", nil, errors.New("underlying"))
var ne *NetworkError
if !errors.As(err, &ne) {
t.Fatalf("expected *NetworkError for status=0, got %T", err)
}
if ne.Message != "dial failed" {
t.Errorf("expected message preserved, got %q", ne.Message)
}
}
// TestRetryConfigDelayCapsAtMax covers the cap branch of retry.delay().
func TestRetryConfigDelayCapsAtMax(t *testing.T) {
rc := RetryConfig{
MaxRetries: 10,
BaseDelay: 100 * time.Millisecond,
MaxDelay: 300 * time.Millisecond,
RetryOn: map[int]bool{500: true},
}
// Attempt 10 would normally produce 100ms * 2^10 = ~102s; capped at 300ms.
if d := rc.delay(10); d > 300*time.Millisecond {
t.Errorf("expected delay capped at 300ms, got %v", d)
}
}