Repository navigation
Expand file tree
/
Copy pathwrite_test.go
More file actions
444 lines (414 loc) · 15.7 KB
/
Copy pathwrite_test.go
File metadata and controls
444 lines (414 loc) · 15.7 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
package codeatlas_test
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
codeatlas "github.com/codeatlasdev/codeatlas-sdk-go"
)
// fakeAPI follows the wire contract of POST /oauth2/register,
// POST /oauth2/token and the /api/v1 write endpoints.
type fakeAPI struct {
srv *httptest.Server
mu sync.Mutex
calls []call
tokens int
polls int
}
type call struct {
method, path string
header http.Header
body string
}
func newFakeAPI(t *testing.T) *fakeAPI {
t.Helper()
f := &fakeAPI{}
f.srv = httptest.NewServer(http.HandlerFunc(f.handle))
t.Cleanup(f.srv.Close)
return f
}
func (f *fakeAPI) client(opts ...codeatlas.Option) *codeatlas.Client {
base := []codeatlas.Option{
codeatlas.WithOrigin(f.srv.URL),
codeatlas.WithBaseURL(f.srv.URL + "/api/v1"),
codeatlas.WithCredentials("ca_1", "cas_1"),
}
return codeatlas.New(append(base, opts...)...)
}
func (f *fakeAPI) callsTo(path string) []call {
f.mu.Lock()
defer f.mu.Unlock()
var out []call
for _, c := range f.calls {
if c.path == path {
out = append(out, c)
}
}
return out
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func apiErr(code, message, hint string) map[string]any {
return map[string]any{"error": map[string]string{"code": code, "message": message, "hint": hint}}
}
func (f *fakeAPI) handle(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
body := string(raw)
f.mu.Lock()
f.calls = append(f.calls, call{r.Method, r.URL.Path, r.Header.Clone(), body})
f.mu.Unlock()
bearer := strings.HasPrefix(r.Header.Get("Authorization"), "Bearer tok")
switch r.URL.Path {
case "/oauth2/register":
var in struct {
ClientName string `json:"client_name"`
GrantTypes []string `json:"grant_types"`
}
_ = json.Unmarshal(raw, &in)
if in.ClientName == "" {
writeJSON(w, 400, map[string]string{"error": "invalid_client_metadata", "error_description": "client_name is required"})
return
}
writeJSON(w, 201, map[string]string{"client_id": "ca_1", "client_secret": "cas_1", "client_name": in.ClientName})
case "/oauth2/token":
form, _ := url.ParseQuery(body)
user, pass, ok := r.BasicAuth()
if !ok || user != "ca_1" || pass != "cas_1" || form.Get("grant_type") != "client_credentials" ||
r.Header.Get("Content-Type") != "application/x-www-form-urlencoded" {
writeJSON(w, 401, map[string]string{"error": "invalid_client", "error_description": "bad secret"})
return
}
f.mu.Lock()
f.tokens++
n := f.tokens
f.mu.Unlock()
writeJSON(w, 200, map[string]any{"access_token": "tok" + string(rune('0'+n)), "expires_in": 3600, "scope": "api:write", "token_type": "Bearer"})
case "/api/v1/contact-requests":
if !bearer {
writeJSON(w, 401, apiErr("unauthorized", "no token", "send Bearer"))
return
}
var in map[string]string
_ = json.Unmarshal(raw, &in)
if in["email"] == "" {
writeJSON(w, 400, apiErr("bad_request", "email", "Use a valid email."))
return
}
w.Header().Set("RateLimit-Policy", `"contact";q=5;w=3600`)
w.Header().Set("RateLimit", `"contact";r=4;t=3599`)
writeJSON(w, 201, map[string]any{"data": map[string]any{"id": "cr_1", "status": "received", "delivery": "stored", "created_at": "2026-01-01T00:00:00Z"}})
case "/api/v1/services/batch":
var in struct {
Slugs []string `json:"slugs"`
}
_ = json.Unmarshal(raw, &in)
results := []map[string]any{}
for _, s := range in.Slugs {
if s == "known" {
results = append(results, map[string]any{"slug": s, "status": 200, "data": map[string]any{"slug": s, "name": "Known"}})
} else {
results = append(results, map[string]any{"slug": s, "status": 404, "error": map[string]string{"code": "not_found", "message": "no", "hint": "list"}})
}
}
writeJSON(w, 200, map[string]any{"count": len(results), "results": results})
case "/api/v1/exports":
if !bearer {
writeJSON(w, 401, apiErr("unauthorized", "no", "x"))
return
}
var in struct {
Format string `json:"format"`
}
_ = json.Unmarshal(raw, &in)
writeJSON(w, 202, map[string]any{"data": map[string]any{"id": "exp_1", "status": "queued", "format": in.Format, "download_url": nil, "created_at": "2026-01-01T00:00:00Z", "expires_at": "2026-01-02T00:00:00Z"}})
case "/api/v1/exports/exp_1":
f.mu.Lock()
f.polls++
status := "running"
if f.polls >= 3 {
status = "succeeded"
}
f.mu.Unlock()
var dl any
if status == "succeeded" {
dl = "https://x/d"
}
writeJSON(w, 200, map[string]any{"data": map[string]any{"id": "exp_1", "status": status, "format": "csv", "download_url": dl, "created_at": "2026-01-01T00:00:00Z", "expires_at": "2026-01-02T00:00:00Z"}})
case "/api/v1/exports/exp_1/download":
w.Header().Set("Content-Type", "text/csv")
_, _ = io.WriteString(w, "slug,name\r\nknown,Known\r\n")
case "/api/v1/services":
cursor := r.URL.Query().Get("cursor")
switch cursor {
case "":
writeJSON(w, 200, map[string]any{"count": 3, "next_cursor": "1", "data": []map[string]any{{"slug": "a"}}})
case "1":
writeJSON(w, 200, map[string]any{"count": 3, "next_cursor": "2", "data": []map[string]any{{"slug": "b"}}})
default:
writeJSON(w, 200, map[string]any{"count": 3, "next_cursor": nil, "data": []map[string]any{{"slug": "c"}}})
}
default:
writeJSON(w, 404, apiErr("not_found", "x", "y"))
}
}
func TestRegisterThenCreateContactRequestWithCachedToken(t *testing.T) {
f := newFakeAPI(t)
ctx := context.Background()
creds, err := codeatlas.Register(ctx, "my-agent", codeatlas.WithOrigin(f.srv.URL))
if err != nil {
t.Fatal(err)
}
if creds.ClientID != "ca_1" || creds.ClientSecret != "cas_1" || creds.ClientName != "my-agent" {
t.Fatalf("unexpected creds: %+v", creds)
}
reg := f.callsTo("/oauth2/register")[0]
if !strings.Contains(reg.body, `"client_credentials"`) {
t.Fatalf("register body missing grant type: %s", reg.body)
}
c := f.client(codeatlas.WithCredentials(creds.ClientID, creds.ClientSecret))
in := codeatlas.ContactRequestInput{Name: "Ana Souza", Email: "ana@example.com", Message: "Preciso de um diagnóstico.", Locale: codeatlas.LocalePTBR}
got, err := c.ContactRequests.Create(ctx, in, codeatlas.WithIdempotencyKey("key-12345678"))
if err != nil {
t.Fatal(err)
}
if _, err := c.ContactRequests.Create(ctx, in); err != nil {
t.Fatal(err)
}
if got.ID != "cr_1" || got.Status != "received" || got.Delivery != "stored" || got.CreatedAt.Year() != 2026 {
t.Fatalf("unexpected receipt: %+v", got)
}
if n := len(f.callsTo("/oauth2/token")); n != 1 {
t.Fatalf("token fetched %d times, want 1 (cached)", n)
}
token := f.callsTo("/oauth2/token")[0]
form, _ := url.ParseQuery(token.body)
if form.Get("resource") != f.srv.URL+"/api/v1" {
t.Fatalf("resource = %q", form.Get("resource"))
}
posts := f.callsTo("/api/v1/contact-requests")
if posts[0].header.Get("Idempotency-Key") != "key-12345678" || posts[1].header.Get("Idempotency-Key") != "" {
t.Fatalf("idempotency headers wrong: %q / %q", posts[0].header.Get("Idempotency-Key"), posts[1].header.Get("Idempotency-Key"))
}
if posts[0].header.Get("Authorization") != "Bearer tok1" {
t.Fatalf("auth header = %q", posts[0].header.Get("Authorization"))
}
var sent map[string]any
_ = json.Unmarshal([]byte(posts[0].body), &sent)
if _, has := sent["company"]; has {
t.Fatalf("empty optional fields must be omitted: %s", posts[0].body)
}
if sent["locale"] != "pt-BR" {
t.Fatalf("locale = %v", sent["locale"])
}
if !strings.Contains(posts[0].header.Get("User-Agent"), "codeatlas-sdk-go/") {
t.Fatalf("user agent = %q", posts[0].header.Get("User-Agent"))
}
}
func TestRateLimitParsing(t *testing.T) {
f := newFakeAPI(t)
c := f.client()
if _, err := c.ContactRequests.Create(context.Background(), codeatlas.ContactRequestInput{Name: "Ana", Email: "a@b.co", Message: "mensagem longa ok"}); err != nil {
t.Fatal(err)
}
want := codeatlas.RateLimit{Policy: "contact", Limit: 5, Window: time.Hour, Remaining: 4, Reset: 3599 * time.Second}
if got := c.LastRateLimit(); got != want {
t.Fatalf("rate limit = %+v, want %+v", got, want)
}
}
func TestCreateWithoutCredentialsFailsBeforeAnyRequest(t *testing.T) {
f := newFakeAPI(t)
c := codeatlas.New(codeatlas.WithOrigin(f.srv.URL), codeatlas.WithBaseURL(f.srv.URL+"/api/v1"))
_, err := c.ContactRequests.Create(context.Background(), codeatlas.ContactRequestInput{Name: "Ana", Email: "a@b.co", Message: "mensagem longa ok"})
var e *codeatlas.APIError
if !errors.As(err, &e) || e.Code != codeatlas.CodeUnauthorized || e.Status != 401 {
t.Fatalf("want unauthorized APIError, got %v", err)
}
if len(f.calls) != 0 {
t.Fatalf("expected no network calls, got %d", len(f.calls))
}
}
func TestOAuthAndAPIErrorsBecomeAPIError(t *testing.T) {
f := newFakeAPI(t)
ctx := context.Background()
in := codeatlas.ContactRequestInput{Name: "Ana", Email: "", Message: "mensagem longa ok"}
bad := f.client(codeatlas.WithCredentials("ca_1", "wrong"))
_, err := bad.ContactRequests.Create(ctx, in)
var oauth *codeatlas.APIError
if !errors.As(err, &oauth) || oauth.Status != 401 || oauth.Code != "invalid_client" || oauth.Message != "bad secret" {
t.Fatalf("oauth error wrong: %v", err)
}
_, err = f.client().ContactRequests.Create(ctx, in)
var api *codeatlas.APIError
if !errors.As(err, &api) || api.Status != 400 || api.Code != codeatlas.CodeBadRequest || api.Hint != "Use a valid email." {
t.Fatalf("api error wrong: %v", err)
}
if !strings.Contains(api.Error(), "Use a valid email.") {
t.Fatalf("Error() should carry the hint: %q", api.Error())
}
}
func TestRegisterRejectsEmptyName(t *testing.T) {
f := newFakeAPI(t)
_, err := codeatlas.Register(context.Background(), "", codeatlas.WithOrigin(f.srv.URL))
var e *codeatlas.APIError
if !errors.As(err, &e) || e.Status != 400 || e.Code != "invalid_client_metadata" {
t.Fatalf("want invalid_client_metadata, got %v", err)
}
}
func TestRateLimitedErrorCarriesRetryAfter(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", "7")
w.Header().Set("RateLimit-Policy", `"read";q=120;w=60`)
w.Header().Set("RateLimit", `"read";r=0;t=7`)
writeJSON(w, 429, apiErr("rate_limited", "slow down", "wait"))
}))
defer srv.Close()
c := codeatlas.New(codeatlas.WithBaseURL(srv.URL))
_, err := c.Health(context.Background())
var e *codeatlas.APIError
if !errors.As(err, &e) || !codeatlas.IsRateLimited(err) {
t.Fatalf("want rate-limited APIError, got %v", err)
}
if e.RetryAfter != 7*time.Second || e.RateLimit.Remaining != 0 || e.RateLimit.Limit != 120 || e.RateLimit.Reset != 7*time.Second {
t.Fatalf("unexpected error details: %+v", e)
}
if c.LastRateLimit().Policy != "read" {
t.Fatalf("LastRateLimit not updated on error: %+v", c.LastRateLimit())
}
}
func TestNonJSONErrorBodyStillYieldsAPIError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "<html>bad gateway</html>", http.StatusBadGateway)
}))
defer srv.Close()
_, err := codeatlas.New(codeatlas.WithBaseURL(srv.URL)).Health(context.Background())
var e *codeatlas.APIError
if !errors.As(err, &e) || e.Status != 502 || e.Code != "unknown_error" {
t.Fatalf("want unknown_error 502, got %v", err)
}
}
func TestBatchReturnsPerItemResults(t *testing.T) {
f := newFakeAPI(t)
res, err := f.client().Services.Batch(context.Background(), []string{"known", "nope"})
if err != nil {
t.Fatal(err)
}
if len(res) != 2 || *res[0].Slug != "known" || res[0].Status != 200 || res[0].Data.Name != "Known" ||
res[1].Status != 404 || res[1].Error.Code != "not_found" {
t.Fatalf("unexpected results: %+v", res)
}
if len(f.callsTo("/oauth2/token")) != 0 {
t.Fatal("batch is public and must not fetch a token")
}
}
func TestAllFollowsCursorAndStopsEarly(t *testing.T) {
f := newFakeAPI(t)
c := f.client()
var slugs []string
for svc, err := range c.Services.All(context.Background(), nil) {
if err != nil {
t.Fatal(err)
}
slugs = append(slugs, svc.Slug)
}
if strings.Join(slugs, ",") != "a,b,c" {
t.Fatalf("slugs = %v", slugs)
}
before := len(f.callsTo("/api/v1/services"))
for range c.Services.All(context.Background(), nil) {
break
}
if got := len(f.callsTo("/api/v1/services")) - before; got != 1 {
t.Fatalf("breaking early fetched %d pages, want 1", got)
}
}
func TestExportCreateWaitDownload(t *testing.T) {
f := newFakeAPI(t)
c := f.client()
ctx := context.Background()
job, err := c.Exports.Create(ctx, codeatlas.ExportCSV, codeatlas.WithIdempotencyKey("exp-key-1234"))
if err != nil {
t.Fatal(err)
}
if job.Status != codeatlas.ExportQueued || job.Format != codeatlas.ExportCSV || job.DownloadURL != nil {
t.Fatalf("unexpected job: %+v", job)
}
if f.callsTo("/api/v1/exports")[0].header.Get("Idempotency-Key") != "exp-key-1234" {
t.Fatal("idempotency key not sent on export create")
}
done, err := c.Exports.Wait(ctx, job.ID, &codeatlas.WaitOptions{Interval: 5 * time.Millisecond})
if err != nil {
t.Fatal(err)
}
if done.Status != codeatlas.ExportSucceeded || done.DownloadURL == nil {
t.Fatalf("unexpected done job: %+v", done)
}
file, err := c.Exports.Download(ctx, job.ID)
if err != nil {
t.Fatal(err)
}
if string(file) != "slug,name\r\nknown,Known\r\n" {
t.Fatalf("file = %q", file)
}
if auth := f.callsTo("/api/v1/exports/exp_1/download")[0].header.Get("Authorization"); auth != "Bearer tok1" {
t.Fatalf("download auth = %q", auth)
}
}
func TestExportWaitTimesOut(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/oauth2/token" {
writeJSON(w, 200, map[string]any{"access_token": "tok", "expires_in": 3600})
return
}
writeJSON(w, 200, map[string]any{"data": map[string]any{"id": "exp_1", "status": "running", "format": "csv", "download_url": nil}})
}))
defer srv.Close()
c := codeatlas.New(codeatlas.WithOrigin(srv.URL), codeatlas.WithBaseURL(srv.URL+"/api/v1"), codeatlas.WithCredentials("a", "b"))
_, err := c.Exports.Wait(context.Background(), "exp_1", &codeatlas.WaitOptions{Interval: 5 * time.Millisecond, Timeout: 40 * time.Millisecond})
if err == nil || !strings.Contains(err.Error(), "still running") || !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("want timeout error, got %v", err)
}
}
func TestSandboxBaseURLIsUsedAsTokenResource(t *testing.T) {
var resource string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
if r.URL.Path == "/oauth2/token" {
form, _ := url.ParseQuery(string(raw))
resource = form.Get("resource")
writeJSON(w, 200, map[string]any{"access_token": "tok", "expires_in": 3600})
return
}
writeJSON(w, 201, map[string]any{"data": map[string]any{"id": "cr_s", "status": "received", "delivery": "sandbox", "created_at": "2026-01-01T00:00:00Z"}})
}))
defer srv.Close()
c := codeatlas.New(codeatlas.WithOrigin(srv.URL), codeatlas.WithBaseURL(codeatlas.SandboxBaseURL+"/"), codeatlas.WithCredentials("a", "b"),
codeatlas.WithHTTPClient(&http.Client{Transport: rewrite{srv.URL}}))
if c.BaseURL() != codeatlas.SandboxBaseURL {
t.Fatalf("BaseURL = %q", c.BaseURL())
}
got, err := c.ContactRequests.Create(context.Background(), codeatlas.ContactRequestInput{Name: "Ana", Email: "a@b.co", Message: "mensagem longa ok"})
if err != nil {
t.Fatal(err)
}
if got.Delivery != "sandbox" || resource != codeatlas.SandboxBaseURL {
t.Fatalf("delivery=%q resource=%q", got.Delivery, resource)
}
}
// rewrite sends every request to the test server, whatever the URL says.
type rewrite struct{ target string }
func (r rewrite) RoundTrip(req *http.Request) (*http.Response, error) {
u, _ := url.Parse(r.target)
req = req.Clone(req.Context())
req.URL.Scheme, req.URL.Host = u.Scheme, u.Host
return http.DefaultTransport.RoundTrip(req)
}