Debian Codegraph @

client/service/service_test.go

raw
1 /*
2 Copyright 2014 Canonical Ltd.
3
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License version 3, as published
6 by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful, but
9 WITHOUT ANY WARRANTY; without even the implied warranties of
10 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 PURPOSE. See the GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License along
14 with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 package service
18
19 import (
20 "encoding/json"
21 "fmt"
22 "io"
23 "net/http"
24 "net/http/httptest"
25 "os"
26 "testing"
27
28 . "gopkg.in/check.v1"
29 "github.com/godbus/dbus/v5"
30
31 "gitlab.com/ubports/development/core/lomiri-push-service/bus"
32 testibus "gitlab.com/ubports/development/core/lomiri-push-service/bus/testing"
33 "gitlab.com/ubports/development/core/lomiri-push-service/click"
34 "gitlab.com/ubports/development/core/lomiri-push-service/logger"
35 "gitlab.com/ubports/development/core/lomiri-push-service/nih"
36 helpers "gitlab.com/ubports/development/core/lomiri-push-service/testing"
37 "gitlab.com/ubports/development/core/lomiri-push-service/testing/condition"
38 )
39
40 func TestService(t *testing.T) {
41 TestingT(t)
42 }
43
44 type serviceSuite struct {
45 log logger.Logger
46 bus bus.Endpoint
47 }
48
49 var _ = Suite(&serviceSuite{})
50
51 var (
52 aPackage = "com.example.test"
53 anAppId = aPackage + "_test-number-one"
54 aPackageOnBus = "/" + string(nih.Quote([]byte(aPackage)))
55 )
56
57 var aMsg = dbus.Message{
58 Type: dbus.TypeMethodCall,
59 Headers: map[dbus.HeaderField]dbus.Variant{
60 dbus.FieldPath: dbus.MakeVariant(aPackageOnBus),
61 },
62 }
63
64 func (ss *serviceSuite) SetUpTest(c *C) {
65 ss.log = helpers.NewTestLogger(c, "debug")
66 ss.bus = testibus.NewTestingEndpoint(condition.Work(true), nil)
67 }
68
69 var testSetup = &PushServiceSetup{}
70
71 func (ss *serviceSuite) TestBuild(c *C) {
72 setup := &PushServiceSetup{
73 RegURL: helpers.ParseURL("http://reg"),
74 DeviceId: "FOO",
75 }
76 svc := NewPushService(setup, ss.log)
77 c.Check(svc.regURL, DeepEquals, helpers.ParseURL("http://reg"))
78 // ...
79 }
80
81 func (ss *serviceSuite) TestStart(c *C) {
82 svc := NewPushService(testSetup, ss.log)
83 svc.Bus = ss.bus
84 c.Check(svc.IsRunning(), Equals, false)
85 c.Check(svc.Start(), IsNil)
86 c.Check(svc.IsRunning(), Equals, true)
87 svc.Stop()
88 }
89
90 func (ss *serviceSuite) TestStartTwice(c *C) {
91 svc := NewPushService(testSetup, ss.log)
92 svc.Bus = ss.bus
93 c.Check(svc.Start(), IsNil)
94 c.Check(svc.Start(), Equals, ErrAlreadyStarted)
95 svc.Stop()
96 }
97
98 func (ss *serviceSuite) TestStartNoLog(c *C) {
99 svc := NewPushService(testSetup, nil)
100 svc.Bus = ss.bus
101 c.Check(svc.Start(), Equals, ErrNotConfigured)
102 }
103
104 func (ss *serviceSuite) TestStartNoBus(c *C) {
105 svc := NewPushService(testSetup, ss.log)
106 svc.Bus = nil
107 c.Check(svc.Start(), Equals, ErrNotConfigured)
108 }
109
110 func (ss *serviceSuite) TestStartFailsOnBusDialFailure(c *C) {
111 bus := testibus.NewTestingEndpoint(condition.Work(false), nil)
112 svc := NewPushService(testSetup, ss.log)
113 svc.Bus = bus
114 c.Check(svc.Start(), ErrorMatches, `.*(?i)cond said no.*`)
115 svc.Stop()
116 }
117
118 func (ss *serviceSuite) TestStartGrabsName(c *C) {
119 svc := NewPushService(testSetup, ss.log)
120 svc.Bus = ss.bus
121 c.Assert(svc.Start(), IsNil)
122 callArgs := testibus.GetCallArgs(ss.bus)
123 defer svc.Stop()
124 c.Assert(callArgs, NotNil)
125 c.Check(callArgs[0].Member, Equals, "::GrabName")
126 }
127
128 func (ss *serviceSuite) TestStopClosesBus(c *C) {
129 svc := NewPushService(testSetup, ss.log)
130 svc.Bus = ss.bus
131 c.Assert(svc.Start(), IsNil)
132 svc.Stop()
133 callArgs := testibus.GetCallArgs(ss.bus)
134 c.Assert(callArgs, NotNil)
135 c.Check(callArgs[len(callArgs)-1].Member, Equals, "::Close")
136 }
137
138 // registration tests
139
140 func (ss *serviceSuite) TestGetRegUrlWorks(c *C) {
141 setup := &PushServiceSetup{
142 RegURL: helpers.ParseURL("http://foo"),
143 }
144 svc := NewPushService(setup, ss.log)
145 svc.Bus = ss.bus
146 url := svc.getParsedUrl("/op")
147 c.Check(url, Equals, "http://foo/op")
148 }
149
150 func (ss *serviceSuite) TestGetRegUrlDoesNotPanic(c *C) {
151 svc := NewPushService(testSetup, ss.log)
152 svc.Bus = ss.bus
153 url := svc.getParsedUrl("/op")
154 c.Check(url, Equals, "")
155 }
156
157 func (ss *serviceSuite) TestRegistrationAndUnregistrationFailIfBadArgs(c *C) {
158 msg := dbus.Message{
159 Type: dbus.TypeMethodCall,
160 Headers: map[dbus.HeaderField]dbus.Variant{
161 dbus.FieldPath: dbus.MakeVariant("/bar"),
162 },
163 }
164 reg, err := new(PushService).register(msg, "foo")
165 c.Check(reg, Equals, "")
166 c.Check(err, DeepEquals, MakeDBusNoObjectErrorWithReason("/bar", click.ErrInvalidAppId))
167
168 err = new(PushService).unregister(msg, "foo")
169 c.Check(err, DeepEquals, MakeDBusNoObjectErrorWithReason("/bar", click.ErrInvalidAppId))
170 }
171
172 func (ss *serviceSuite) TestRegistrationWorks(c *C) {
173 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
174 buf := make([]byte, 256)
175 n := r.ContentLength
176 _, e := io.ReadFull(r.Body, buf[:n])
177 c.Assert(e, IsNil)
178 req := registrationRequest{}
179 c.Assert(json.Unmarshal(buf[:n], &req), IsNil)
180 c.Check(req, DeepEquals, registrationRequest{"fake-device-id", anAppId})
181 c.Check(r.URL.Path, Equals, "/register")
182 w.Header().Set("Content-Type", "application/json")
183 fmt.Fprintln(w, `{"ok":true,"token":"blob-of-bytes"}`)
184 }))
185 defer ts.Close()
186 setup := &PushServiceSetup{
187 DeviceId: "fake-device-id",
188 RegURL: helpers.ParseURL(ts.URL),
189 }
190 svc := NewPushService(setup, ss.log)
191 svc.Bus = ss.bus
192 // this'll check (un)quoting, too
193 reg, err := svc.register(aMsg, anAppId)
194 c.Assert(err, IsNil)
195 c.Check(reg, Equals, "blob-of-bytes")
196 }
197
198 func (ss *serviceSuite) TestRegistrationOverrideWorks(c *C) {
199 envar := "PUSH_REG_" + string(nih.Quote([]byte(anAppId)))
200 os.Setenv(envar, "42")
201 defer os.Setenv(envar, "")
202
203 reg, err := new(PushService).register(aMsg, anAppId)
204 c.Check(reg, Equals, "42")
205 c.Check(err, IsNil)
206 }
207
208 func (ss *serviceSuite) TestManageRegFailsOnNoServer(c *C) {
209 setup := &PushServiceSetup{
210 DeviceId: "fake-device-id",
211 RegURL: helpers.ParseURL("xyzzy://"),
212 }
213 svc := NewPushService(setup, ss.log)
214 svc.Bus = ss.bus
215 reg, err := svc.register(aMsg, anAppId)
216 c.Check(reg, Equals, "")
217 c.Check(err.Name, Equals, "org.freedesktop.DBus.Error.Failed")
218 c.Check(err.Body[0], Matches, "unable to request registration: .*")
219 }
220
221 func (ss *serviceSuite) TestManageRegFailsOn401(c *C) {
222 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
223 http.Error(w, "Unauthorized", 401)
224 }))
225 defer ts.Close()
226 setup := &PushServiceSetup{
227 DeviceId: "fake-device-id",
228 RegURL: helpers.ParseURL(ts.URL),
229 }
230 svc := NewPushService(setup, ss.log)
231 svc.Bus = ss.bus
232 reg, err := svc.register(aMsg, anAppId)
233 c.Check(err, DeepEquals, dbus.MakeFailedError(ErrBadAuth))
234 c.Check(reg, Equals, "")
235 }
236
237 func (ss *serviceSuite) TestManageRegFailsOn40x(c *C) {
238 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
239 http.Error(w, "I'm a teapot", 418)
240 }))
241 defer ts.Close()
242 setup := &PushServiceSetup{
243 DeviceId: "fake-device-id",
244 RegURL: helpers.ParseURL(ts.URL),
245 }
246 svc := NewPushService(setup, ss.log)
247 svc.Bus = ss.bus
248 reg, err := svc.register(aMsg, anAppId)
249 c.Check(err, DeepEquals, dbus.MakeFailedError(ErrBadRequest))
250 c.Check(reg, Equals, "")
251 }
252
253 func (ss *serviceSuite) TestManageRegFailsOn50x(c *C) {
254 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
255 http.Error(w, "Not implemented", 501)
256 }))
257 defer ts.Close()
258 setup := &PushServiceSetup{
259 DeviceId: "fake-device-id",
260 RegURL: helpers.ParseURL(ts.URL),
261 }
262 svc := NewPushService(setup, ss.log)
263 svc.Bus = ss.bus
264 reg, err := svc.register(aMsg, anAppId)
265 c.Check(err, DeepEquals, dbus.MakeFailedError(ErrBadServer))
266 c.Check(reg, Equals, "")
267 }
268
269 func (ss *serviceSuite) TestManageRegFailsOnBadJSON(c *C) {
270 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
271 buf := make([]byte, 256)
272 n := r.ContentLength
273 _, e := io.ReadFull(r.Body, buf[:n])
274 c.Assert(e, IsNil)
275 req := registrationRequest{}
276 c.Assert(json.Unmarshal(buf[:n], &req), IsNil)
277 c.Check(req, DeepEquals, registrationRequest{"fake-device-id", anAppId})
278
279 w.Header().Set("Content-Type", "application/json")
280 fmt.Fprintln(w, `{`)
281 }))
282 defer ts.Close()
283 setup := &PushServiceSetup{
284 DeviceId: "fake-device-id",
285 RegURL: helpers.ParseURL(ts.URL),
286 }
287 svc := NewPushService(setup, ss.log)
288 svc.Bus = ss.bus
289 // this'll check (un)quoting, too
290 reg, err := svc.register(aMsg, anAppId)
291 c.Check(reg, Equals, "")
292 c.Check(err.Name, Equals, "org.freedesktop.DBus.Error.Failed")
293 c.Check(err.Body[0], Matches, "unable to unmarshal register response: .*")
294 }
295
296 func (ss *serviceSuite) TestManageRegFailsOnBadJSONDocument(c *C) {
297 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
298 buf := make([]byte, 256)
299 n := r.ContentLength
300 _, e := io.ReadFull(r.Body, buf[:n])
301 c.Assert(e, IsNil)
302 req := registrationRequest{}
303 c.Assert(json.Unmarshal(buf[:n], &req), IsNil)
304 c.Check(req, DeepEquals, registrationRequest{"fake-device-id", anAppId})
305
306 w.Header().Set("Content-Type", "application/json")
307 fmt.Fprintln(w, `{"bananas": "very yes"}`)
308 }))
309 defer ts.Close()
310 setup := &PushServiceSetup{
311 DeviceId: "fake-device-id",
312 RegURL: helpers.ParseURL(ts.URL),
313 }
314 svc := NewPushService(setup, ss.log)
315 svc.Bus = ss.bus
316 // this'll check (un)quoting, too
317 reg, err := svc.register(aMsg, anAppId)
318 c.Check(reg, Equals, "")
319 c.Check(err, DeepEquals, dbus.MakeFailedError(ErrBadToken))
320 }
321
322 func (ss *serviceSuite) TestDBusUnregisterWorks(c *C) {
323 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
324 buf := make([]byte, 256)
325 n := r.ContentLength
326 _, e := io.ReadFull(r.Body, buf[:n])
327 c.Assert(e, IsNil)
328 req := registrationRequest{}
329 c.Assert(json.Unmarshal(buf[:n], &req), IsNil)
330 c.Check(req, DeepEquals, registrationRequest{"fake-device-id", anAppId})
331 c.Check(r.URL.Path, Equals, "/unregister")
332 w.Header().Set("Content-Type", "application/json")
333 fmt.Fprintln(w, `{"ok":true,"token":"blob-of-bytes"}`)
334 }))
335 defer ts.Close()
336 setup := &PushServiceSetup{
337 DeviceId: "fake-device-id",
338 RegURL: helpers.ParseURL(ts.URL),
339 }
340 svc := NewPushService(setup, ss.log)
341 svc.Bus = ss.bus
342 // this'll check (un)quoting, too
343 err := svc.unregister(aMsg, anAppId)
344 c.Assert(err, IsNil)
345 }
346
347 func (ss *serviceSuite) TestUnregistrationWorks(c *C) {
348 invoked := make(chan bool, 1)
349 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
350 buf := make([]byte, 256)
351 n := r.ContentLength
352 _, e := io.ReadFull(r.Body, buf[:n])
353 c.Assert(e, IsNil)
354 req := registrationRequest{}
355 c.Assert(json.Unmarshal(buf[:n], &req), IsNil)
356 c.Check(req, DeepEquals, registrationRequest{"fake-device-id", anAppId})
357 c.Check(r.URL.Path, Equals, "/unregister")
358 invoked <- true
359 w.Header().Set("Content-Type", "application/json")
360 fmt.Fprintln(w, `{"ok":true}`)
361 }))
362 defer ts.Close()
363 setup := &PushServiceSetup{
364 DeviceId: "fake-device-id",
365 RegURL: helpers.ParseURL(ts.URL),
366 }
367 svc := NewPushService(setup, ss.log)
368 svc.Bus = ss.bus
369 err := svc.Unregister(anAppId)
370 c.Assert(err, IsNil)
371 c.Check(invoked, HasLen, 1)
372 }