-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_test.go
More file actions
1938 lines (1669 loc) · 45.2 KB
/
Copy pathgraph_test.go
File metadata and controls
1938 lines (1669 loc) · 45.2 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 graph
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/graphql-go/graphql"
)
// Test Utility Functions
func TestGetArgString(t *testing.T) {
tests := []struct {
name string
args map[string]interface{}
key string
want string
wantError bool
}{
{
name: "valid string argument",
args: map[string]interface{}{"name": "John"},
key: "name",
want: "John",
wantError: false,
},
{
name: "missing argument",
args: map[string]interface{}{},
key: "name",
want: "",
wantError: true,
},
{
name: "wrong type argument",
args: map[string]interface{}{"name": 123},
key: "name",
want: "",
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
params := graphql.ResolveParams{Args: tt.args}
got, err := GetArgString(ResolveParams(params), tt.key)
if (err != nil) != tt.wantError {
t.Errorf("GetArgString() error = %v, wantError %v", err, tt.wantError)
return
}
if got != tt.want {
t.Errorf("GetArgString() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetArgInt(t *testing.T) {
tests := []struct {
name string
args map[string]interface{}
key string
want int
wantError bool
}{
{
name: "valid int argument",
args: map[string]interface{}{"age": 30},
key: "age",
want: 30,
wantError: false,
},
{
name: "missing argument",
args: map[string]interface{}{},
key: "age",
want: 0,
wantError: true,
},
{
name: "wrong type argument",
args: map[string]interface{}{"age": "thirty"},
key: "age",
want: 0,
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
params := graphql.ResolveParams{Args: tt.args}
got, err := GetArgInt(ResolveParams(params), tt.key)
if (err != nil) != tt.wantError {
t.Errorf("GetArgInt() error = %v, wantError %v", err, tt.wantError)
return
}
if got != tt.want {
t.Errorf("GetArgInt() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetArgBool(t *testing.T) {
tests := []struct {
name string
args map[string]interface{}
key string
want bool
wantError bool
}{
{
name: "valid bool argument true",
args: map[string]interface{}{"active": true},
key: "active",
want: true,
wantError: false,
},
{
name: "valid bool argument false",
args: map[string]interface{}{"active": false},
key: "active",
want: false,
wantError: false,
},
{
name: "missing argument",
args: map[string]interface{}{},
key: "active",
want: false,
wantError: true,
},
{
name: "wrong type argument",
args: map[string]interface{}{"active": "yes"},
key: "active",
want: false,
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
params := graphql.ResolveParams{Args: tt.args}
got, err := GetArgBool(ResolveParams(params), tt.key)
if (err != nil) != tt.wantError {
t.Errorf("GetArgBool() error = %v, wantError %v", err, tt.wantError)
return
}
if got != tt.want {
t.Errorf("GetArgBool() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetArg(t *testing.T) {
type Input struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
tests := []struct {
name string
args map[string]interface{}
key string
want Input
wantError bool
}{
{
name: "valid complex argument",
args: map[string]interface{}{
"input": map[string]interface{}{
"name": "John",
"email": "john@example.com",
"age": float64(30),
},
},
key: "input",
want: Input{Name: "John", Email: "john@example.com", Age: 30},
wantError: false,
},
{
name: "missing argument",
args: map[string]interface{}{},
key: "input",
want: Input{},
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
params := graphql.ResolveParams{Args: tt.args}
var got Input
err := GetArg(ResolveParams(params), tt.key, &got)
if (err != nil) != tt.wantError {
t.Errorf("GetArg() error = %v, wantError %v", err, tt.wantError)
return
}
if !tt.wantError && got != tt.want {
t.Errorf("GetArg() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetRootString(t *testing.T) {
tests := []struct {
name string
rootValue map[string]interface{}
key string
want string
wantError bool
}{
{
name: "valid root string",
rootValue: map[string]interface{}{"token": "abc123"},
key: "token",
want: "abc123",
wantError: false,
},
{
name: "missing key",
rootValue: map[string]interface{}{},
key: "token",
want: "",
wantError: true,
},
{
name: "wrong type",
rootValue: map[string]interface{}{"token": 123},
key: "token",
want: "",
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: tt.rootValue,
},
}
got, err := GetRootString(ResolveParams(params), tt.key)
if (err != nil) != tt.wantError {
t.Errorf("GetRootString() error = %v, wantError %v", err, tt.wantError)
return
}
if got != tt.want {
t.Errorf("GetRootString() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetRootInfo(t *testing.T) {
type UserDetails struct {
ID int `json:"id"`
Name string `json:"name"`
}
tests := []struct {
name string
rootValue map[string]interface{}
key string
want UserDetails
wantError bool
}{
{
name: "valid root info",
rootValue: map[string]interface{}{
"details": map[string]interface{}{
"id": float64(1),
"name": "John",
},
},
key: "details",
want: UserDetails{ID: 1, Name: "John"},
wantError: false,
},
{
name: "missing key",
rootValue: map[string]interface{}{},
key: "details",
want: UserDetails{},
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: tt.rootValue,
},
}
var got UserDetails
err := GetRootInfo(ResolveParams(params), tt.key, &got)
if (err != nil) != tt.wantError {
t.Errorf("GetRootInfo() error = %v, wantError %v", err, tt.wantError)
return
}
if !tt.wantError && got != tt.want {
t.Errorf("GetRootInfo() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetRoot(t *testing.T) {
type UserDetails struct {
ID int `json:"id"`
Name string `json:"name"`
}
t.Run("GetRoot with string", func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: map[string]interface{}{
"token": "abc123",
},
},
}
rootInfo := NewRootInfo(ResolveParams(params))
got := GetRoot[string](rootInfo, "token")
if got != "abc123" {
t.Errorf("GetRoot[string]() = %v, want %v", got, "abc123")
}
})
t.Run("GetRoot with missing key returns zero value", func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: map[string]interface{}{},
},
}
rootInfo := NewRootInfo(ResolveParams(params))
got := GetRoot[string](rootInfo, "token")
if got != "" {
t.Errorf("GetRoot[string]() = %v, want empty string", got)
}
})
t.Run("GetRoot with struct", func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: map[string]interface{}{
"details": map[string]interface{}{
"id": float64(1),
"name": "John",
},
},
},
}
rootInfo := NewRootInfo(ResolveParams(params))
got := GetRoot[UserDetails](rootInfo, "details")
want := UserDetails{ID: 1, Name: "John"}
if got != want {
t.Errorf("GetRoot[UserDetails]() = %v, want %v", got, want)
}
})
t.Run("GetRootE with error", func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: map[string]interface{}{},
},
}
rootInfo := NewRootInfo(ResolveParams(params))
_, err := GetRootE[string](rootInfo, "missing")
if err == nil {
t.Error("GetRootE() expected error for missing key")
}
})
t.Run("GetRootE with nil root info", func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: nil,
},
}
rootInfo := NewRootInfo(ResolveParams(params))
_, err := GetRootE[string](rootInfo, "token")
if err == nil {
t.Error("GetRootE() expected error for nil root info")
}
})
t.Run("GetRootOr with default value", func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: map[string]interface{}{},
},
}
rootInfo := NewRootInfo(ResolveParams(params))
got := GetRootOr[string](rootInfo, "token", "default")
if got != "default" {
t.Errorf("GetRootOr[string]() = %v, want %v", got, "default")
}
})
t.Run("GetRootOr with existing value", func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: map[string]interface{}{
"token": "actual",
},
},
}
rootInfo := NewRootInfo(ResolveParams(params))
got := GetRootOr[string](rootInfo, "token", "default")
if got != "actual" {
t.Errorf("GetRootOr[string]() = %v, want %v", got, "actual")
}
})
t.Run("MustGetRoot panics on missing key", func(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("MustGetRoot() expected panic for missing key")
}
}()
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: map[string]interface{}{},
},
}
rootInfo := NewRootInfo(ResolveParams(params))
_ = MustGetRoot[string](rootInfo, "missing")
})
t.Run("MustGetRoot succeeds with valid key", func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: map[string]interface{}{
"token": "valid",
},
},
}
rootInfo := NewRootInfo(ResolveParams(params))
got := MustGetRoot[string](rootInfo, "token")
if got != "valid" {
t.Errorf("MustGetRoot[string]() = %v, want %v", got, "valid")
}
})
t.Run("GetRoot with int conversion", func(t *testing.T) {
params := graphql.ResolveParams{
Info: graphql.ResolveInfo{
RootValue: map[string]interface{}{
"userID": float64(42),
},
},
}
rootInfo := NewRootInfo(ResolveParams(params))
got := GetRoot[int](rootInfo, "userID")
if got != 42 {
t.Errorf("GetRoot[int]() = %v, want %v", got, 42)
}
})
}
// Test Token Extraction
func TestExtractBearerToken(t *testing.T) {
tests := []struct {
name string
header string
want string
}{
{
name: "valid bearer token",
header: "Bearer abc123def456",
want: "abc123def456",
},
{
name: "valid bearer token with extra spaces",
header: "Bearer abc123def456",
want: "abc123def456",
},
{
name: "no bearer prefix",
header: "abc123def456",
want: "",
},
{
name: "empty header",
header: "",
want: "",
},
{
name: "bearer only",
header: "Bearer",
want: "",
},
{
name: "lowercase bearer",
header: "bearer abc123def456",
want: "abc123def456",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/graphql", nil)
if tt.header != "" {
req.Header.Set("Authorization", tt.header)
}
got := ExtractBearerToken(req)
if got != tt.want {
t.Errorf("ExtractBearerToken() = %v, want %v", got, tt.want)
}
})
}
}
// Test Schema Builder
func TestSchemaBuilder_Simple(t *testing.T) {
params := SchemaBuilderParams{
QueryFields: []QueryField{
getDefaultHelloQuery(),
},
MutationFields: []MutationField{
getDefaultEchoMutation(),
},
}
schema, err := NewSchemaBuilder(params).Build()
if err != nil {
t.Fatalf("NewSchemaBuilder().Build() error = %v", err)
}
if schema.QueryType() == nil {
t.Error("Schema should have query type")
}
if schema.MutationType() == nil {
t.Error("Schema should have mutation type")
}
}
func TestSchemaBuilder_WithCustomTypes(t *testing.T) {
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
params := SchemaBuilderParams{
QueryFields: []QueryField{
NewResolver[User]("user").
WithArgs(graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{Type: graphql.Int},
}).
WithResolver(func(p ResolveParams) (*User, error) {
return &User{ID: 1, Name: "Test"}, nil
}).BuildQuery(),
},
}
schema, err := NewSchemaBuilder(params).Build()
if err != nil {
t.Fatalf("NewSchemaBuilder().Build() error = %v", err)
}
if schema.QueryType() == nil {
t.Error("Schema should have query type")
}
}
// Test Resolver Creation
func TestNewResolver_Simple(t *testing.T) {
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
field := NewResolver[User]("user").
WithResolver(func(p ResolveParams) (*User, error) {
return &User{ID: 1, Name: "Test"}, nil
}).BuildQuery()
if field.Name() != "user" {
t.Errorf("Field name = %v, want user", field.Name())
}
graphqlField := field.Serve()
if graphqlField.Type == nil {
t.Error("Field type should not be nil")
}
if graphqlField.Resolve == nil {
t.Error("Field resolve function should not be nil")
}
}
func TestNewResolver_WithArgs(t *testing.T) {
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
field := NewResolver[User]("user").
WithArgs(graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{Type: graphql.Int},
}).
WithResolver(func(p ResolveParams) (*User, error) {
return &User{ID: 1, Name: "Test"}, nil
}).BuildQuery()
graphqlField := field.Serve()
if graphqlField.Args == nil {
t.Error("Field args should not be nil")
}
if _, ok := graphqlField.Args["id"]; !ok {
t.Error("Field should have 'id' argument")
}
}
func TestNewResolver_AsList(t *testing.T) {
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
field := NewResolver[[]User]("users").
AsList().
WithResolver(func(p ResolveParams) (*[]User, error) {
users := []User{{ID: 1, Name: "Test"}}
return &users, nil
}).BuildQuery()
if field.Name() != "users" {
t.Errorf("Field name = %v, want users", field.Name())
}
graphqlField := field.Serve()
if graphqlField.Type == nil {
t.Error("Field type should not be nil")
}
}
func TestNewResolver_AsPaginated(t *testing.T) {
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
field := NewResolver[PaginatedResponse[User]]("users").
AsPaginated().
WithResolver(func(p ResolveParams) (*PaginatedResponse[User], error) {
response := PaginatedResponse[User]{
Items: []User{{ID: 1, Name: "Test"}},
TotalCount: 1,
PageInfo: PageInfo{
HasNextPage: false,
HasPreviousPage: false,
},
}
return &response, nil
}).BuildQuery()
if field.Name() != "users" {
t.Errorf("Field name = %v, want users", field.Name())
}
graphqlField := field.Serve()
if graphqlField.Type == nil {
t.Error("Field type should not be nil")
}
}
func TestNewResolver_SliceOfStrings_WithoutAsList(t *testing.T) {
// Test that NewResolver[[]string] works without calling AsList()
field := NewResolver[[]string]("tags").
WithResolver(func(p ResolveParams) (*[]string, error) {
tags := []string{"go", "graphql", "test"}
return &tags, nil
}).BuildQuery()
if field.Name() != "tags" {
t.Errorf("Field name = %v, want tags", field.Name())
}
graphqlField := field.Serve()
if graphqlField.Type == nil {
t.Error("Field type should not be nil")
}
// Verify it's a list type
listType, ok := graphqlField.Type.(*graphql.List)
if !ok {
t.Errorf("Expected list type, got %T", graphqlField.Type)
return
}
// Verify the element type is String
if listType.OfType != graphql.String {
t.Errorf("Expected list of String, got list of %v", listType.OfType)
}
// Test resolver execution
schema, err := NewSchemaBuilder(SchemaBuilderParams{
QueryFields: []QueryField{field},
}).Build()
if err != nil {
t.Fatalf("Failed to build schema: %v", err)
}
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: `{ tags }`,
})
if len(result.Errors) > 0 {
t.Errorf("Query returned errors: %v", result.Errors)
}
data, ok := result.Data.(map[string]interface{})
if !ok {
t.Fatalf("Expected map result, got %T", result.Data)
}
tags, ok := data["tags"].([]interface{})
if !ok {
t.Fatalf("Expected []interface{} for tags, got %T", data["tags"])
}
if len(tags) != 3 {
t.Errorf("Expected 3 tags, got %d", len(tags))
}
expectedTags := []string{"go", "graphql", "test"}
for i, tag := range tags {
if tag != expectedTags[i] {
t.Errorf("Tag[%d] = %v, want %v", i, tag, expectedTags[i])
}
}
}
func TestNewResolver_SliceOfInts_WithoutAsList(t *testing.T) {
// Test that NewResolver[[]int] works without calling AsList()
field := NewResolver[[]int]("numbers").
WithResolver(func(p ResolveParams) (*[]int, error) {
numbers := []int{1, 2, 3, 4, 5}
return &numbers, nil
}).BuildQuery()
if field.Name() != "numbers" {
t.Errorf("Field name = %v, want numbers", field.Name())
}
graphqlField := field.Serve()
if graphqlField.Type == nil {
t.Error("Field type should not be nil")
}
// Verify it's a list type
listType, ok := graphqlField.Type.(*graphql.List)
if !ok {
t.Errorf("Expected list type, got %T", graphqlField.Type)
return
}
// Verify the element type is Int
if listType.OfType != graphql.Int {
t.Errorf("Expected list of Int, got list of %v", listType.OfType)
}
// Test resolver execution
schema, err := NewSchemaBuilder(SchemaBuilderParams{
QueryFields: []QueryField{field},
}).Build()
if err != nil {
t.Fatalf("Failed to build schema: %v", err)
}
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: `{ numbers }`,
})
if len(result.Errors) > 0 {
t.Errorf("Query returned errors: %v", result.Errors)
}
data, ok := result.Data.(map[string]interface{})
if !ok {
t.Fatalf("Expected map result, got %T", result.Data)
}
numbers, ok := data["numbers"].([]interface{})
if !ok {
t.Fatalf("Expected []interface{} for numbers, got %T", data["numbers"])
}
if len(numbers) != 5 {
t.Errorf("Expected 5 numbers, got %d", len(numbers))
}
}
// Test Query Validation
func TestValidateGraphQLQuery_SimpleQuery(t *testing.T) {
schema, _ := NewSchemaBuilder(SchemaBuilderParams{
QueryFields: []QueryField{getDefaultHelloQuery()},
}).Build()
tests := []struct {
name string
query string
wantError bool
}{
{
name: "valid simple query",
query: `{ hello }`,
wantError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateGraphQLQuery(tt.query, &schema)
if (err != nil) != tt.wantError {
t.Errorf("ValidateGraphQLQuery() error = %v, wantError %v", err, tt.wantError)
}
})
}
}
func TestValidateGraphQLQuery_MaxDepth(t *testing.T) {
schema, _ := NewSchemaBuilder(SchemaBuilderParams{
QueryFields: []QueryField{getDefaultHelloQuery()},
}).Build()
// Deep query that exceeds max depth (10 levels)
query := `{
level1 {
level2 {
level3 {
level4 {
level5 {
level6 {
level7 {
level8 {
level9 {
level10 {
level11
}
}
}
}
}
}
}
}
}
}
}`
err := ValidateGraphQLQuery(query, &schema)
if err == nil {
t.Error("ValidateGraphQLQuery() should reject queries exceeding max depth")
}
}
func TestValidateGraphQLQuery_MaxAliases(t *testing.T) {
schema, _ := NewSchemaBuilder(SchemaBuilderParams{
QueryFields: []QueryField{getDefaultHelloQuery()},
}).Build()
// Query with too many aliases (more than 4)
query := `{
alias1: hello
alias2: hello
alias3: hello
alias4: hello
alias5: hello
}`
err := ValidateGraphQLQuery(query, &schema)
if err == nil {
t.Error("ValidateGraphQLQuery() should reject queries with too many aliases")
}
}
func TestValidateGraphQLQuery_Introspection(t *testing.T) {
schema, _ := NewSchemaBuilder(SchemaBuilderParams{
QueryFields: []QueryField{getDefaultHelloQuery()},
}).Build()
tests := []struct {
name string
query string
}{
{
name: "introspection __schema",
query: `{ __schema { types { name } } }`,
},
{
name: "introspection __type",
query: `{ __type(name: "Query") { name } }`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateGraphQLQuery(tt.query, &schema)
if err == nil {
t.Error("ValidateGraphQLQuery() should block introspection")
}
// Just check that an error was returned - the exact message may vary
})
}
}
// Test HTTP Handler
func TestNewHTTP_DefaultSchema(t *testing.T) {
graphCtx := &GraphContext{
DEBUG: true,
Playground: true,
}
handler := NewHTTP(graphCtx)
if handler == nil {
t.Fatal("NewHTTP() should return a handler")
}
// Test POST request
body := bytes.NewBufferString(`{"query":"{ hello }"}`)
req := httptest.NewRequest(http.MethodPost, "/graphql", body)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("Status code = %v, want %v", w.Code, http.StatusOK)
}
var response map[string]interface{}
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
if data, ok := response["data"].(map[string]interface{}); !ok {
t.Error("Response should have 'data' field")
} else if hello, ok := data["hello"].(string); !ok || hello == "" {
t.Error("Response should have 'hello' field with value")
}
}
func TestNewHTTP_WithAuth(t *testing.T) {
graphCtx := &GraphContext{
DEBUG: true,
UserDetailsFn: func(ctx context.Context, token string) (context.Context, interface{}, error) {
return ctx, map[string]interface{}{"id": 1, "name": "Test User"}, nil
},
}
handler := NewHTTP(graphCtx)
body := bytes.NewBufferString(`{"query":"{ hello }"}`)
req := httptest.NewRequest(http.MethodPost, "/graphql", body)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer test-token-123")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("Status code = %v, want %v", w.Code, http.StatusOK)
}
}
func TestNewHTTP_GET(t *testing.T) {
graphCtx := &GraphContext{
DEBUG: true,
Playground: true,
}
handler := NewHTTP(graphCtx)