-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathintegration_test.go
More file actions
2489 lines (2139 loc) · 77.6 KB
/
integration_test.go
File metadata and controls
2489 lines (2139 loc) · 77.6 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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build integration
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"math"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/onllm-dev/onwatch/v2/internal/agent"
"github.com/onllm-dev/onwatch/v2/internal/api"
"github.com/onllm-dev/onwatch/v2/internal/config"
"github.com/onllm-dev/onwatch/v2/internal/store"
"github.com/onllm-dev/onwatch/v2/internal/testutil"
"github.com/onllm-dev/onwatch/v2/internal/tracker"
"github.com/onllm-dev/onwatch/v2/internal/web"
)
// discardLogger returns a logger that discards all output
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
// makeHandler creates a Handler wired with proper sessions/config for legacy tests.
func makeHandler(t *testing.T, s *store.Store, tr *tracker.Tracker) *web.Handler {
t.Helper()
logger := discardLogger()
cfg := testutil.TestConfig("http://localhost:0")
sessions := web.NewSessionStore(cfg.AdminUser, "testhash", s)
h := web.NewHandler(s, tr, logger, sessions, cfg)
h.SetVersion("test-dev")
return h
}
// mockServer creates a test server that returns synthetic API responses.
// Uses atomic counter for thread safety. Does not call t.Errorf from the handler
// goroutine to avoid races with the test goroutine.
func mockServer(_ *testing.T, responses []api.QuotaResponse) *httptest.Server {
var callCount atomic.Int64
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" || r.URL.Path != "/v2/quotas" {
http.Error(w, "not found", http.StatusNotFound)
return
}
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
idx := int(callCount.Add(1) - 1)
if idx < len(responses) {
json.NewEncoder(w).Encode(responses[idx])
} else {
// Return last response repeatedly
json.NewEncoder(w).Encode(responses[len(responses)-1])
}
}))
}
// TestIntegration_FullCycle tests the complete flow from API poll to dashboard data
func TestIntegration_FullCycle(t *testing.T) {
// Create temp directory for test database
tempDir := t.TempDir()
dbPath := filepath.Join(tempDir, "test.db")
// Setup mock API responses - need at least 2 with different values
// so SessionManager detects usage change and creates a session
now := time.Now().UTC()
responses := []api.QuotaResponse{
{
Subscription: api.QuotaInfo{
Limit: 1350,
Requests: 100.0,
RenewsAt: now.Add(5 * time.Hour),
},
Search: api.SearchInfo{
Hourly: api.QuotaInfo{
Limit: 250,
Requests: 10.0,
RenewsAt: now.Add(1 * time.Hour),
},
},
ToolCallDiscounts: api.QuotaInfo{
Limit: 16200,
Requests: 5000.0,
RenewsAt: now.Add(3 * time.Hour),
},
},
{
Subscription: api.QuotaInfo{
Limit: 1350,
Requests: 100.0,
RenewsAt: now.Add(5 * time.Hour),
},
Search: api.SearchInfo{
Hourly: api.QuotaInfo{
Limit: 250,
Requests: 11.0, // Slightly different to trigger session creation
RenewsAt: now.Add(1 * time.Hour),
},
},
ToolCallDiscounts: api.QuotaInfo{
Limit: 16200,
Requests: 5000.0,
RenewsAt: now.Add(3 * time.Hour),
},
},
}
server := mockServer(t, responses)
defer server.Close()
// Open database
db, err := store.New(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer db.Close()
// Create API client pointing to mock server
client := api.NewClient("syn_test_key", discardLogger(), api.WithBaseURL(server.URL+"/v2/quotas"))
// Create tracker
tr := tracker.New(db, discardLogger())
// Create session manager and agent with short interval for testing
sm := agent.NewSessionManager(db, "synthetic", 5*time.Minute, discardLogger())
ag := agent.New(client, db, tr, 100*time.Millisecond, discardLogger(), sm)
// Run agent for a short time - enough for 2+ polls to detect session
ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond)
defer cancel()
// Run agent (it will poll once immediately, then at interval)
done := make(chan error, 1)
go func() {
done <- ag.Run(ctx)
}()
// Wait for agent to complete or timeout
select {
case err := <-done:
if err != nil && err != context.DeadlineExceeded && err != context.Canceled {
t.Fatalf("Agent error: %v", err)
}
case <-time.After(500 * time.Millisecond):
t.Fatal("Agent did not complete in time")
}
// Verify data was stored (latest is second response after session-triggering poll)
latest, err := db.QueryLatest()
if err != nil {
t.Fatalf("Failed to query latest: %v", err)
}
if latest == nil {
t.Fatal("Expected snapshot to be stored")
}
if latest.Sub.Requests != 100.0 {
t.Errorf("Expected sub requests 100.0, got %f", latest.Sub.Requests)
}
// Search may be 10.0 or 11.0 depending on which poll was last
if latest.Search.Requests < 10.0 || latest.Search.Requests > 11.0 {
t.Errorf("Expected search requests 10.0-11.0, got %f", latest.Search.Requests)
}
if latest.ToolCall.Requests != 5000.0 {
t.Errorf("Expected tool requests 5000.0, got %f", latest.ToolCall.Requests)
}
// Verify session was created (needs 2 polls with different values)
sessions, err := db.QuerySessionHistory()
if err != nil {
t.Fatalf("Failed to query sessions: %v", err)
}
if len(sessions) < 1 {
t.Fatalf("Expected at least 1 session, got %d", len(sessions))
}
if sessions[0].SnapshotCount < 1 {
t.Errorf("Expected at least 1 snapshot, got %d", sessions[0].SnapshotCount)
}
// Test web handler returns the data
handler := makeHandler(t, db, tr)
// Test /api/current endpoint for synthetic provider
req := httptest.NewRequest("GET", "/api/current?provider=synthetic", nil)
w := httptest.NewRecorder()
handler.Current(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var currentResp map[string]interface{}
if err := json.Unmarshal(w.Body.Bytes(), ¤tResp); err != nil {
t.Fatalf("Failed to parse current response: %v", err)
}
// Verify the response contains subscription data
if _, ok := currentResp["subscription"]; !ok {
if _, ok2 := currentResp["error"]; ok2 {
t.Fatalf("Got error response: %s", w.Body.String())
}
t.Fatalf("Expected subscription in response, got keys: %v", currentResp)
}
}
// TestIntegration_ResetDetection tests reset cycle detection
func TestIntegration_ResetDetection(t *testing.T) {
tempDir := t.TempDir()
dbPath := filepath.Join(tempDir, "test.db")
now := time.Now().UTC()
oldRenewsAt := now.Add(5 * time.Hour)
newRenewsAt := now.Add(6 * time.Hour)
responses := []api.QuotaResponse{
// First poll - initial state
{
Subscription: api.QuotaInfo{
Limit: 1350,
Requests: 100.0,
RenewsAt: oldRenewsAt,
},
Search: api.SearchInfo{
Hourly: api.QuotaInfo{
Limit: 250,
Requests: 10.0,
RenewsAt: now.Add(1 * time.Hour),
},
},
ToolCallDiscounts: api.QuotaInfo{
Limit: 16200,
Requests: 5000.0,
RenewsAt: now.Add(3 * time.Hour),
},
},
// Second poll - subscription reset detected (renewsAt changed)
{
Subscription: api.QuotaInfo{
Limit: 1350,
Requests: 50.0, // Reset to lower value
RenewsAt: newRenewsAt,
},
Search: api.SearchInfo{
Hourly: api.QuotaInfo{
Limit: 250,
Requests: 15.0,
RenewsAt: now.Add(1 * time.Hour),
},
},
ToolCallDiscounts: api.QuotaInfo{
Limit: 16200,
Requests: 5100.0,
RenewsAt: now.Add(3 * time.Hour),
},
},
}
server := mockServer(t, responses)
defer server.Close()
db, err := store.New(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer db.Close()
client := api.NewClient("syn_test_key", discardLogger(), api.WithBaseURL(server.URL+"/v2/quotas"))
tr := tracker.New(db, discardLogger())
// First poll - runs once immediately then exits via short timeout
sm1 := agent.NewSessionManager(db, "synthetic", 5*time.Minute, discardLogger())
ag1 := agent.New(client, db, tr, 1*time.Hour, discardLogger(), sm1)
ctx1, cancel1 := context.WithTimeout(context.Background(), 200*time.Millisecond)
done1 := make(chan struct{})
go func() {
ag1.Run(ctx1)
close(done1)
}()
<-done1 // Wait for first agent to fully stop
cancel1()
// Second poll - should detect reset (renewsAt changed)
sm2 := agent.NewSessionManager(db, "synthetic", 5*time.Minute, discardLogger())
ag2 := agent.New(client, db, tr, 1*time.Hour, discardLogger(), sm2)
ctx2, cancel2 := context.WithTimeout(context.Background(), 200*time.Millisecond)
done2 := make(chan struct{})
go func() {
ag2.Run(ctx2)
close(done2)
}()
<-done2 // Wait for second agent to fully stop
cancel2()
// Verify cycles were recorded
history, err := db.QueryCycleHistory("subscription")
if err != nil {
t.Fatalf("Failed to query cycle history: %v", err)
}
if len(history) != 1 {
t.Fatalf("Expected 1 completed subscription cycle, got %d", len(history))
}
// The completed cycle should have peak of 100 (the max seen before reset)
if history[0].PeakRequests != 100.0 {
t.Errorf("Expected peak requests 100.0, got %f", history[0].PeakRequests)
}
// Verify via API endpoint
handler := makeHandler(t, db, tr)
req := httptest.NewRequest("GET", "/api/cycles?type=subscription&provider=synthetic", nil)
w := httptest.NewRecorder()
handler.Cycles(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d: %s", w.Code, w.Body.String())
}
var cyclesResp []map[string]interface{}
if err := json.Unmarshal(w.Body.Bytes(), &cyclesResp); err != nil {
t.Fatalf("Failed to parse cycles response: %v", err)
}
if len(cyclesResp) < 1 {
t.Fatalf("Expected at least 1 cycle in response, got %d", len(cyclesResp))
}
}
// TestIntegration_DashboardRendersData tests that the dashboard HTML contains actual data
func TestIntegration_DashboardRendersData(t *testing.T) {
tempDir := t.TempDir()
dbPath := filepath.Join(tempDir, "test.db")
now := time.Now().UTC()
responses := []api.QuotaResponse{
{
Subscription: api.QuotaInfo{
Limit: 1350,
Requests: 154.3,
RenewsAt: now.Add(5 * time.Hour),
},
Search: api.SearchInfo{
Hourly: api.QuotaInfo{
Limit: 250,
Requests: 0,
RenewsAt: now.Add(1 * time.Hour),
},
},
ToolCallDiscounts: api.QuotaInfo{
Limit: 16200,
Requests: 7635,
RenewsAt: now.Add(3 * time.Hour),
},
},
}
server := mockServer(t, responses)
defer server.Close()
db, err := store.New(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer db.Close()
client := api.NewClient("syn_test_key", discardLogger(), api.WithBaseURL(server.URL+"/v2/quotas"))
tr := tracker.New(db, discardLogger())
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
sm := agent.NewSessionManager(db, "synthetic", 5*time.Minute, discardLogger())
ag := agent.New(client, db, tr, 1*time.Hour, discardLogger(), sm)
go ag.Run(ctx)
time.Sleep(250 * time.Millisecond)
cancel()
time.Sleep(50 * time.Millisecond)
// Test dashboard HTML response
handler := makeHandler(t, db, tr)
req := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
handler.Dashboard(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
body := w.Body.String()
// Check that the page contains expected elements
if !strings.Contains(body, "onWatch") {
t.Error("Dashboard should contain 'onWatch'")
}
if !strings.Contains(body, "Dashboard") {
t.Error("Dashboard should contain 'Dashboard'")
}
if !strings.Contains(body, "style.css") {
t.Error("Dashboard should reference style.css")
}
if !strings.Contains(body, "app.js") {
t.Error("Dashboard should reference app.js")
}
}
// TestIntegration_GracefulShutdown tests that SIGINT triggers clean shutdown
func TestIntegration_GracefulShutdown(t *testing.T) {
if os.Getenv("CI") != "" {
t.Skip("Skipping shutdown test in CI environment")
}
tempDir := t.TempDir()
dbPath := filepath.Join(tempDir, "test.db")
now := time.Now().UTC()
responses := []api.QuotaResponse{
{
Subscription: api.QuotaInfo{
Limit: 1350,
Requests: 100.0,
RenewsAt: now.Add(5 * time.Hour),
},
Search: api.SearchInfo{
Hourly: api.QuotaInfo{
Limit: 250,
Requests: 10.0,
RenewsAt: now.Add(1 * time.Hour),
},
},
ToolCallDiscounts: api.QuotaInfo{
Limit: 16200,
Requests: 5000.0,
RenewsAt: now.Add(3 * time.Hour),
},
},
{
Subscription: api.QuotaInfo{
Limit: 1350,
Requests: 101.0, // Changed to trigger session
RenewsAt: now.Add(5 * time.Hour),
},
Search: api.SearchInfo{
Hourly: api.QuotaInfo{
Limit: 250,
Requests: 10.0,
RenewsAt: now.Add(1 * time.Hour),
},
},
ToolCallDiscounts: api.QuotaInfo{
Limit: 16200,
Requests: 5000.0,
RenewsAt: now.Add(3 * time.Hour),
},
},
}
server := mockServer(t, responses)
defer server.Close()
db, err := store.New(dbPath)
if err != nil {
t.Fatalf("Failed to open database: %v", err)
}
defer db.Close()
client := api.NewClient("syn_test_key", discardLogger(), api.WithBaseURL(server.URL+"/v2/quotas"))
tr := tracker.New(db, discardLogger())
sm := agent.NewSessionManager(db, "synthetic", 5*time.Minute, discardLogger())
ag := agent.New(client, db, tr, 500*time.Millisecond, discardLogger(), sm)
// Create web server
handler := makeHandler(t, db, tr)
webServer := web.NewServer(0, handler, discardLogger(), "admin", "testhash", "", "")
// Start web server in background
go webServer.Start()
time.Sleep(100 * time.Millisecond)
// Start agent in background - needs 2 polls to create session
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go ag.Run(ctx)
time.Sleep(1200 * time.Millisecond)
// Get active session
session, err := db.QueryActiveSession()
if err != nil {
t.Fatalf("Failed to query active session: %v", err)
}
if session == nil {
t.Fatal("Expected active session before shutdown")
}
// Cancel context to trigger graceful shutdown (simulates SIGINT handler)
cancel()
time.Sleep(500 * time.Millisecond)
// Verify session was closed properly
sessions, err := db.QuerySessionHistory()
if err != nil {
t.Fatalf("Failed to query sessions: %v", err)
}
if len(sessions) < 1 {
t.Fatal("Expected at least one session")
}
// The most recent session should have an end time
if sessions[0].EndedAt == nil {
t.Error("Session should have been closed (ended_at should not be nil)")
}
// Verify database is not corrupted by opening it again
db2, err := store.New(dbPath)
if err != nil {
t.Fatalf("Failed to reopen database: %v", err)
}
db2.Close()
}
// TestMain ensures the main package compiles and basic flags work
func TestMain_Version(t *testing.T) {
// Test version flag by checking if binary can be built
if testing.Short() {
t.Skip("Skipping binary build test in short mode")
}
// Just verify main.go compiles
// The actual binary test would require building
fmt.Println("Main package compiles successfully")
}
// Helper to make HTTP requests in tests
func makeRequest(t *testing.T, method, url string, body string) (*http.Response, string) {
var bodyReader io.Reader
if body != "" {
bodyReader = strings.NewReader(body)
}
req, err := http.NewRequest(method, url, bodyReader)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
return resp, string(respBody)
}
// ═══════════════════════════════════════════════════════════════════════
// 3.1 Synthetic Data Integrity (5 tests)
// ═══════════════════════════════════════════════════════════════════════
// TestIntegration_Synthetic_SnapshotStoredCorrectly verifies every field of a Synthetic
// snapshot is stored and round-tripped from the DB accurately.
func TestIntegration_Synthetic_SnapshotStoredCorrectly(t *testing.T) {
db := testutil.InMemoryStore(t)
now := time.Now().UTC().Truncate(time.Second)
renewsAt := now.Add(5 * time.Hour)
snap := &api.Snapshot{
CapturedAt: now,
Sub: api.QuotaInfo{Limit: 1350, Requests: 154.3, RenewsAt: renewsAt},
Search: api.QuotaInfo{Limit: 250, Requests: 42.7, RenewsAt: renewsAt},
ToolCall: api.QuotaInfo{Limit: 16200, Requests: 7635.5, RenewsAt: renewsAt},
}
id, err := db.InsertSnapshot(snap)
if err != nil {
t.Fatalf("InsertSnapshot: %v", err)
}
if id < 1 {
t.Fatal("Expected positive snapshot ID")
}
latest, err := db.QueryLatest()
if err != nil {
t.Fatalf("QueryLatest: %v", err)
}
if latest == nil {
t.Fatal("Expected non-nil snapshot")
}
// Verify every field
if latest.Sub.Limit != 1350 {
t.Errorf("Sub.Limit: want 1350, got %f", latest.Sub.Limit)
}
if latest.Sub.Requests != 154.3 {
t.Errorf("Sub.Requests: want 154.3, got %f", latest.Sub.Requests)
}
if latest.Search.Limit != 250 {
t.Errorf("Search.Limit: want 250, got %f", latest.Search.Limit)
}
if latest.Search.Requests != 42.7 {
t.Errorf("Search.Requests: want 42.7, got %f", latest.Search.Requests)
}
if latest.ToolCall.Limit != 16200 {
t.Errorf("ToolCall.Limit: want 16200, got %f", latest.ToolCall.Limit)
}
if latest.ToolCall.Requests != 7635.5 {
t.Errorf("ToolCall.Requests: want 7635.5, got %f", latest.ToolCall.Requests)
}
}
// TestIntegration_Synthetic_SequentialPollsAccumulate verifies multiple polls
// create multiple snapshots in the DB.
func TestIntegration_Synthetic_SequentialPollsAccumulate(t *testing.T) {
db := testutil.InMemoryStore(t)
now := time.Now().UTC()
renewsAt := now.Add(5 * time.Hour)
for i := range 5 {
snap := &api.Snapshot{
CapturedAt: now.Add(time.Duration(i) * time.Minute),
Sub: api.QuotaInfo{Limit: 1350, Requests: 100 + float64(i)*10, RenewsAt: renewsAt},
Search: api.QuotaInfo{Limit: 250, Requests: float64(i) * 5, RenewsAt: renewsAt},
ToolCall: api.QuotaInfo{Limit: 16200, Requests: 5000 + float64(i)*100, RenewsAt: renewsAt},
}
if _, err := db.InsertSnapshot(snap); err != nil {
t.Fatalf("InsertSnapshot[%d]: %v", i, err)
}
}
start := now.Add(-time.Minute)
end := now.Add(10 * time.Minute)
snaps, err := db.QueryRange(start, end)
if err != nil {
t.Fatalf("QueryRange: %v", err)
}
if len(snaps) != 5 {
t.Fatalf("Expected 5 snapshots, got %d", len(snaps))
}
// Verify ordering (ascending by captured_at)
for i := 1; i < len(snaps); i++ {
if snaps[i].CapturedAt.Before(snaps[i-1].CapturedAt) {
t.Errorf("Snapshots not in ascending order at index %d", i)
}
}
// Verify last snapshot has the highest requests
if snaps[4].Sub.Requests != 140 {
t.Errorf("Last snapshot Sub.Requests: want 140, got %f", snaps[4].Sub.Requests)
}
}
// TestIntegration_Synthetic_ResetDetectionCreatesCycle verifies that a change in
// renewsAt creates a new cycle via the tracker.
func TestIntegration_Synthetic_ResetDetectionCreatesCycle(t *testing.T) {
db := testutil.InMemoryStore(t)
tr := tracker.New(db, testutil.DiscardLogger())
now := time.Now().UTC()
// First snapshot: initial state
snap1 := &api.Snapshot{
CapturedAt: now,
Sub: api.QuotaInfo{Limit: 1350, Requests: 500, RenewsAt: now.Add(1 * time.Hour)},
Search: api.QuotaInfo{Limit: 250, Requests: 100, RenewsAt: now.Add(1 * time.Hour)},
ToolCall: api.QuotaInfo{Limit: 16200, Requests: 10000, RenewsAt: now.Add(1 * time.Hour)},
}
db.InsertSnapshot(snap1)
tr.Process(snap1)
// Second snapshot: renewsAt changed = reset occurred
snap2 := &api.Snapshot{
CapturedAt: now.Add(time.Minute),
Sub: api.QuotaInfo{Limit: 1350, Requests: 5, RenewsAt: now.Add(25 * time.Hour)},
Search: api.QuotaInfo{Limit: 250, Requests: 0, RenewsAt: now.Add(1 * time.Hour)},
ToolCall: api.QuotaInfo{Limit: 16200, Requests: 50, RenewsAt: now.Add(1 * time.Hour)},
}
db.InsertSnapshot(snap2)
tr.Process(snap2)
// Verify subscription cycle was closed
cycles, err := db.QueryCycleHistory("subscription")
if err != nil {
t.Fatalf("QueryCycleHistory: %v", err)
}
if len(cycles) < 1 {
t.Fatal("Expected at least 1 completed subscription cycle")
}
if cycles[0].PeakRequests != 500 {
t.Errorf("Peak requests: want 500, got %f", cycles[0].PeakRequests)
}
}
// TestIntegration_Synthetic_FloatPrecision verifies that float64 values survive
// the SQLite round-trip without precision loss.
func TestIntegration_Synthetic_FloatPrecision(t *testing.T) {
db := testutil.InMemoryStore(t)
now := time.Now().UTC()
// Use values with fractional parts that might lose precision
snap := &api.Snapshot{
CapturedAt: now,
Sub: api.QuotaInfo{Limit: 1350, Requests: 154.333333333, RenewsAt: now.Add(time.Hour)},
Search: api.QuotaInfo{Limit: 250, Requests: 0.000001, RenewsAt: now.Add(time.Hour)},
ToolCall: api.QuotaInfo{Limit: 16200, Requests: 99999.999999, RenewsAt: now.Add(time.Hour)},
}
db.InsertSnapshot(snap)
latest, err := db.QueryLatest()
if err != nil {
t.Fatalf("QueryLatest: %v", err)
}
eps := 1e-9
if math.Abs(latest.Sub.Requests-154.333333333) > eps {
t.Errorf("Sub.Requests precision loss: %f", latest.Sub.Requests)
}
if math.Abs(latest.Search.Requests-0.000001) > eps {
t.Errorf("Search.Requests precision loss: %f", latest.Search.Requests)
}
if math.Abs(latest.ToolCall.Requests-99999.999999) > eps {
t.Errorf("ToolCall.Requests precision loss: %f", latest.ToolCall.Requests)
}
}
// TestIntegration_Synthetic_HandlerReturnsDBData verifies the /api/current handler
// returns data that matches what was stored in the DB.
func TestIntegration_Synthetic_HandlerReturnsDBData(t *testing.T) {
h, s := testutil.TestHandler(t)
now := time.Now().UTC()
snap := &api.Snapshot{
CapturedAt: now,
Sub: api.QuotaInfo{Limit: 1350, Requests: 200, RenewsAt: now.Add(5 * time.Hour)},
Search: api.QuotaInfo{Limit: 250, Requests: 50, RenewsAt: now.Add(1 * time.Hour)},
ToolCall: api.QuotaInfo{Limit: 16200, Requests: 8000, RenewsAt: now.Add(3 * time.Hour)},
}
s.InsertSnapshot(snap)
req := httptest.NewRequest("GET", "/api/current?provider=synthetic", nil)
w := httptest.NewRecorder()
h.Current(w, req)
if w.Code != http.StatusOK {
t.Fatalf("Expected 200, got %d: %s", w.Code, w.Body.String())
}
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
sub, ok := resp["subscription"].(map[string]interface{})
if !ok {
t.Fatal("Missing subscription in response")
}
if sub["usage"].(float64) != 200 {
t.Errorf("subscription.usage: want 200, got %v", sub["usage"])
}
if sub["limit"].(float64) != 1350 {
t.Errorf("subscription.limit: want 1350, got %v", sub["limit"])
}
}
// ═══════════════════════════════════════════════════════════════════════
// 3.2 Z.ai Data Integrity (7 tests)
// ═══════════════════════════════════════════════════════════════════════
// TestIntegration_Zai_SnapshotStoredCorrectly verifies every field of a Z.ai
// snapshot is stored and round-tripped.
func TestIntegration_Zai_SnapshotStoredCorrectly(t *testing.T) {
db := testutil.InMemoryStore(t)
now := time.Now().UTC().Truncate(time.Second)
resetTime := now.Add(7 * 24 * time.Hour)
snap := &api.ZaiSnapshot{
CapturedAt: now,
TimeLimit: 1000,
TimeUnit: 1,
TimeNumber: 1000,
TimeUsage: 1000,
TimeCurrentValue: 19,
TimeRemaining: 981,
TimePercentage: 1,
TimeUsageDetails: `[{"modelCode":"search-prime","usage":16}]`,
TokensLimit: 200000000,
TokensUnit: 1,
TokensNumber: 200000000,
TokensUsage: 200000000,
TokensCurrentValue: 50000000,
TokensRemaining: 150000000,
TokensPercentage: 25,
TokensNextResetTime: &resetTime,
}
id, err := db.InsertZaiSnapshot(snap)
if err != nil {
t.Fatalf("InsertZaiSnapshot: %v", err)
}
if id < 1 {
t.Fatal("Expected positive ID")
}
latest, err := db.QueryLatestZai()
if err != nil {
t.Fatalf("QueryLatestZai: %v", err)
}
if latest == nil {
t.Fatal("Expected non-nil snapshot")
}
if latest.TimeUsage != 1000 {
t.Errorf("TimeUsage: want 1000, got %f", latest.TimeUsage)
}
if latest.TimeCurrentValue != 19 {
t.Errorf("TimeCurrentValue: want 19, got %f", latest.TimeCurrentValue)
}
if latest.TokensUsage != 200000000 {
t.Errorf("TokensUsage: want 200000000, got %f", latest.TokensUsage)
}
if latest.TokensCurrentValue != 50000000 {
t.Errorf("TokensCurrentValue: want 50000000, got %f", latest.TokensCurrentValue)
}
if latest.TokensPercentage != 25 {
t.Errorf("TokensPercentage: want 25, got %d", latest.TokensPercentage)
}
if latest.TokensNextResetTime == nil {
t.Fatal("TokensNextResetTime should not be nil")
}
if latest.TimeUsageDetails == "" {
t.Error("TimeUsageDetails should not be empty")
}
}
// TestIntegration_Zai_EpochMsToISO8601 verifies that epoch millisecond reset times
// are correctly converted to time.Time during the API -> snapshot conversion.
func TestIntegration_Zai_EpochMsToISO8601(t *testing.T) {
epochMs := int64(1770398385482)
expected := time.UnixMilli(epochMs)
limit := api.ZaiLimit{
Type: "TOKENS_LIMIT",
Usage: 200000000,
CurrentValue: 50000000,
Remaining: 150000000,
Percentage: 25,
NextResetMs: &epochMs,
}
resetTime := limit.GetResetTime()
if resetTime == nil {
t.Fatal("Expected non-nil reset time")
}
if !resetTime.Equal(expected) {
t.Errorf("Reset time: want %v, got %v", expected, *resetTime)
}
// Verify through ToSnapshot conversion
resp := &api.ZaiQuotaResponse{
Limits: []api.ZaiLimit{
{Type: "TIME_LIMIT", Usage: 1000, CurrentValue: 19, Remaining: 981, Percentage: 1},
limit,
},
}
snap := resp.ToSnapshot(time.Now().UTC())
if snap.TokensNextResetTime == nil {
t.Fatal("Snapshot TokensNextResetTime should not be nil")
}
if !snap.TokensNextResetTime.Equal(expected) {
t.Errorf("Snapshot reset time mismatch: want %v, got %v", expected, *snap.TokensNextResetTime)
}
}
// TestIntegration_Zai_UsageExceedsLimit verifies Z.ai snapshots store correctly
// when currentValue exceeds the usage budget (no hard cap).
func TestIntegration_Zai_UsageExceedsLimit(t *testing.T) {
db := testutil.InMemoryStore(t)
now := time.Now().UTC()
snap := &api.ZaiSnapshot{
CapturedAt: now,
TokensUsage: 200000000,
TokensCurrentValue: 200112618, // Exceeds budget
TokensRemaining: 0,
TokensPercentage: 100,
}
_, err := db.InsertZaiSnapshot(snap)
if err != nil {
t.Fatalf("InsertZaiSnapshot: %v", err)
}
latest, err := db.QueryLatestZai()
if err != nil {
t.Fatalf("QueryLatestZai: %v", err)
}
if latest.TokensCurrentValue != 200112618 {
t.Errorf("Expected currentValue 200112618, got %f", latest.TokensCurrentValue)
}
if latest.TokensCurrentValue <= latest.TokensUsage {
t.Error("Expected currentValue > usage (over budget)")
}
}
// TestIntegration_Zai_NoResetTimeOnTimeLimit verifies TIME_LIMIT has nil reset time.
func TestIntegration_Zai_NoResetTimeOnTimeLimit(t *testing.T) {
db := testutil.InMemoryStore(t)
now := time.Now().UTC()
// TIME_LIMIT has no reset time
snap := &api.ZaiSnapshot{
CapturedAt: now,
TimeUsage: 1000,
TimeCurrentValue: 19,
TimeRemaining: 981,
TimePercentage: 1,
TokensNextResetTime: nil, // no reset info for TIME_LIMIT
}
db.InsertZaiSnapshot(snap)
latest, err := db.QueryLatestZai()
if err != nil {
t.Fatalf("QueryLatestZai: %v", err)
}
if latest.TokensNextResetTime != nil {
t.Errorf("Expected nil TokensNextResetTime for TIME_LIMIT, got %v", latest.TokensNextResetTime)
}
}
// TestIntegration_Zai_ResetDetection verifies Z.ai token reset cycle detection.
func TestIntegration_Zai_ResetDetection(t *testing.T) {
db := testutil.InMemoryStore(t)
zaiTr := tracker.NewZaiTracker(db, testutil.DiscardLogger())
now := time.Now().UTC()
resetBefore := now.Add(1 * time.Hour)
resetAfter := now.Add(8 * 24 * time.Hour)
// First snapshot: high usage, near reset
snap1 := &api.ZaiSnapshot{
CapturedAt: now,
TokensUsage: 200000000,
TokensCurrentValue: 190000000,
TokensRemaining: 10000000,
TokensPercentage: 95,
TokensNextResetTime: &resetBefore,
TimeUsage: 1000,
TimeCurrentValue: 900,
}
db.InsertZaiSnapshot(snap1)
zaiTr.Process(snap1)
// Second snapshot: reset occurred (new reset time, low usage)
snap2 := &api.ZaiSnapshot{
CapturedAt: now.Add(2 * time.Minute),
TokensUsage: 200000000,
TokensCurrentValue: 1000000,
TokensRemaining: 199000000,
TokensPercentage: 0,
TokensNextResetTime: &resetAfter,
TimeUsage: 1000,
TimeCurrentValue: 5,
}
db.InsertZaiSnapshot(snap2)
zaiTr.Process(snap2)
// Verify completed cycle exists
cycles, err := db.QueryZaiCycleHistory("tokens")
if err != nil {
t.Fatalf("QueryZaiCycleHistory: %v", err)
}
if len(cycles) < 1 {
t.Fatal("Expected at least 1 completed tokens cycle")
}
// Peak should be 190000000
if cycles[0].PeakValue != 190000000 {
t.Errorf("Peak value: want 190000000, got %d", cycles[0].PeakValue)
}
}
// TestIntegration_Zai_BodyLevel401 verifies parsing of Z.ai body-level 401 responses.
func TestIntegration_Zai_BodyLevel401(t *testing.T) {
authErrJSON := testutil.ZaiAuthErrorResponse()
_, err := api.ParseZaiResponse([]byte(authErrJSON))
if err == nil {
t.Fatal("Expected error for body-level 401")
}
if !strings.Contains(err.Error(), "token expired or incorrect") {
t.Errorf("Error should contain 'token expired or incorrect', got: %s", err.Error())