-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient_test.go
More file actions
1205 lines (1010 loc) · 32.6 KB
/
client_test.go
File metadata and controls
1205 lines (1010 loc) · 32.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
package epo_ops
import (
"context"
"embed"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
//go:embed testdata/*.xml
var testdata embed.FS
// loadTestData loads an XML file from the embedded testdata directory
func loadTestData(filename string) []byte {
data, err := testdata.ReadFile("testdata/" + filename)
if err != nil {
panic("Failed to load test data: " + filename + " - " + err.Error())
}
return data
}
// Mock OAuth2 server
func newMockAuthServer(t *testing.T) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/auth/accesstoken" {
t.Errorf("Unexpected auth path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
// Check authorization header
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Basic ") {
t.Errorf("Missing or invalid Authorization header: %s", auth)
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"access_token":"test_token_12345","expires_in":"3600"}`))
}))
}
// Mock OPS API server
func newMockOPSServer(t *testing.T, handler http.HandlerFunc) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check authorization header
auth := r.Header.Get("Authorization")
if auth != "Bearer test_token_12345" {
t.Errorf("Invalid bearer token: %s", auth)
w.WriteHeader(http.StatusUnauthorized)
return
}
// Add quota headers (format: "used=123,quota=456")
w.Header().Set("X-Throttling-Control", "green")
w.Header().Set("X-IndividualQuota", "used=1000000,quota=4000000000")
handler(w, r)
}))
}
// Test client initialization
func TestNewClient(t *testing.T) {
t.Run("Valid configuration", func(t *testing.T) {
config := &Config{
ConsumerKey: "test-key",
ConsumerSecret: "test-secret",
}
client, err := NewClient(config)
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
if client == nil {
t.Fatal("Expected client, got nil")
}
if client.config.ConsumerKey != "test-key" {
t.Errorf("Expected ConsumerKey 'test-key', got: %s", client.config.ConsumerKey)
}
})
t.Run("Nil config uses defaults", func(t *testing.T) {
config := DefaultConfig()
config.ConsumerKey = "test"
config.ConsumerSecret = "test"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
if client.config.MaxRetries != 3 {
t.Errorf("Expected MaxRetries 3, got: %d", client.config.MaxRetries)
}
if client.config.Timeout != 30*time.Second {
t.Errorf("Expected Timeout 30s, got: %v", client.config.Timeout)
}
})
t.Run("Missing credentials", func(t *testing.T) {
config := &Config{}
_, err := NewClient(config)
if err == nil {
t.Error("Expected error for missing credentials")
}
if _, ok := err.(*ConfigError); !ok {
t.Errorf("Expected ConfigError, got: %T", err)
}
})
}
// Test text retrieval endpoints
func TestGetBiblio(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/biblio") {
t.Errorf("Unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("biblio.xml"))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
// Override auth URL for testing
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
biblio, err := client.GetBiblio(ctx, "publication", "docdb", "EP.1000000.B1")
if err != nil {
t.Fatalf("GetBiblio failed: %v", err)
}
if biblio.PatentNumber == "" {
t.Errorf("Expected patent number to be parsed")
}
if biblio.FamilyID == "" {
t.Errorf("Expected family ID to be parsed")
}
}
func TestGetClaims(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/claims") {
t.Errorf("Unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("claims.xml"))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
claims, err := client.GetClaims(ctx, "publication", "docdb", "EP.1000000.B1")
if err != nil {
t.Fatalf("GetClaims failed: %v", err)
}
if claims.PatentNumber == "" {
t.Errorf("Expected patent number to be parsed")
}
if len(claims.Claims) == 0 {
t.Errorf("Expected claims to be parsed")
}
}
func TestGetDescription(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/description") {
t.Errorf("Unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("description.xml"))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
desc, err := client.GetDescription(ctx, "publication", "docdb", "EP.1000000.B1")
if err != nil {
t.Fatalf("GetDescription failed: %v", err)
}
if desc == nil {
t.Fatal("Expected parsed description data, got nil")
}
if len(desc.Paragraphs) == 0 {
t.Errorf("Expected paragraphs in description data")
}
}
func TestGetAbstract(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/abstract") {
t.Errorf("Unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("abstract.xml"))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
abstract, err := client.GetAbstract(ctx, "publication", "docdb", "EP.1000000.B1")
if err != nil {
t.Fatalf("GetAbstract failed: %v", err)
}
if abstract.PatentNumber == "" {
t.Errorf("Expected patent number to be parsed")
}
if abstract.Text == "" {
t.Errorf("Expected abstract text to be parsed")
}
}
// Test search endpoints
func TestSearch(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/search") {
t.Errorf("Unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
query := r.URL.Query().Get("q")
if query == "" {
t.Error("Missing query parameter")
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("search.xml"))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
results, err := client.Search(ctx, "ti=battery", "1-5")
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if results == nil {
t.Fatal("Expected parsed search results, got nil")
}
if results.TotalCount == 0 {
t.Errorf("Expected non-zero total count in search results")
}
if len(results.Results) == 0 {
t.Errorf("Expected search results")
}
}
// Test family endpoints
func TestGetFamily(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/family") {
t.Errorf("Unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("family.xml"))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
family, err := client.GetFamily(ctx, "publication", "docdb", "EP.1000000.B1")
if err != nil {
t.Fatalf("GetFamily failed: %v", err)
}
if family == nil {
t.Fatal("Expected parsed family data, got nil")
}
if len(family.Members) == 0 {
t.Errorf("Expected family members in family data")
}
// FamilyID is optional in the API response, so we don't assert on it
}
// Test image endpoints
func TestGetImage(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
// Mock TIFF header (little-endian)
mockTIFF := []byte{0x49, 0x49, 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00}
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/images/") {
t.Errorf("Unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "image/tiff")
_, _ = w.Write(mockTIFF)
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
imageData, err := client.GetImage(ctx, "EP", "1000000", "B1", "Drawing", 1)
if err != nil {
t.Fatalf("GetImage failed: %v", err)
}
if len(imageData) == 0 {
t.Error("Expected image data, got empty response")
}
// Check TIFF header
if len(imageData) >= 4 && (imageData[0] != 'I' || imageData[1] != 'I') {
t.Errorf("Expected TIFF header, got: %v", imageData[:4])
}
}
// Test legal and register endpoints
func TestGetLegal(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/legal") {
t.Errorf("Unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("legal.xml"))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
legal, err := client.GetLegal(ctx, "publication", "docdb", "EP.1000000.B1")
if err != nil {
t.Fatalf("GetLegal failed: %v", err)
}
if legal == nil {
t.Fatal("Expected parsed legal data, got nil")
}
if len(legal.LegalEvents) == 0 {
t.Errorf("Expected legal events in legal data")
}
}
// Test error handling
func TestErrorHandling(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
t.Run("404 Not Found", func(t *testing.T) {
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write(loadTestData("error_404.xml"))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
_, err = client.GetBiblio(ctx, "publication", "docdb", "EP.99999999.A1")
if err == nil {
t.Error("Expected error for 404 response")
}
if _, ok := err.(*NotFoundError); !ok {
t.Errorf("Expected NotFoundError, got: %T", err)
}
})
t.Run("503 Service Unavailable", func(t *testing.T) {
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte(`Service temporarily unavailable`))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
MaxRetries: 0, // Disable retries for this test
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
_, err = client.GetBiblio(ctx, "publication", "docdb", "EP.1000000.B1")
if err == nil {
t.Error("Expected error for 503 response")
}
if _, ok := err.(*ServiceUnavailableError); !ok {
t.Errorf("Expected ServiceUnavailableError, got: %T", err)
}
})
t.Run("429 Quota Exceeded", func(t *testing.T) {
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Throttling-Control", "black")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write(loadTestData("error_429.xml"))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
_, err = client.GetBiblio(ctx, "publication", "docdb", "EP.1000000.B1")
if err == nil {
t.Error("Expected error for 429 response")
}
if _, ok := err.(*QuotaExceededError); !ok {
t.Errorf("Expected QuotaExceededError, got: %T", err)
}
})
}
// Test quota tracking
func TestQuotaTracking(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Throttling-Control", "green")
w.Header().Set("X-IndividualQuota", "used=1234567,quota=4000000000")
w.Header().Set("X-RegisteredQuota", "used=5000000,quota=10000000000")
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?>
<ops:world-patent-data xmlns:ops="http://ops.epo.org">
<exchange-document></exchange-document>
</ops:world-patent-data>`))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
// Quota should be nil before any request
quota := client.GetLastQuota()
if quota != nil {
t.Error("Expected nil quota before first request")
}
ctx := context.Background()
_, err = client.GetBiblio(ctx, "publication", "docdb", "EP.1000000.B1")
if err != nil {
t.Fatalf("GetBiblio failed: %v", err)
}
// Quota should be populated after request
quota = client.GetLastQuota()
if quota == nil {
t.Fatal("Expected quota after request")
}
if quota.Status != "green" {
t.Errorf("Expected status 'green', got: %s", quota.Status)
}
if quota.Individual.Used != 1234567 {
t.Errorf("Expected Individual.Used 1234567, got: %d", quota.Individual.Used)
}
if quota.Individual.Limit != 4000000000 {
t.Errorf("Expected Individual.Limit 4000000000, got: %d", quota.Individual.Limit)
}
if quota.Registered.Used != 5000000 {
t.Errorf("Expected Registered.Used 5000000, got: %d", quota.Registered.Used)
}
usagePercent := quota.Individual.UsagePercent()
if usagePercent < 0.03 || usagePercent > 0.04 {
t.Errorf("Expected usage percent around 0.03%%, got: %.2f%%", usagePercent)
}
}
// Test GetUsageStats
func TestGetUsageStats(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
// Check that it's the usage stats endpoint
if !strings.Contains(r.URL.Path, "/stats/usage") {
t.Errorf("Unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
// Return mock JSON usage stats
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{
"data": [
{"timestamp": 1640995200, "total_response_size": 1048576, "message_count": 10},
{"timestamp": 1641081600, "total_response_size": 2097152, "message_count": 20}
]
}`))
})
defer opsServer.Close()
config := DefaultConfig()
config.ConsumerKey = "test"
config.ConsumerSecret = "test"
config.BaseURL = opsServer.URL
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, _ := NewClient(config)
ctx := context.Background()
stats, err := client.GetUsageStats(ctx, "01/01/2022")
if err != nil {
t.Fatalf("GetUsageStats failed: %v", err)
}
if stats == nil {
t.Fatal("Expected usage stats, got nil")
}
if len(stats.Entries) != 2 {
t.Errorf("Expected 2 usage entries, got: %d", len(stats.Entries))
}
if stats.Entries[0].TotalResponseSize != 1048576 {
t.Errorf("Expected first entry size 1048576, got: %d", stats.Entries[0].TotalResponseSize)
}
}
// Test context cancellation
func TestContextCancellation(t *testing.T) {
authServer := newMockAuthServer(t)
defer authServer.Close()
// Create a slow server
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
time.Sleep(200 * time.Millisecond)
_, _ = w.Write([]byte(`<data></data>`))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
Timeout: 10 * time.Millisecond, // Very short timeout
MaxRetries: 0, // No retries
RetryDelay: 1 * time.Nanosecond, // Fast failure
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
_, err = client.GetBiblio(ctx, "publication", "docdb", "EP.1000000.B1")
if err == nil {
t.Error("Expected timeout error")
}
// Verify it's a timeout-related error
if err != nil && !strings.Contains(err.Error(), "timeout") && !strings.Contains(err.Error(), "context deadline exceeded") {
t.Logf("Got error (acceptable): %v", err)
}
}
// Test token refresh on 401
func TestTokenRefreshOn401(t *testing.T) {
authCallCount := 0
authServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authCallCount++
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"access_token":"test_token_12345","expires_in":"3600"}`))
}))
defer authServer.Close()
requestCount := 0
opsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCount++
// First request returns 401, second succeeds
if requestCount == 1 {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`Unauthorized`))
return
}
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("biblio.xml"))
}))
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
_, err = client.GetBiblio(ctx, "publication", "docdb", "EP.1000000.B1")
if err != nil {
t.Fatalf("Expected success after token refresh, got: %v", err)
}
// Should have made 2 auth calls (initial + refresh after 401)
if authCallCount != 2 {
t.Errorf("Expected 2 auth calls, got: %d", authCallCount)
}
// Should have made 2 API requests (first 401, second success)
if requestCount != 2 {
t.Errorf("Expected 2 API requests, got: %d", requestCount)
}
}
// Benchmark tests
func BenchmarkGetBiblio(b *testing.B) {
authServer := newMockAuthServer(&testing.T{})
defer authServer.Close()
opsServer := newMockOPSServer(&testing.T{}, func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`<data>test</data>`))
})
defer opsServer.Close()
config := &Config{
ConsumerKey: "test",
ConsumerSecret: "test",
BaseURL: opsServer.URL,
}
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, _ := NewClient(config)
ctx := context.Background()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = client.GetBiblio(ctx, "publication", "docdb", "EP.1000000.B1")
}
}
// TestGetAcceptHeader tests the Accept header selection for different endpoints
func TestGetAcceptHeader(t *testing.T) {
tests := []struct {
endpoint string
want string
}{
{EndpointBiblio, "application/exchange+xml"},
{EndpointAbstract, "application/exchange+xml"},
{EndpointFulltext, "application/fulltext+xml"},
{EndpointClaims, "application/fulltext+xml"},
{EndpointDescription, "application/fulltext+xml"},
{EndpointFamily, "application/ops+xml"},
{EndpointLegal, "application/ops+xml"},
{EndpointSearch, "application/ops+xml"},
{EndpointRegister, "application/register+xml"},
{EndpointImages, "application/tiff"},
{"unknown", "application/xml"},
}
for _, tt := range tests {
t.Run(tt.endpoint, func(t *testing.T) {
got := getAcceptHeader(tt.endpoint)
if got != tt.want {
t.Errorf("getAcceptHeader(%s) = %s, want %s", tt.endpoint, got, tt.want)
}
})
}
}
// TestGetEndpointFromPath tests endpoint extraction from URL paths
func TestGetEndpointFromPath(t *testing.T) {
tests := []struct {
path string
want string
}{
{"/rest-services/published-data/publication/epodoc/EP1000000/biblio", EndpointBiblio},
{"/rest-services/published-data/publication/docdb/EP.1000000.B1/abstract", EndpointAbstract},
{"/rest-services/published-data/publication/epodoc/EP1000000/claims", EndpointClaims},
{"/rest-services/published-data/publication/epodoc/EP1000000/description", EndpointDescription},
{"/rest-services/published-data/publication/epodoc/EP1000000/fulltext", EndpointFulltext},
{"/rest-services/family/publication/docdb/EP.1000000.B1/biblio", EndpointFamily},
{"/rest-services/legal/publication/docdb/EP.1000000.B1", EndpointLegal},
{"/rest-services/register/publication/epodoc/EP1000000", EndpointRegister},
{"/rest-services/published-data/search?q=test", EndpointSearch},
{"/rest-services/published-data/images/EP/1000000/A1/fullimage", EndpointImages},
{"/unknown/path", ""},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
got := getEndpointFromPath(tt.path)
if got != tt.want {
t.Errorf("getEndpointFromPath(%s) = %s, want %s", tt.path, got, tt.want)
}
})
}
}
// TestAcceptHeaderIntegration tests that Accept headers are correctly set in actual requests
func TestAcceptHeaderIntegration(t *testing.T) {
// Mock auth server
authServer := newMockAuthServer(t)
defer authServer.Close()
// Track captured Accept headers
var capturedHeaders []string
// Mock OPS server that captures Accept headers
opsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedHeaders = append(capturedHeaders, r.Header.Get("Accept"))
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("biblio.xml"))
}))
defer opsServer.Close()
config := DefaultConfig()
config.ConsumerKey = "test"
config.ConsumerSecret = "test"
config.BaseURL = opsServer.URL
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
ctx := context.Background()
// Test biblio endpoint
_, err = client.GetBiblioRaw(ctx, RefTypePublication, FormatDocDB, "EP.1000000.B1")
if err != nil {
t.Fatalf("GetBiblioRaw failed: %v", err)
}
// Verify Accept header was set (should be application/exchange+xml for biblio)
if len(capturedHeaders) == 0 {
t.Fatal("No Accept headers captured")
}
lastHeader := capturedHeaders[len(capturedHeaders)-1]
expectedHeader := "application/exchange+xml"
if lastHeader != expectedHeader {
t.Errorf("Expected Accept header %s, got %s", expectedHeader, lastHeader)
}
}
// TestFormatBulkBody tests the formatBulkBody helper
func TestFormatBulkBody(t *testing.T) {
tests := []struct {
name string
numbers []string
expected string
}{
{
name: "Single number",
numbers: []string{"EP.1000000.B1"},
expected: "EP.1000000.B1",
},
{
name: "Multiple numbers",
numbers: []string{"EP.1000000.B1", "EP.1000001.A1", "US.5551212.A"},
expected: "EP.1000000.B1\nEP.1000001.A1\nUS.5551212.A",
},
{
name: "Empty slice",
numbers: []string{},
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := formatBulkBody(tt.numbers)
if result != tt.expected {
t.Errorf("formatBulkBody() = %q, want %q", result, tt.expected)
}
})
}
}
// TestGetBiblioMultiple tests bulk bibliographic data retrieval
func TestGetBiblioMultiple(t *testing.T) {
// Mock auth server
authServer := newMockAuthServer(t)
defer authServer.Close()
// Mock OPS server
opsServer := newMockOPSServer(t, func(w http.ResponseWriter, r *http.Request) {
// Verify it's a POST request
if r.Method != "POST" {
t.Errorf("Expected POST request, got %s", r.Method)
}
// Verify Content-Type header
contentType := r.Header.Get("Content-Type")
if contentType != "text/plain" {
t.Errorf("Expected Content-Type 'text/plain', got %s", contentType)
}
// Read and verify body
body, _ := io.ReadAll(r.Body)
bodyStr := string(body)
expectedBody := "EP.1000000.B1\nEP.1000001.A1"
if bodyStr != expectedBody {
t.Errorf("Expected body %q, got %q", expectedBody, bodyStr)
}
// Return sample biblio XML
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write(loadTestData("biblio.xml"))
})
defer opsServer.Close()
config := DefaultConfig()
config.ConsumerKey = "test"
config.ConsumerSecret = "test"
config.BaseURL = opsServer.URL
config.AuthURL = authServer.URL + "/auth/accesstoken"
client, err := NewClient(config)