@@ -3,20 +3,51 @@ package vibeGraphql
33import (
44 "bytes"
55 "encoding/json"
6+ "mime/multipart"
67 "net/http"
78 "net/http/httptest"
89 "testing"
910)
1011
11- func TestGraphqlHandler (t * testing.T ) {
12- // Register a simple query resolver for testing.
13- RegisterQueryResolver ("hello" , func (source interface {}, args map [string ]interface {}) (interface {}, error ) {
14- return "world" , nil
15- })
12+ func TestBuildValue_Object (t * testing.T ) {
13+ objValue := & Value {
14+ Kind : "Object" ,
15+ ObjectFields : map [string ]* Value {
16+ "key" : {Kind : "String" , Literal : "value" },
17+ "num" : {Kind : "Int" , Literal : "42" },
18+ },
19+ }
20+ result := buildValue (objValue , nil )
21+ m , ok := result .(map [string ]interface {})
22+ if ! ok {
23+ t .Fatalf ("expected map[string]interface{}, got %T" , result )
24+ }
25+ if m ["key" ] != "value" {
26+ t .Errorf ("expected key 'value', got %v" , m ["key" ])
27+ }
28+ // buildValue for Int converts to int.
29+ if m ["num" ] != 42 {
30+ t .Errorf ("expected num 42, got %v" , m ["num" ])
31+ }
32+ }
33+
34+ func TestGraphqlHandler_InvalidJSON (t * testing.T ) {
35+ req := httptest .NewRequest ("POST" , "/graphql" , bytes .NewBuffer ([]byte ("invalid json" )))
36+ w := httptest .NewRecorder ()
37+
38+ GraphqlHandler (w , req )
39+ resp := w .Result ()
40+ defer resp .Body .Close ()
41+
42+ if resp .StatusCode != http .StatusBadRequest {
43+ t .Errorf ("expected status 400 for invalid JSON, got %d" , resp .StatusCode )
44+ }
45+ }
1646
17- // Prepare a test GraphQL query.
47+ func TestGraphqlHandler_NoQuery (t * testing.T ) {
48+ // Send a JSON payload without the "query" field.
1849 payload := map [string ]interface {}{
19- "query " : "{ hello } " ,
50+ "notQuery " : "test " ,
2051 }
2152 body , err := json .Marshal (payload )
2253 if err != nil {
@@ -30,20 +61,140 @@ func TestGraphqlHandler(t *testing.T) {
3061 resp := w .Result ()
3162 defer resp .Body .Close ()
3263
33- if resp .StatusCode != http .StatusOK {
34- t .Errorf ("expected status 200, got %d" , resp .StatusCode )
64+ // When query is missing, the parser will likely create an empty document and return an error.
65+ if resp .StatusCode != http .StatusInternalServerError {
66+ t .Errorf ("expected status 500 for missing query, got %d" , resp .StatusCode )
3567 }
68+ }
3669
37- var result map [string ]interface {}
38- if err := json .NewDecoder (resp .Body ).Decode (& result ); err != nil {
39- t .Fatalf ("error decoding response: %v" , err )
70+ func TestGraphqlUploadHandler_MissingOperations (t * testing.T ) {
71+ // Simulate a multipart request missing the "operations" field.
72+ var buf bytes.Buffer
73+ writer := multipart .NewWriter (& buf )
74+ // Create a dummy file field.
75+ part , err := writer .CreateFormFile ("file1" , "dummy.txt" )
76+ if err != nil {
77+ t .Fatalf ("failed to create form file: %v" , err )
78+ }
79+ part .Write ([]byte ("dummy content" ))
80+ writer .Close ()
81+
82+ req := httptest .NewRequest ("POST" , "/graphql/upload" , & buf )
83+ req .Header .Set ("Content-Type" , "multipart/form-data; boundary=" + writer .Boundary ())
84+
85+ w := httptest .NewRecorder ()
86+ GraphqlUploadHandler (w , req )
87+ resp := w .Result ()
88+ defer resp .Body .Close ()
89+
90+ if resp .StatusCode != http .StatusBadRequest {
91+ t .Errorf ("expected status 400 for missing operations field, got %d" , resp .StatusCode )
92+ }
93+ }
94+
95+ func TestGraphqlUploadHandler_InvalidMap (t * testing.T ) {
96+ // Simulate a multipart request with invalid JSON in the "map" field.
97+ var buf bytes.Buffer
98+ writer := multipart .NewWriter (& buf )
99+ // Write a valid operations field.
100+ writer .WriteField ("operations" , `{"query": "{ hello }", "variables": {}}` )
101+ // Write an invalid map field.
102+ writer .WriteField ("map" , "not a valid json" )
103+ writer .Close ()
104+
105+ req := httptest .NewRequest ("POST" , "/graphql/upload" , & buf )
106+ req .Header .Set ("Content-Type" , "multipart/form-data; boundary=" + writer .Boundary ())
107+
108+ w := httptest .NewRecorder ()
109+ GraphqlUploadHandler (w , req )
110+ resp := w .Result ()
111+ defer resp .Body .Close ()
112+
113+ if resp .StatusCode != http .StatusBadRequest {
114+ t .Errorf ("expected status 400 for invalid map JSON, got %d" , resp .StatusCode )
115+ }
116+ }
117+
118+ func TestSetNestedValueAndArrayValue (t * testing.T ) {
119+ var vars = make (map [string ]interface {})
120+ // Test setting a nested value.
121+ setNestedValue (vars , "user.name" , "Alice" )
122+ if vars ["user" ] == nil {
123+ t .Fatal ("expected nested map for user" )
124+ }
125+ userMap , ok := vars ["user" ].(map [string ]interface {})
126+ if ! ok {
127+ t .Fatalf ("expected map for user, got %T" , vars ["user" ])
128+ }
129+ if userMap ["name" ] != "Alice" {
130+ t .Errorf ("expected user.name to be 'Alice', got %v" , userMap ["name" ])
40131 }
41132
133+ // Test setting an array value.
134+ setNestedArrayValue (vars , "files.0" , "file1.txt" )
135+ arr , ok := vars ["files" ].([]interface {})
136+ if ! ok {
137+ t .Fatalf ("expected files to be an array, got %T" , vars ["files" ])
138+ }
139+ if arr [0 ] != "file1.txt" {
140+ t .Errorf ("expected files[0] to be 'file1.txt', got %v" , arr [0 ])
141+ }
142+ }
143+
144+ func TestExecuteDocument_NoDefinitions (t * testing.T ) {
145+ // Create a Document with no definitions.
146+ doc := & Document {}
147+ _ , err := executeDocument (doc , nil )
148+ if err == nil {
149+ t .Error ("expected error for document with no definitions, got nil" )
150+ }
151+ }
152+
153+ func TestResolveField_NoResolver (t * testing.T ) {
154+ // Ensure that resolveField returns an error when no resolver is registered.
155+ field := & Field {Name : "nonexistent" }
156+ _ , err := resolveField (nil , field , nil )
157+ if err == nil {
158+ t .Error ("expected error for unresolved field, got nil" )
159+ }
160+ }
161+
162+ func dummyHelloResolver (source interface {}, args map [string ]interface {}) (interface {}, error ) {
163+ return "world" , nil
164+ }
165+
166+ func TestGraphqlHandler (t * testing.T ) {
167+ // Register the dummy resolver for the "hello" field.
168+ QueryResolvers ["hello" ] = dummyHelloResolver
169+
170+ // Create a GraphQL query that requests the "hello" field.
171+ reqBody , err := json .Marshal (map [string ]interface {}{
172+ "query" : "query { hello }" ,
173+ })
174+ if err != nil {
175+ t .Fatalf ("failed to marshal request body: %v" , err )
176+ }
177+ req := httptest .NewRequest ("POST" , "/graphql" , bytes .NewBuffer (reqBody ))
178+ req .Header .Set ("Content-Type" , "application/json" )
179+
180+ // Create a ResponseRecorder to capture the response.
181+ rr := httptest .NewRecorder ()
182+ GraphqlHandler (rr , req )
183+
184+ res := rr .Result ()
185+ if res .StatusCode != http .StatusOK {
186+ t .Errorf ("expected status OK, got %v" , res .StatusCode )
187+ }
188+
189+ var result map [string ]interface {}
190+ if err := json .NewDecoder (res .Body ).Decode (& result ); err != nil {
191+ t .Fatalf ("failed to decode response body: %v" , err )
192+ }
42193 data , ok := result ["data" ].(map [string ]interface {})
43194 if ! ok {
44- t .Fatalf ("expected data to be a map, got %v" , result [ "data" ] )
195+ t .Fatalf ("expected response to contain 'data' field" )
45196 }
46197 if data ["hello" ] != "world" {
47- t .Errorf ("expected hello: world, got %v" , data ["hello" ])
198+ t .Errorf ("expected field ' hello' to be ' world' , got %v" , data ["hello" ])
48199 }
49200}
0 commit comments