Skip to content

Commit e6d9f57

Browse files
committed
feat: increase test cov
1 parent 1eb2afb commit e6d9f57

File tree

7 files changed

+679
-109
lines changed

7 files changed

+679
-109
lines changed

document_test.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,59 @@ func TestDocumentTokenLiteral(t *testing.T) {
2525
t.Errorf("expected empty string, got %q", got)
2626
}
2727
}
28+
29+
func TestOperationDefinitionTokenLiteral(t *testing.T) {
30+
// When Name is provided, TokenLiteral should return it.
31+
opWithName := &OperationDefinition{
32+
Operation: "query",
33+
Name: "GetUser",
34+
}
35+
if got := opWithName.TokenLiteral(); got != "GetUser" {
36+
t.Errorf("expected 'GetUser', got %q", got)
37+
}
38+
39+
// When Name is empty, TokenLiteral should return Operation.
40+
opWithoutName := &OperationDefinition{
41+
Operation: "mutation",
42+
Name: "",
43+
}
44+
if got := opWithoutName.TokenLiteral(); got != "mutation" {
45+
t.Errorf("expected 'mutation', got %q", got)
46+
}
47+
}
48+
49+
func TestVariableDefinitionTokenLiteral(t *testing.T) {
50+
varDef := &VariableDefinition{
51+
Variable: "$id",
52+
}
53+
if got := varDef.TokenLiteral(); got != "$id" {
54+
t.Errorf("expected '$id', got %q", got)
55+
}
56+
}
57+
58+
func TestFieldTokenLiteral(t *testing.T) {
59+
field := &Field{
60+
Name: "username",
61+
}
62+
if got := field.TokenLiteral(); got != "username" {
63+
t.Errorf("expected 'username', got %q", got)
64+
}
65+
}
66+
67+
func TestArgumentTokenLiteral(t *testing.T) {
68+
arg := &Argument{
69+
Name: "limit",
70+
}
71+
if got := arg.TokenLiteral(); got != "limit" {
72+
t.Errorf("expected 'limit', got %q", got)
73+
}
74+
}
75+
76+
func TestTypeDefinitionTokenLiteral(t *testing.T) {
77+
typeDef := &TypeDefinition{
78+
Name: "Query",
79+
}
80+
if got := typeDef.TokenLiteral(); got != "Query" {
81+
t.Errorf("expected 'Query', got %q", got)
82+
}
83+
}

graphql_test.go

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -530,33 +530,6 @@ func TestGraphqlHandler_MissingQueryField(t *testing.T) {
530530
}
531531
}
532532

533-
func TestOperationDefinitionTokenLiteral(t *testing.T) {
534-
// When a name is provided.
535-
op := &OperationDefinition{Operation: "query", Name: "MyQuery"}
536-
if op.TokenLiteral() != "MyQuery" {
537-
t.Errorf("expected TokenLiteral to be 'MyQuery', got %q", op.TokenLiteral())
538-
}
539-
// When no name is provided.
540-
op = &OperationDefinition{Operation: "query", Name: ""}
541-
if op.TokenLiteral() != "query" {
542-
t.Errorf("expected TokenLiteral to be 'query', got %q", op.TokenLiteral())
543-
}
544-
}
545-
546-
func TestFieldTokenLiteral(t *testing.T) {
547-
field := &Field{Name: "testField"}
548-
if field.TokenLiteral() != "testField" {
549-
t.Errorf("expected TokenLiteral to be 'testField', got %q", field.TokenLiteral())
550-
}
551-
}
552-
553-
func TestArgumentTokenLiteral(t *testing.T) {
554-
arg := &Argument{Name: "arg1"}
555-
if arg.TokenLiteral() != "arg1" {
556-
t.Errorf("expected TokenLiteral to be 'arg1', got %q", arg.TokenLiteral())
557-
}
558-
}
559-
560533
func TestValueTokenLiteral(t *testing.T) {
561534
val := &Value{Literal: "value"}
562535
if val.TokenLiteral() != "value" {
@@ -745,15 +718,6 @@ func TestParseValue_Illegal(t *testing.T) {
745718
}
746719
}
747720

748-
// Test resolveField when no resolver is found for a top-level field.
749-
func TestResolveField_NoResolver(t *testing.T) {
750-
field := &Field{Name: "nonexistent"}
751-
_, err := resolveField(nil, field, nil)
752-
if err == nil {
753-
t.Error("expected error when no resolver is found for field 'nonexistent'")
754-
}
755-
}
756-
757721
// Test executeSelectionSet to skip non-Field selections.
758722
type dummySel struct{}
759723

handler_test.go

Lines changed: 165 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,51 @@ package vibeGraphql
33
import (
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

Comments
 (0)