-
Notifications
You must be signed in to change notification settings - Fork 0
/
dispatch_test.go
88 lines (67 loc) · 2.2 KB
/
dispatch_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
// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package rpc_test
import (
"fmt"
"net/http"
"net/http/httptest"
"code.google.com/p/go.net/websocket"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/juju/rpc"
"github.com/juju/juju/rpc/jsoncodec"
)
type dispatchSuite struct {
server *httptest.Server
serverAddr string
ready chan struct{}
}
var _ = gc.Suite(&dispatchSuite{})
func (s *dispatchSuite) SetUpSuite(c *gc.C) {
rpcServer := func(ws *websocket.Conn) {
codec := jsoncodec.NewWebsocket(ws)
conn := rpc.NewConn(codec, nil)
conn.Serve(&DispatchRoot{}, nil)
conn.Start()
<-conn.Dead()
}
http.Handle("/rpc", websocket.Handler(rpcServer))
s.server = httptest.NewServer(nil)
s.serverAddr = s.server.Listener.Addr().String()
s.ready = make(chan struct{}, 1)
}
func (s *dispatchSuite) TearDownSuite(c *gc.C) {
s.server.Close()
}
func (s *dispatchSuite) TestWSWithoutParams(c *gc.C) {
resp := s.request(c, `{"RequestId":1,"Type": "DispatchDummy","Id": "without","Request":"DoSomething"}`)
c.Assert(resp, gc.Equals, `{"RequestId":1,"Response":{}}`)
}
func (s *dispatchSuite) TestWSWithParams(c *gc.C) {
resp := s.request(c, `{"RequestId":2,"Type": "DispatchDummy","Id": "with","Request":"DoSomething", "Params": {}}`)
c.Assert(resp, gc.Equals, `{"RequestId":2,"Response":{}}`)
}
// request performs one request to the test server via websockets.
func (s *dispatchSuite) request(c *gc.C, req string) string {
url := fmt.Sprintf("ws://%s/rpc", s.serverAddr)
ws, err := websocket.Dial(url, "", "http://localhost")
c.Assert(err, jc.ErrorIsNil)
reqdata := []byte(req)
_, err = ws.Write(reqdata)
c.Assert(err, jc.ErrorIsNil)
var resp = make([]byte, 512)
n, err := ws.Read(resp)
c.Assert(err, jc.ErrorIsNil)
resp = resp[0:n]
err = ws.Close()
c.Assert(err, jc.ErrorIsNil)
return string(resp)
}
// DispatchRoot simulates the root for the test.
type DispatchRoot struct{}
func (*DispatchRoot) DispatchDummy(id string) (*DispatchDummy, error) {
return &DispatchDummy{}, nil
}
// DispatchDummy is the type to whish the request is dispatched.
type DispatchDummy struct{}
func (d *DispatchDummy) DoSomething() {}