This repository has been archived by the owner on May 2, 2021. It is now read-only.
forked from functionalfoundry/graphqlws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscriptions_e2e_test.go
213 lines (177 loc) · 5.75 KB
/
subscriptions_e2e_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
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
package graphqlws_test
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/graphql-go/graphql"
log "github.com/sirupsen/logrus"
"github.com/wahed-tech/graphqlws"
)
var wsMountPath = "/subscriptions"
var subscriptionName = "StaticString"
func TestSubscriptions(t *testing.T) {
testedValue := "1231331313"
numberOfMessages := 3
log.Infof("Building schema")
schema, err := buildSchema()
if err != nil {
t.Errorf("could not build graphql schema: " + err.Error())
t.FailNow()
}
subscriptionManager := graphqlws.NewSubscriptionManager(schema)
srv := startServer(subscriptionManager)
defer srv.Close()
port := ":" + strings.Split(srv.URL, ":")[2]
log.Infof("Starting server on port: %s", port)
graphqlWsHeader := http.Header{}
graphqlWsHeader["Sec-WebSocket-Protocol"] = []string{"graphql-ws"}
webSocketConnectUrl := "ws://localhost" + port + wsMountPath
log.Infof("Connecting WebSocket client to %s", webSocketConnectUrl)
webSocketClient, resp, err := websocket.DefaultDialer.Dial(webSocketConnectUrl, graphqlWsHeader)
if err != nil {
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
responseBody := buf.String()
t.Errorf("couldn't connect to websocket resource: '%s', response: '%s'", err.Error(), responseBody)
t.FailNow()
}
defer webSocketClient.Close()
queryMessage := fmt.Sprintf(`{
"id": "1",
"type": "start",
"payload": {
"variables": {},
"extensions": {},
"operationName": null,
"query": "subscription { %s { payload } }"
}
}`, subscriptionName)
log.Infof("Subscribing for %s events", subscriptionName)
err = webSocketClient.WriteMessage(websocket.TextMessage, []byte(queryMessage))
if err != nil {
t.Errorf("could not subscribe to events: %s", err.Error())
t.FailNow()
}
messageChannel := make(chan string, numberOfMessages)
log.Infof("Listening for websocket events")
go listenForMessages(webSocketClient, messageChannel, numberOfMessages)
time.Sleep(500 * time.Millisecond)
payload := map[string]interface{}{
"payload": testedValue,
}
for i := 0; i < numberOfMessages; i++ {
triggerSubscription(payload, schema, subscriptionManager)
}
expectedMessage := fmt.Sprintf("{\"id\":\"1\",\"type\":\"data\",\"payload\":{\"data\":{\"%s\":{\"payload\":\"%s\"}},\"errors\":null}}", subscriptionName, testedValue)
for i := 0; i < numberOfMessages; i++ {
receivedMessage := <-messageChannel
receivedMessage = strings.Replace(receivedMessage, "\n", "", -1)
if receivedMessage != expectedMessage {
t.Errorf("unexpected value received: '%s', expected: '%s'", receivedMessage, expectedMessage)
}
}
}
func listenForMessages(webSocketClient *websocket.Conn, messageChannel chan string, maxNumberOfMessages int) {
messagesProcessed := 0
for {
_, message, err := webSocketClient.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
messagesProcessed++
messageChannel <- string(message)
if messagesProcessed == maxNumberOfMessages {
return
}
}
}
func triggerSubscription(payload map[string]interface{}, schema *graphql.Schema, manager graphqlws.SubscriptionManager) error {
allSubscriptions := manager.Subscriptions()
sameQuerySubscriptionsMap := make(map[string][]*graphqlws.Subscription)
for connection := range allSubscriptions {
for _, subscription := range allSubscriptions[connection] {
for _, field := range subscription.Fields {
if field == subscriptionName {
sameQuerySubscriptionsMap[subscription.Query] = append(sameQuerySubscriptionsMap[subscription.Query], subscription)
}
}
}
}
for _, sameQuerySubscriptions := range sameQuerySubscriptionsMap {
var subscriptionData *graphqlws.DataMessagePayload
for _, subscription := range sameQuerySubscriptions {
if subscriptionData == nil {
ctx := context.Background()
params := graphql.Params{
Schema: *schema,
RequestString: subscription.Query,
VariableValues: subscription.Variables,
OperationName: subscription.OperationName,
Context: ctx,
RootObject: payload,
}
result := graphql.Do(params)
subscriptionData = &graphqlws.DataMessagePayload{
Data: result.Data,
Errors: graphqlws.ErrorsFromGraphQLErrors(result.Errors),
}
}
subscription.SendData(subscriptionData)
}
}
return nil
}
func startServer(subscriptionManager graphqlws.SubscriptionManager) *httptest.Server {
websocketHandler := graphqlws.NewHandler(graphqlws.HandlerConfig{
SubscriptionManager: subscriptionManager,
})
srv := httptest.NewServer(websocketHandler)
time.Sleep(500 * time.Millisecond)
return srv
}
func defineSubscriptionSchema() graphql.Fields {
subscriptions := make(graphql.Fields)
randomStringSubscription := &graphql.Field{
Type: graphql.NewObject(graphql.ObjectConfig{
Name: "StaticStringSubscriptionPayload",
Fields: graphql.Fields{
"payload": &graphql.Field{
Type: graphql.NewNonNull(graphql.String),
},
},
}),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Source, nil
},
}
subscriptions[subscriptionName] = randomStringSubscription
return subscriptions
}
func buildSchema() (*graphql.Schema, error) {
fields := graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "world", nil
},
},
}
rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
rootSubscription := graphql.ObjectConfig{Name: "RootSubscription", Fields: defineSubscriptionSchema()}
schemaConfig := graphql.SchemaConfig{
Query: graphql.NewObject(rootQuery),
Subscription: graphql.NewObject(rootSubscription),
}
schema, err := graphql.NewSchema(schemaConfig)
if err != nil {
return nil, err
}
return &schema, nil
}