-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient_test.go
More file actions
505 lines (410 loc) · 13.5 KB
/
Copy pathclient_test.go
File metadata and controls
505 lines (410 loc) · 13.5 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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
package braintrust
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
"github.com/braintrustdata/braintrust-sdk-go/internal/auth"
intlogger "github.com/braintrustdata/braintrust-sdk-go/internal/logger"
"github.com/braintrustdata/braintrust-sdk-go/logger"
)
func TestNew_WithMinimalConfig(t *testing.T) {
t.Parallel()
// Create a TracerProvider
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
// Create client with minimal config
client, err := New(tp,
WithAPIKey(auth.TestAPIKey),
WithProject("test-project"),
WithLogger(intlogger.NewFailTestLogger(t)),
)
require.NoError(t, err)
require.NotNil(t, client)
// Test TracerProvider() accessor
assert.Equal(t, tp, client.TracerProvider())
// Test Tracer() method creates a working tracer
tracer := client.Tracer("test-tracer")
assert.NotNil(t, tracer)
// Create a span to verify tracer works
ctx, span := tracer.Start(context.Background(), "test-span")
span.End()
assert.NotNil(t, ctx)
// Test String() output contains expected info
str := client.String()
assert.Contains(t, str, "test-project")
assert.Contains(t, str, "Braintrust Client")
}
func TestNew_WithBlockingLogin(t *testing.T) {
t.Parallel()
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
// Create client with blocking login
client, err := New(tp,
WithAPIKey(auth.TestAPIKey),
WithProject("test-project"),
WithBlockingLogin(true),
WithLogger(intlogger.NewFailTestLogger(t)),
)
require.NoError(t, err)
require.NotNil(t, client)
// After blocking login, session info should be available
org := client.session.OrgInfo()
assert.Equal(t, "test-org-id", org.ID)
assert.Equal(t, "test-org-name", org.Name)
// String() should show org info
str := client.String()
assert.Contains(t, str, "test-org-name")
assert.Contains(t, str, "test-org-id")
}
func TestNew_InitializesWithoutImmediateAPIKey(t *testing.T) {
// Note: No t.Parallel() because we're setting environment variables
// Clear environment variable to ensure no API key is set
t.Setenv("BRAINTRUST_API_KEY", "")
dir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(dir, ".braintrust.json"), []byte(`{"BRAINTRUST_API_KEY":""}`), 0o600))
oldwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(dir))
t.Cleanup(func() {
require.NoError(t, os.Chdir(oldwd))
})
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
// Try to create client without API key
client, err := New(tp,
WithProject("test-project"),
WithLogger(logger.Discard()),
)
// The client can initialize because .braintrust.json discovery is lazy and
// runs outside the constructor path.
require.NoError(t, err)
require.NotNil(t, client)
}
func TestNew_BlockingLoginFailsWhenBraintrustJSONHasNoAPIKey(t *testing.T) {
// Note: No t.Parallel() because this test changes the process cwd.
t.Setenv("BRAINTRUST_API_KEY", "")
dir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(dir, ".braintrust.json"), []byte(`{"BRAINTRUST_API_KEY":""}`), 0o600))
oldwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(dir))
t.Cleanup(func() {
require.NoError(t, os.Chdir(oldwd))
})
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
client, err := New(tp,
WithProject("test-project"),
WithBlockingLogin(true),
WithLogger(logger.Discard()),
)
require.Error(t, err)
assert.Nil(t, client)
assert.Contains(t, err.Error(), "API key is required")
}
func TestNew_UsesBraintrustJSONFallbackForBlockingLogin(t *testing.T) {
// Note: No t.Parallel() because this test changes the process cwd.
t.Setenv("BRAINTRUST_API_KEY", "")
root := t.TempDir()
nested := filepath.Join(root, "nested", "project")
require.NoError(t, os.MkdirAll(nested, 0o755))
require.NoError(t, os.WriteFile(
filepath.Join(root, ".braintrust.json"),
[]byte(fmt.Sprintf(`{"BRAINTRUST_API_KEY":%q,"OTHER_SECRET":"ignored"}`, auth.TestAPIKey)),
0o600,
))
oldwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(nested))
t.Cleanup(func() {
require.NoError(t, os.Chdir(oldwd))
})
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
client, err := New(tp,
WithProject("test-project"),
WithBlockingLogin(true),
WithLogger(intlogger.NewFailTestLogger(t)),
)
require.NoError(t, err)
require.NotNil(t, client)
assert.Equal(t, "", os.Getenv("BRAINTRUST_API_KEY"))
org := client.session.OrgInfo()
assert.Equal(t, "test-org-id", org.ID)
assert.Equal(t, "test-org-name", org.Name)
assert.Equal(t, auth.TestAPIKey, client.session.APIInfo().APIKey)
}
func TestNew_APIKeyPrecedenceOverBraintrustJSON(t *testing.T) {
// Note: No t.Parallel() because this test changes the process cwd.
t.Setenv("BRAINTRUST_API_KEY", auth.TestAPIKey)
root := t.TempDir()
require.NoError(t, os.WriteFile(
filepath.Join(root, ".braintrust.json"),
[]byte(`{"BRAINTRUST_API_KEY":"file-key"}`),
0o600,
))
oldwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(root))
t.Cleanup(func() {
require.NoError(t, os.Chdir(oldwd))
})
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
client, err := New(tp,
WithProject("test-project"),
WithBlockingLogin(true),
WithLogger(intlogger.NewFailTestLogger(t)),
)
require.NoError(t, err)
require.NotNil(t, client)
assert.Equal(t, auth.TestAPIKey, client.session.APIInfo().APIKey)
}
func TestNew_ExplicitAPIKeyPrecedence(t *testing.T) {
// Note: No t.Parallel() because this test changes the process cwd.
t.Setenv("BRAINTRUST_API_KEY", "env-key")
root := t.TempDir()
require.NoError(t, os.WriteFile(
filepath.Join(root, ".braintrust.json"),
[]byte(`{"BRAINTRUST_API_KEY":"file-key"}`),
0o600,
))
oldwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(root))
t.Cleanup(func() {
require.NoError(t, os.Chdir(oldwd))
})
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
client, err := New(tp,
WithAPIKey(auth.TestAPIKey),
WithProject("test-project"),
WithBlockingLogin(true),
WithLogger(intlogger.NewFailTestLogger(t)),
)
require.NoError(t, err)
require.NotNil(t, client)
assert.Equal(t, auth.TestAPIKey, client.session.APIInfo().APIKey)
}
func TestNew_BlankExplicitAPIKeyPreservesEnvironmentFallback(t *testing.T) {
// Note: No t.Parallel() because this test changes the process cwd.
t.Setenv("BRAINTRUST_API_KEY", auth.TestAPIKey)
root := t.TempDir()
require.NoError(t, os.WriteFile(
filepath.Join(root, ".braintrust.json"),
[]byte(`{"BRAINTRUST_API_KEY":"file-key"}`),
0o600,
))
oldwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(root))
t.Cleanup(func() {
require.NoError(t, os.Chdir(oldwd))
})
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
client, err := New(tp,
WithAPIKey(" "),
WithProject("test-project"),
WithBlockingLogin(true),
WithLogger(intlogger.NewFailTestLogger(t)),
)
require.NoError(t, err)
require.NotNil(t, client)
assert.Equal(t, auth.TestAPIKey, client.session.APIInfo().APIKey)
}
func TestNew_BlankExplicitAPIKeyUsesBraintrustJSONFallback(t *testing.T) {
// Note: No t.Parallel() because this test changes the process cwd.
t.Setenv("BRAINTRUST_API_KEY", "")
root := t.TempDir()
require.NoError(t, os.WriteFile(
filepath.Join(root, ".braintrust.json"),
[]byte(fmt.Sprintf(`{"BRAINTRUST_API_KEY":%q}`, auth.TestAPIKey)),
0o600,
))
oldwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(root))
t.Cleanup(func() {
require.NoError(t, os.Chdir(oldwd))
})
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
client, err := New(tp,
WithAPIKey(os.Getenv("BRAINTRUST_API_KEY")),
WithProject("test-project"),
WithBlockingLogin(true),
WithLogger(intlogger.NewFailTestLogger(t)),
)
require.NoError(t, err)
require.NotNil(t, client)
assert.Equal(t, auth.TestAPIKey, client.session.APIInfo().APIKey)
}
func TestTracing_OTLPExporterWaitsForBraintrustJSONFallback(t *testing.T) {
// Note: No t.Parallel() because this test changes the process cwd.
t.Setenv("BRAINTRUST_API_KEY", "")
root := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(root, ".braintrust.json"), []byte(`{"BRAINTRUST_API_KEY":"file-api-key"}`), 0o600))
oldwd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(root))
t.Cleanup(func() {
require.NoError(t, os.Chdir(oldwd))
})
otelAuth := make(chan string, 1)
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/apikey/login":
assert.Equal(t, "Bearer file-api-key", r.Header.Get("Authorization"))
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"org_info":[{"id":"test-org-id","name":"test-org","api_url":%q,"proxy_url":%q}]}`, server.URL, server.URL)
case "/otel/v1/traces":
otelAuth <- r.Header.Get("Authorization")
w.WriteHeader(http.StatusOK)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
client, err := New(tp,
WithProject("test-project"),
WithAPIURL(server.URL),
WithAppURL(server.URL),
WithLogger(logger.Discard()),
)
require.NoError(t, err)
tracer := client.Tracer("test-app")
_, span := tracer.Start(context.Background(), "test-span")
span.End()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
require.NoError(t, tp.ForceFlush(ctx))
select {
case authHeader := <-otelAuth:
assert.Equal(t, "Bearer file-api-key", authHeader)
case <-ctx.Done():
t.Fatal("timed out waiting for OTLP export")
}
}
func TestNew_MissingAppURL(t *testing.T) {
// Note: No t.Parallel() because we're setting environment variables
t.Setenv("BRAINTRUST_APP_URL", "")
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
// Try to create client without App URL (override the default)
client, err := New(tp,
WithAPIKey("test-key"),
WithProject("test-project"),
WithAppURL(""), // Explicitly set to empty
WithLogger(logger.Discard()),
)
// Should fail with error about App URL
require.Error(t, err)
assert.Nil(t, client)
assert.Contains(t, err.Error(), "app URL")
}
func TestNew_MissingAPIURL(t *testing.T) {
// Note: No t.Parallel() because we're setting environment variables
t.Setenv("BRAINTRUST_API_URL", "")
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
// Try to create client without API URL (override the default)
client, err := New(tp,
WithAPIKey("test-key"),
WithProject("test-project"),
WithAPIURL(""), // Explicitly set to empty
WithLogger(logger.Discard()),
)
// Should fail with error about API URL
require.Error(t, err)
assert.Nil(t, client)
assert.Contains(t, err.Error(), "API URL")
}
func TestNew_InvalidAPIURLWithImmediateAPIKey(t *testing.T) {
t.Parallel()
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(context.Background()) }()
client, err := New(tp,
WithAPIKey(auth.TestAPIKey),
WithProject("test-project"),
WithAPIURL("not-a-url"),
WithLogger(logger.Discard()),
)
if client != nil {
defer client.session.Close()
}
require.Error(t, err)
assert.Nil(t, client)
assert.Contains(t, err.Error(), "invalid url")
}
func TestTracing_EndToEnd(t *testing.T) {
t.Parallel()
// Create a memory exporter to capture spans without making API calls
exporter := tracetest.NewInMemoryExporter()
// Create TracerProvider with simple processor
tp := trace.NewTracerProvider(
trace.WithSyncer(exporter),
)
defer func() { _ = tp.Shutdown(context.Background()) }()
// Create client with custom exporter
client, err := New(tp,
WithAPIKey(auth.TestAPIKey),
WithProject("test-project"),
WithExporter(exporter),
WithLogger(intlogger.NewFailTestLogger(t)),
)
require.NoError(t, err)
// Create a span using the client's tracer
tracer := client.Tracer("test-app")
ctx, span := tracer.Start(context.Background(), "test-operation")
span.End()
// Flush to ensure span is exported
err = client.TracerProvider().ForceFlush(context.Background())
require.NoError(t, err)
// Verify context is valid
assert.NotNil(t, ctx)
// Verify span was captured by our exporter
spans := exporter.GetSpans()
assert.GreaterOrEqual(t, len(spans), 1, "Expected at least one span to be exported")
}
func TestTracing_WithExporter(t *testing.T) {
t.Parallel()
// Create a memory exporter for testing
exporter := tracetest.NewInMemoryExporter()
// Create TracerProvider with simple processor
tp := trace.NewTracerProvider(
trace.WithSyncer(exporter),
)
defer func() { _ = tp.Shutdown(context.Background()) }()
// Create client with custom exporter
client, err := New(tp,
WithAPIKey(auth.TestAPIKey),
WithProject("test-project"),
WithExporter(exporter),
WithLogger(intlogger.NewFailTestLogger(t)),
)
require.NoError(t, err)
// Create a span
tracer := client.Tracer("test-app")
_, span := tracer.Start(context.Background(), "test-span")
span.End()
// Force flush to ensure span is exported
err = tp.ForceFlush(context.Background())
require.NoError(t, err)
// Verify span was captured
spans := exporter.GetSpans()
assert.GreaterOrEqual(t, len(spans), 1)
}