-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_test.go
More file actions
586 lines (527 loc) · 17.9 KB
/
query_test.go
File metadata and controls
586 lines (527 loc) · 17.9 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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package augur_test
import (
"context"
"errors"
"testing"
augur "github.com/rossbrandon/augur-go"
)
type actorFamily struct {
Spouse string `json:"spouse" augur:"required,desc:Current or most recent spouse"`
Children []string `json:"children" augur:"required,desc:Biological and adopted children"`
Parents []string `json:"parents" augur:"desc:Biological parents"`
}
type netWorth struct {
Amount int64 `json:"amount" augur:"required,desc:Estimated net worth in USD"`
Currency string `json:"currency" augur:"required,default:USD"`
}
func TestQuery_FullSuccess(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin","Elizabeth"],"parents":["Amos","Janet"]}`)
client := augur.New(newMock(resp))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Data == nil {
t.Fatal("Data should not be nil on full success")
}
if result.Data.Spouse != "Rita Wilson" {
t.Errorf("spouse: got %q", result.Data.Spouse)
}
if len(result.Data.Children) != 2 {
t.Errorf("children count: got %d", len(result.Data.Children))
}
if len(result.Errors) != 0 {
t.Errorf("expected no errors, got %v", result.Errors)
}
}
func TestQuery_PartialSuccess_OptionalFieldMissing(t *testing.T) {
// Parents is optional — missing it should yield partial success (err == nil).
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin","Elizabeth"]}`)
client := augur.New(newMock(resp))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Data == nil {
t.Fatal("Data should not be nil on partial success")
}
if len(result.Errors) == 0 {
t.Error("expected field errors for missing optional field")
}
found := false
for _, e := range result.Errors {
if e.Field == "parents" {
found = true
}
}
if !found {
t.Error("expected parents in field errors")
}
}
func TestQuery_TotalFailure_RequiredFieldMissing(t *testing.T) {
// Spouse is required — missing after retries yields total failure.
// err is nil; total failure is signaled by resp.Data == nil.
resp := envelope(`{"children":["Colin","Elizabeth"]}`)
client := augur.New(newMock(resp), augur.WithMaxRetries(0))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("expected nil error on total failure, got %v", err)
}
if result == nil {
t.Fatal("result should be non-nil on total failure")
}
if result.Data != nil {
t.Error("Data should be nil on total failure")
}
if len(result.Errors) == 0 {
t.Error("expected field errors on total failure")
}
}
func TestQuery_Retry_ResolvesRequiredField(t *testing.T) {
// First call missing spouse; second (retry) provides it.
first := envelope(`{"children":["Colin","Elizabeth"]}`)
second := envelope(`{"spouse":"Rita Wilson"}`)
client := augur.New(newMock(first, second), augur.WithMaxRetries(1))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error after retry: %v", err)
}
if result.Data == nil {
t.Fatal("Data should not be nil after successful retry")
}
if result.Data.Spouse != "Rita Wilson" {
t.Errorf("spouse after retry: got %q", result.Data.Spouse)
}
}
func TestQuery_DefaultApplied(t *testing.T) {
resp := envelope(`{"amount":400000000}`)
client := augur.New(newMock(resp))
result, err := augur.Query[netWorth](context.Background(), client, &augur.Request{
Query: "Tom Hanks net worth",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Data.Currency != "USD" {
t.Errorf("default currency: got %q, want %q", result.Data.Currency, "USD")
}
}
func TestQuery_CoercesStringToInt(t *testing.T) {
resp := envelope(`{"amount":"$400,000,000","currency":"USD"}`)
client := augur.New(newMock(resp))
result, err := augur.Query[netWorth](context.Background(), client, &augur.Request{
Query: "Tom Hanks net worth",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Data.Amount != 400000000 {
t.Errorf("amount after coercion: got %d, want 400000000", result.Data.Amount)
}
}
func TestQuery_ProviderFailure(t *testing.T) {
client := augur.New(newMockErr(errors.New("connection refused")))
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if !errors.Is(err, augur.ErrProviderFailure) {
t.Fatalf("expected ErrProviderFailure, got %v", err)
}
}
func TestQuery_MalformedResponse(t *testing.T) {
client := augur.New(newMock("this is not json"))
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if !errors.Is(err, augur.ErrResponseMalformed) {
t.Fatalf("expected ErrResponseMalformed, got %v", err)
}
}
func TestQuery_ExplicitSchema(t *testing.T) {
const schemaJSON = `{
"type": "object",
"properties": {
"net_worth": {"type": "integer", "description": "Net worth in USD"}
},
"required": ["net_worth"]
}`
schema, err := augur.SchemaFromJSON(schemaJSON)
if err != nil {
t.Fatalf("SchemaFromJSON: %v", err)
}
resp := envelope(`{"net_worth":400000000}`)
client := augur.New(newMock(resp))
result, err := augur.Query[map[string]any](context.Background(), client, &augur.Request{
Query: "Tom Hanks net worth",
Schema: schema,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Data == nil {
t.Fatal("expected non-nil Data")
}
nw, ok := (*result.Data)["net_worth"]
if !ok {
t.Fatal("net_worth missing from result")
}
if nw != float64(400000000) {
t.Errorf("net_worth: got %v", nw)
}
}
func TestQuery_NoSchema_MapType_ReturnsError(t *testing.T) {
client := augur.New(newMock(`{}`))
_, err := augur.Query[map[string]any](context.Background(), client, &augur.Request{
Query: "anything",
})
if !errors.Is(err, augur.ErrSchemaInvalid) {
t.Fatalf("expected ErrSchemaInvalid, got %v", err)
}
}
func TestQuery_TokenUsageAccumulated(t *testing.T) {
// Two calls (initial + retry), each returning 10 input / 20 output tokens.
first := envelope(`{"children":["Colin"]}`)
second := envelope(`{"spouse":"Rita Wilson"}`)
client := augur.New(newMock(first, second), augur.WithMaxRetries(1))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Usage == nil {
t.Fatal("expected non-nil Usage")
}
if result.Usage.InputTokens != 20 {
t.Errorf("input tokens: got %d, want 20", result.Usage.InputTokens)
}
if result.Usage.OutputTokens != 40 {
t.Errorf("output tokens: got %d, want 40", result.Usage.OutputTokens)
}
}
func TestQuery_MetaFlowsThrough(t *testing.T) {
resp := envelopeWithMeta(
`{"spouse":"Rita Wilson","children":["Colin","Elizabeth"],"parents":["Amos"]}`,
`{"spouse":{"confidence":0.99,"sources":[{"url":"https://example.com","title":"Wikipedia"}]},"children":{"confidence":0.9,"sources":[]}}`,
)
client := augur.New(newMock(resp))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Meta == nil {
t.Fatal("expected non-nil Meta")
}
spouseMeta, ok := result.Meta["spouse"]
if !ok {
t.Fatal("expected spouse in Meta")
}
if spouseMeta.Confidence != 0.99 {
t.Errorf("spouse confidence: got %v, want 0.99", spouseMeta.Confidence)
}
if len(spouseMeta.Sources) != 1 {
t.Fatalf("spouse sources count: got %d, want 1", len(spouseMeta.Sources))
}
if spouseMeta.Sources[0].URL != "https://example.com" {
t.Errorf("spouse source url: got %q", spouseMeta.Sources[0].URL)
}
if spouseMeta.Sources[0].Title != "Wikipedia" {
t.Errorf("spouse source title: got %q", spouseMeta.Sources[0].Title)
}
if result.Notes != "test notes" {
t.Errorf("notes: got %q, want %q", result.Notes, "test notes")
}
}
func TestQuery_CancelledContext_DuringRetry(t *testing.T) {
// First call missing required field triggers retry, but context is
// cancelled before the retry executes.
ctx, cancel := context.WithCancel(context.Background())
mock := &mockProvider{
responses: []string{envelope(`{"children":["Colin"]}`)},
}
client := augur.New(mock, augur.WithMaxRetries(1))
// Cancel after the first call completes (before retry).
cancel()
_, err := augur.Query[actorFamily](ctx, client, &augur.Request{
Query: "Tom Hanks family",
})
if err == nil {
t.Fatal("expected error for cancelled context during retry")
}
if !errors.Is(err, context.Canceled) {
t.Fatalf("expected context.Canceled, got %v", err)
}
}
func TestQuery_ProviderFailureOnRetry(t *testing.T) {
// First call succeeds but missing required field; retry fails with provider error.
mock := &mockProvider{
responses: []string{envelope(`{"children":["Colin"]}`)},
errOnCall: map[int]error{1: errors.New("rate limited")},
}
client := augur.New(mock, augur.WithMaxRetries(1))
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if !errors.Is(err, augur.ErrProviderFailure) {
t.Fatalf("expected ErrProviderFailure, got %v", err)
}
}
func TestQuery_ResponseHelpers(t *testing.T) {
t.Run("OK", func(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin"],"parents":["Amos"]}`)
client := augur.New(newMock(resp))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !result.OK() {
t.Error("expected OK() to be true for full success")
}
if result.IsPartial() {
t.Error("expected IsPartial() to be false for full success")
}
})
t.Run("Partial", func(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin"]}`)
client := augur.New(newMock(resp))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.OK() {
t.Error("expected OK() to be false for partial success")
}
if !result.IsPartial() {
t.Error("expected IsPartial() to be true for partial success")
}
})
t.Run("TotalFailure", func(t *testing.T) {
resp := envelope(`{"children":["Colin"]}`)
client := augur.New(newMock(resp), augur.WithMaxRetries(0))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.OK() {
t.Error("expected OK() to be false for total failure")
}
if result.IsPartial() {
t.Error("expected IsPartial() to be false for total failure")
}
if result.Data != nil {
t.Error("expected Data to be nil for total failure")
}
})
}
func TestSchemaFromFile_Nonexistent(t *testing.T) {
_, err := augur.SchemaFromFile("/nonexistent/path/schema.json")
if !errors.Is(err, augur.ErrSchemaInvalid) {
t.Fatalf("expected ErrSchemaInvalid, got %v", err)
}
}
func TestQuery_SourcesConfig_PassedToProvider(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin"],"parents":["Amos"]}`)
mock := newMock(resp)
client := augur.New(mock)
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
Options: &augur.QueryOptions{
Sources: &augur.SourceConfig{
MaxSearches: augur.Int(3),
AllowedDomains: []string{"wikipedia.org"},
},
},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if mock.lastParams == nil {
t.Fatal("expected lastParams to be captured")
}
if mock.lastParams.Sources == nil {
t.Fatal("expected Sources to be passed to provider")
}
if *mock.lastParams.Sources.MaxSearches != 3 {
t.Errorf("MaxSearches: got %d, want 3", *mock.lastParams.Sources.MaxSearches)
}
if len(mock.lastParams.Sources.AllowedDomains) != 1 || mock.lastParams.Sources.AllowedDomains[0] != "wikipedia.org" {
t.Errorf("AllowedDomains: got %v", mock.lastParams.Sources.AllowedDomains)
}
}
func TestQuery_DefaultSourcesPassedToProvider(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin"],"parents":["Amos"]}`)
mock := newMock(resp)
client := augur.New(mock)
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if mock.lastParams.Sources == nil {
t.Error("expected Sources to be non-nil by default (web search enabled)")
}
}
func TestQuery_SourcesDisabled_NotPassedToProvider(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin"],"parents":["Amos"]}`)
mock := newMock(resp)
client := augur.New(mock)
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
Options: &augur.QueryOptions{
Sources: &augur.SourceConfig{Disabled: true},
},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if mock.lastParams.Sources != nil {
t.Error("expected Sources to be nil when disabled")
}
}
func TestQuery_WithoutWebSearch_DisablesGlobally(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin"],"parents":["Amos"]}`)
mock := newMock(resp)
client := augur.New(mock, augur.WithoutWebSearch())
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if mock.lastParams.Sources != nil {
t.Error("expected Sources to be nil when WithoutWebSearch is set")
}
}
func TestQuery_WithoutWebSearch_PerQueryReenables(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin"],"parents":["Amos"]}`)
mock := newMock(resp)
client := augur.New(mock, augur.WithoutWebSearch())
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
Options: &augur.QueryOptions{
Sources: &augur.SourceConfig{},
},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if mock.lastParams.Sources == nil {
t.Error("expected Sources to be non-nil when per-query re-enables web search")
}
}
func TestQuery_WithSourceConfig_SetsDefaults(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin"],"parents":["Amos"]}`)
mock := newMock(resp)
client := augur.New(mock, augur.WithSourceConfig(augur.SourceConfig{
MaxSearches: augur.Int(5),
AllowedDomains: []string{"example.com"},
}))
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if mock.lastParams.Sources == nil {
t.Fatal("expected Sources to be non-nil")
}
if *mock.lastParams.Sources.MaxSearches != 5 {
t.Errorf("MaxSearches: got %d, want 5", *mock.lastParams.Sources.MaxSearches)
}
if len(mock.lastParams.Sources.AllowedDomains) != 1 || mock.lastParams.Sources.AllowedDomains[0] != "example.com" {
t.Errorf("AllowedDomains: got %v", mock.lastParams.Sources.AllowedDomains)
}
}
func TestQuery_PerQuerySources_OverridesClient(t *testing.T) {
resp := envelope(`{"spouse":"Rita Wilson","children":["Colin"],"parents":["Amos"]}`)
mock := newMock(resp)
client := augur.New(mock, augur.WithSourceConfig(augur.SourceConfig{
MaxSearches: augur.Int(5),
}))
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
Options: &augur.QueryOptions{
Sources: &augur.SourceConfig{
MaxSearches: augur.Int(1),
},
},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if *mock.lastParams.Sources.MaxSearches != 1 {
t.Errorf("MaxSearches: got %d, want 1 (per-query override)", *mock.lastParams.Sources.MaxSearches)
}
}
func TestQuery_WebSearchUsageAccumulated(t *testing.T) {
first := envelope(`{"children":["Colin"]}`)
second := envelope(`{"spouse":"Rita Wilson"}`)
mock := &mockProvider{
responses: []string{first, second},
usage: &augur.Usage{InputTokens: 10, OutputTokens: 20, WebSearchRequests: 2},
}
client := augur.New(mock, augur.WithMaxRetries(1))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result.Usage == nil {
t.Fatal("expected non-nil Usage")
}
if result.Usage.WebSearchRequests != 4 {
t.Errorf("WebSearchRequests: got %d, want 4 (2 per call x 2 calls)", result.Usage.WebSearchRequests)
}
}
func TestQuery_MetaCitedTextFlowsThrough(t *testing.T) {
resp := envelopeWithMeta(
`{"spouse":"Rita Wilson","children":["Colin"],"parents":["Amos"]}`,
`{"spouse":{"confidence":0.99,"sources":[{"url":"https://en.wikipedia.org/wiki/Tom_Hanks","title":"Tom Hanks - Wikipedia","citedText":"Tom Hanks married Rita Wilson in 1988."}]}}`,
)
client := augur.New(newMock(resp))
result, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
spouseMeta, ok := result.Meta["spouse"]
if !ok {
t.Fatal("expected spouse in Meta")
}
if len(spouseMeta.Sources) != 1 {
t.Fatalf("expected 1 source, got %d", len(spouseMeta.Sources))
}
src := spouseMeta.Sources[0]
if src.CitedText != "Tom Hanks married Rita Wilson in 1988." {
t.Errorf("CitedText: got %q", src.CitedText)
}
}
func TestQuery_SourcesNotSupported(t *testing.T) {
mock := newMockErr(augur.ErrSourcesNotSupported)
client := augur.New(mock)
_, err := augur.Query[actorFamily](context.Background(), client, &augur.Request{
Query: "Tom Hanks family",
})
if !errors.Is(err, augur.ErrProviderFailure) {
t.Fatalf("expected ErrProviderFailure wrapping, got %v", err)
}
}