-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension_test.go
77 lines (61 loc) · 2.5 KB
/
extension_test.go
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
package complexityreporter_test
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
complexityreporter "github.com/basemachina/gqlgen-complexity-reporter"
"github.com/stretchr/testify/require"
"github.com/99designs/gqlgen/graphql/handler/testserver"
"github.com/99designs/gqlgen/graphql/handler/transport"
)
type testReporter struct {
complexity int
}
func (t *testReporter) ReportComplexity(ctx context.Context, _ string, complexity int) {
t.complexity = complexity
}
func TestReportComplexity(t *testing.T) {
h := testserver.New()
h.AddTransport(&transport.POST{})
t.Run("always report", func(t *testing.T) {
reporter := &testReporter{complexity: 0}
h.Use(complexityreporter.NewExtension(reporter))
h.SetCalculatedComplexity(2)
resp := doRequest(h, "POST", "/graphql", `{"query":"{ name }"}`)
require.Equal(t, http.StatusOK, resp.Code, resp.Body.String())
require.Equal(t, 2, reporter.complexity)
})
t.Run("below complexity threshold", func(t *testing.T) {
reporter := &testReporter{complexity: 0}
h.Use(complexityreporter.NewExtension(reporter, complexityreporter.WithThreshold(2)))
h.SetCalculatedComplexity(2)
resp := doRequest(h, "POST", "/graphql", `{"query":"{ name }"}`)
require.Equal(t, http.StatusOK, resp.Code, resp.Body.String())
require.Equal(t, 0, reporter.complexity)
})
t.Run("above complexity threshold", func(t *testing.T) {
reporter := &testReporter{complexity: 0}
h.Use(complexityreporter.NewExtension(reporter, complexityreporter.WithThreshold(2)))
h.SetCalculatedComplexity(4)
resp := doRequest(h, "POST", "/graphql", `{"query":"{ name }"}`)
require.Equal(t, http.StatusOK, resp.Code, resp.Body.String())
require.Equal(t, 4, reporter.complexity)
})
t.Run("bypass __schema field", func(t *testing.T) {
reporter := &testReporter{complexity: 0}
h.Use(complexityreporter.NewExtension(reporter, complexityreporter.WithThreshold(2)))
h.SetCalculatedComplexity(4)
resp := doRequest(h, "POST", "/graphql", `{ "operationName":"IntrospectionQuery", "query":"query IntrospectionQuery { __schema { queryType { name } mutationType { name }}}"}`)
require.Equal(t, http.StatusOK, resp.Code, resp.Body.String())
require.Equal(t, 0, reporter.complexity)
})
}
func doRequest(handler http.Handler, method string, target string, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, target, strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
return w
}