Debian Codegraph @

client/service/postal_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 "errors"
22 "fmt"
23 "io/ioutil"
24 "os"
25 "path/filepath"
26 "sort"
27 "sync"
28 "time"
29
30 . "gopkg.in/check.v1"
31 "github.com/godbus/dbus/v5"
32
33 "gitlab.com/ubports/development/core/lomiri-push-service/bus"
34 "gitlab.com/ubports/development/core/lomiri-push-service/bus/focusinfo"
35 "gitlab.com/ubports/development/core/lomiri-push-service/bus/notifications"
36 testibus "gitlab.com/ubports/development/core/lomiri-push-service/bus/testing"
37 "gitlab.com/ubports/development/core/lomiri-push-service/click"
38 clickhelp "gitlab.com/ubports/development/core/lomiri-push-service/click/testing"
39 "gitlab.com/ubports/development/core/lomiri-push-service/launch_helper"
40 "gitlab.com/ubports/development/core/lomiri-push-service/messaging/reply"
41 "gitlab.com/ubports/development/core/lomiri-push-service/nih"
42 helpers "gitlab.com/ubports/development/core/lomiri-push-service/testing"
43 "gitlab.com/ubports/development/core/lomiri-push-service/testing/condition"
44 )
45
46 // takeNext takes a value from given channel with a 5s timeout
47 func takeNextBool(ch <-chan bool) bool {
48 select {
49 case <-time.After(5 * time.Second):
50 panic("channel stuck: too long waiting")
51 case v := <-ch:
52 return v
53 }
54 }
55
56 // takeNextBytes takes a value from given channel with a 5s timeout
57 func takeNextBytes(ch <-chan []byte) []byte {
58 select {
59 case <-time.After(5 * time.Second):
60 panic("channel stuck: too long waiting")
61 case v := <-ch:
62 return v
63 }
64 }
65
66 // takeNextHelperOutput takes a value from given channel with a 5s timeout
67 func takeNextHelperOutput(ch <-chan *launch_helper.HelperOutput) *launch_helper.HelperOutput {
68 select {
69 case <-time.After(5 * time.Second):
70 panic("channel stuck: too long waiting")
71 case v := <-ch:
72 return v
73 }
74 }
75
76 func takeNextError(ch <-chan error) error {
77 select {
78 case <-time.After(5 * time.Second):
79 panic("channel stuck: too long waiting")
80 case v := <-ch:
81 return v
82 }
83 }
84
85 func installTickMessageHandler(svc *PostalService) chan bool {
86 ch := make(chan bool)
87 msgHandler := svc.GetMessageHandler()
88 svc.SetMessageHandler(func(app *click.AppId, nid string, output *launch_helper.HelperOutput) bool {
89 var b bool
90 if msgHandler != nil {
91 b = msgHandler(app, nid, output)
92 }
93 ch <- b
94 return b
95 })
96 return ch
97 }
98
99 type fakeHelperLauncher struct {
100 i int
101 ch chan []byte
102 done func(string)
103 }
104
105 func (fhl *fakeHelperLauncher) InstallObserver(done func(string)) error {
106 fhl.done = done
107 return nil
108 }
109 func (fhl *fakeHelperLauncher) RemoveObserver() error { return nil }
110 func (fhl *fakeHelperLauncher) Stop(_, _ string) error { return nil }
111 func (fhl *fakeHelperLauncher) HelperAppID(app *click.AppId) string {
112 if app.Click {
113 return "helpId"
114 } else {
115 return app.Application
116 }
117 }
118 func (fhl *fakeHelperLauncher) Launch(_, f1, f2 string) (string, error) {
119 dat, err := ioutil.ReadFile(f1)
120 if err != nil {
121 return "", err
122 }
123 err = ioutil.WriteFile(f2, dat, os.ModeTemporary)
124 if err != nil {
125 return "", err
126 }
127
128 id := []string{"0", "1", "2"}[fhl.i]
129 fhl.i++
130
131 fhl.ch <- dat
132
133 return id, nil
134 }
135
136 type fakeUrlDispatcher struct {
137 DispatchDone chan bool
138 DispatchCalls [][]string
139 TestURLCalls []map[string][]string
140 NextTestURLResult bool
141 DispatchShouldFail bool
142 Lock sync.Mutex
143 }
144
145 func (fud *fakeUrlDispatcher) DispatchURL(url string, app *click.AppId) error {
146 fud.Lock.Lock()
147 defer fud.Lock.Unlock()
148 fud.DispatchCalls = append(fud.DispatchCalls, []string{url, app.DispatchPackage()})
149 if fud.DispatchShouldFail {
150 return errors.New("fail!")
151 }
152 fud.DispatchDone <- true
153 return nil
154 }
155
156 func (fud *fakeUrlDispatcher) TestURL(app *click.AppId, urls []string) bool {
157 fud.Lock.Lock()
158 defer fud.Lock.Unlock()
159 var args = make(map[string][]string, 1)
160 args[app.DispatchPackage()] = urls
161 fud.TestURLCalls = append(fud.TestURLCalls, args)
162 return fud.NextTestURLResult
163 }
164
165 type postalSuite struct {
166 log *helpers.TestLogger
167 cfg *PostalServiceSetup
168 bus bus.Endpoint
169 notifBus bus.Endpoint
170 counterBus bus.Endpoint
171 hapticBus bus.Endpoint
172 greeterBus bus.Endpoint
173 focusInfoBus bus.Endpoint
174 accountsBus bus.Endpoint
175 accountsCh chan []interface{}
176 fakeLauncher *fakeHelperLauncher
177 getTempDir func(string) (string, error)
178 oldAreEnabled func(*click.AppId) bool
179 notifyEnabled bool
180 }
181
182 type ualPostalSuite struct {
183 postalSuite
184 }
185
186 type trivialPostalSuite struct {
187 postalSuite
188 }
189
190 var _ = Suite(&ualPostalSuite{})
191 var _ = Suite(&trivialPostalSuite{})
192
193 func (ps *postalSuite) SetUpTest(c *C) {
194 ps.oldAreEnabled = areNotificationsEnabled
195 areNotificationsEnabled = func(*click.AppId) bool { return ps.notifyEnabled }
196 ps.log = helpers.NewTestLogger(c, "debug")
197 ps.cfg = &PostalServiceSetup{}
198 ps.bus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true))
199 ps.notifBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true))
200 ps.counterBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true))
201 ps.accountsBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), map[string]dbus.Variant{
202 "IncomingMessageVibrate": dbus.MakeVariant(true),
203 "SilentMode": dbus.MakeVariant(false),
204 "IncomingMessageSound": dbus.MakeVariant(""),
205 "IncomingMessageVibrateSilentMode": dbus.MakeVariant(false),
206 })
207
208 ps.hapticBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true))
209 ps.greeterBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), false)
210 ps.focusInfoBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), false)
211 ps.fakeLauncher = &fakeHelperLauncher{ch: make(chan []byte)}
212 ps.notifyEnabled = true
213
214 focusinfo.GetPrimaryPID = func(appId *click.AppId) int {
215 return 42
216 }
217
218 ps.getTempDir = launch_helper.GetTempDir
219 d := c.MkDir()
220 launch_helper.GetTempDir = func(pkgName string) (string, error) {
221 tmpDir := filepath.Join(d, pkgName)
222 return tmpDir, os.MkdirAll(tmpDir, 0700)
223 }
224
225 ps.accountsCh = make(chan []interface{})
226 testibus.SetWatchSource(ps.accountsBus, "PropertiesChanged", ps.accountsCh)
227 }
228
229 func (ps *postalSuite) TearDownTest(c *C) {
230 areNotificationsEnabled = ps.oldAreEnabled
231 launch_helper.GetTempDir = ps.getTempDir
232 close(ps.accountsCh)
233 }
234
235 func (ts *trivialPostalSuite) SetUpTest(c *C) {
236 ts.postalSuite.SetUpTest(c)
237 useTrivialHelper = true
238 }
239
240 func (ts *trivialPostalSuite) TearDownTest(c *C) {
241 ts.postalSuite.TearDownTest(c)
242 useTrivialHelper = false
243 }
244
245 func (ps *postalSuite) replaceBuses(pst *PostalService) *PostalService {
246 pst.Bus = ps.bus
247 pst.NotificationsEndp = ps.notifBus
248 pst.EmblemCounterEndp = ps.counterBus
249 pst.AccountsEndp = ps.accountsBus
250 pst.HapticEndp = ps.hapticBus
251 pst.GreeterEndp = ps.greeterBus
252 pst.FocusInfoEndp = ps.focusInfoBus
253 pst.launchers = map[string]launch_helper.HelperLauncher{}
254 return pst
255 }
256
257 func (ps *postalSuite) TestStart(c *C) {
258 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
259 c.Check(svc.IsRunning(), Equals, false)
260 c.Check(svc.Start(), IsNil)
261 c.Check(svc.IsRunning(), Equals, true)
262 svc.Stop()
263 }
264
265 func (ps *postalSuite) TestStartTwice(c *C) {
266 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
267 c.Check(svc.Start(), IsNil)
268 c.Check(svc.Start(), Equals, ErrAlreadyStarted)
269 svc.Stop()
270 }
271
272 func (ps *postalSuite) TestStartNoLog(c *C) {
273 svc := ps.replaceBuses(NewPostalService(ps.cfg, nil))
274 c.Check(svc.Start(), Equals, ErrNotConfigured)
275 }
276
277 func (ps *postalSuite) TestStartNoBus(c *C) {
278 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
279 svc.Bus = nil
280 c.Check(svc.Start(), Equals, ErrNotConfigured)
281
282 svc = ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
283 svc.NotificationsEndp = nil
284 c.Check(svc.Start(), Equals, ErrNotConfigured)
285 }
286
287 func (ps *postalSuite) TestTakeTheBusFail(c *C) {
288 nEndp := testibus.NewMultiValuedTestingEndpoint(condition.Work(true), condition.Work(false))
289 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
290 svc.NotificationsEndp = nEndp
291 _, err := svc.takeTheBus()
292 c.Check(err, NotNil)
293 }
294
295 func (ps *postalSuite) TestTakeTheBusOk(c *C) {
296 nEndp := testibus.NewMultiValuedTestingEndpoint(condition.Work(true), condition.Work(true), []interface{}{uint32(1), "hello"})
297 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
298 svc.NotificationsEndp = nEndp
299 _, err := svc.takeTheBus()
300 c.Check(err, IsNil)
301 }
302
303 func (ps *postalSuite) TestStartFailsOnBusDialFailure(c *C) {
304 // XXX actually, we probably want to autoredial this
305 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
306 svc.Bus = testibus.NewTestingEndpoint(condition.Work(false), nil)
307 c.Check(svc.Start(), ErrorMatches, `.*(?i)cond said no.*`)
308 svc.Stop()
309 }
310
311 func (ps *postalSuite) TestStartGrabsName(c *C) {
312 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
313 c.Assert(svc.Start(), IsNil)
314 callArgs := testibus.GetCallArgs(ps.bus)
315 defer svc.Stop()
316 c.Assert(callArgs, NotNil)
317 c.Check(callArgs[0].Member, Equals, "::GrabName")
318 }
319
320 func (ps *postalSuite) TestStopClosesBus(c *C) {
321 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
322 c.Assert(svc.Start(), IsNil)
323 svc.Stop()
324 callArgs := testibus.GetCallArgs(ps.bus)
325 c.Assert(callArgs, NotNil)
326 c.Check(callArgs[len(callArgs)-1].Member, Equals, "::Close")
327 }
328
329 //
330 // post() tests
331
332 func (ps *postalSuite) TestPostHappyPath(c *C) {
333 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
334 svc.msgHandler = nil
335 ch := installTickMessageHandler(svc)
336 svc.launchers = map[string]launch_helper.HelperLauncher{
337 "click": ps.fakeLauncher,
338 }
339 c.Assert(svc.Start(), IsNil)
340 payload := `{"message": {"world":1}}`
341 err := svc.post(aMsg, anAppId, payload)
342 c.Assert(err, IsNil)
343
344 if ps.fakeLauncher.done != nil {
345 // wait for the two posts to "launch"
346 inputData := takeNextBytes(ps.fakeLauncher.ch)
347 c.Check(string(inputData), Equals, payload)
348
349 go ps.fakeLauncher.done("0") // OneDone
350 }
351
352 c.Check(takeNextBool(ch), Equals, false) // one,
353 // xxx here?
354 c.Assert(svc.mbox, HasLen, 1)
355 box, ok := svc.mbox[anAppId]
356 c.Check(ok, Equals, true)
357 msgs := box.AllMessages()
358 c.Assert(msgs, HasLen, 1)
359 c.Check(msgs[0], Equals, `{"world":1}`)
360 c.Check(box.nids[0], Not(Equals), "")
361 }
362
363 func (ps *postalSuite) TestPostFailsIfBadArgs(c *C) {
364 for i, s := range []struct {
365 appID, payload string
366 errt *dbus.Error
367 }{
368 {anAppId, "zoom", dbus.MakeFailedError(ErrBadJSON)},
369 {"bar", "hello", MakeDBusNoObjectErrorWithReason(
370 aPackageOnBus, click.ErrInvalidAppId)},
371 } {
372 err := new(PostalService).post(aMsg, s.appID, s.payload)
373 c.Check(err, DeepEquals, s.errt, Commentf("iteration #%d", i))
374 }
375 }
376
377 // Post() tests
378
379 func (ps *postalSuite) TestPostWorks(c *C) {
380 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
381 svc.msgHandler = nil
382 ch := installTickMessageHandler(svc)
383 fakeLauncher2 := &fakeHelperLauncher{ch: make(chan []byte)}
384 svc.launchers = map[string]launch_helper.HelperLauncher{
385 "click": ps.fakeLauncher,
386 "legacy": fakeLauncher2,
387 }
388 c.Assert(svc.Start(), IsNil)
389
390 app := clickhelp.MustParseAppId(anAppId)
391 // these two, being for the same app, will be done sequentially.
392 svc.Post(app, "m1", json.RawMessage(`{"message":{"world":1}}`))
393 svc.Post(app, "m2", json.RawMessage(`{"message":{"moon":1}}`))
394 classicApp := clickhelp.MustParseAppId("_classic-app")
395 svc.Post(classicApp, "m3", json.RawMessage(`{"message":{"mars":42}}`))
396
397 oneConsumed := false
398
399 if ps.fakeLauncher.done != nil {
400 // wait for the two posts to "launch"
401 takeNextBytes(ps.fakeLauncher.ch)
402 takeNextBytes(fakeLauncher2.ch)
403 go ps.fakeLauncher.done("0") // OneDone
404 go fakeLauncher2.done("0")
405
406 c.Check(takeNextBool(ch), Equals, false) // one
407 oneConsumed = true
408
409 inputData := takeNextBytes(ps.fakeLauncher.ch)
410
411 c.Check(string(inputData), Equals, `{"message":{"moon":1}}`)
412
413 go ps.fakeLauncher.done("1") // OneDone
414 }
415
416 if !oneConsumed {
417 c.Check(takeNextBool(ch), Equals, false) // one,
418 }
419 c.Check(takeNextBool(ch), Equals, false) // two,
420 c.Check(takeNextBool(ch), Equals, false) // three posts
421 c.Assert(svc.mbox, HasLen, 2)
422 box, ok := svc.mbox[anAppId]
423 c.Check(ok, Equals, true)
424 msgs := box.AllMessages()
425 c.Assert(msgs, HasLen, 2)
426 c.Check(msgs[0], Equals, `{"world":1}`)
427 c.Check(msgs[1], Equals, `{"moon":1}`)
428 c.Check(box.nids, DeepEquals, []string{"m1", "m2"})
429 box, ok = svc.mbox["_classic-app"]
430 c.Assert(ok, Equals, true)
431 msgs = box.AllMessages()
432 c.Assert(msgs, HasLen, 1)
433 c.Check(msgs[0], Equals, `{"mars":42}`)
434 }
435
436 func (ps *postalSuite) TestPostCallsMessageHandlerDetails(c *C) {
437 ch := make(chan *launch_helper.HelperOutput)
438 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
439 svc.launchers = map[string]launch_helper.HelperLauncher{
440 "click": ps.fakeLauncher,
441 }
442 c.Assert(svc.Start(), IsNil)
443 // check the message handler gets called
444 app := clickhelp.MustParseAppId(anAppId)
445 f := func(app *click.AppId, nid string, s *launch_helper.HelperOutput) bool {
446 c.Check(app.Base(), Equals, anAppId)
447 c.Check(nid, Equals, "m7")
448 ch <- s
449 return true
450 }
451 svc.SetMessageHandler(f)
452 svc.Post(app, "m7", json.RawMessage("{}"))
453
454 if ps.fakeLauncher.done != nil {
455 takeNextBytes(ps.fakeLauncher.ch)
456
457 go ps.fakeLauncher.done("0") // OneDone
458 }
459
460 c.Check(takeNextHelperOutput(ch), DeepEquals, &launch_helper.HelperOutput{})
461 }
462
463 func (ps *postalSuite) TestAfterMessageHandlerSignal(c *C) {
464 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
465 svc.msgHandler = nil
466
467 hInp := &launch_helper.HelperInput{
468 App: clickhelp.MustParseAppId(anAppId),
469 }
470 res := &launch_helper.HelperResult{Input: hInp}
471
472 svc.handleHelperResult(res)
473
474 // and check it fired the right signal
475 callArgs := testibus.GetCallArgs(ps.bus)
476 l := len(callArgs)
477 if l < 1 {
478 c.Fatal("not enough elements in resposne from GetCallArgs")
479 }
480 c.Check(callArgs[l-1].Member, Equals, "::Signal")
481 c.Check(callArgs[l-1].Args, DeepEquals, []interface{}{"Post", aPackageOnBus, []interface{}{anAppId}})
482 }
483
484 func (ps *postalSuite) TestFailingMessageHandlerSurvived(c *C) {
485 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
486 svc.SetMessageHandler(func(*click.AppId, string, *launch_helper.HelperOutput) bool {
487 return false
488 })
489
490 hInp := &launch_helper.HelperInput{
491 App: clickhelp.MustParseAppId(anAppId),
492 }
493 res := &launch_helper.HelperResult{Input: hInp}
494
495 svc.handleHelperResult(res)
496
497 c.Check(ps.log.Captured(), Equals, "DEBUG msgHandler did not present the notification\n")
498 // we actually want to send a signal even if we didn't do anything
499 callArgs := testibus.GetCallArgs(ps.bus)
500 c.Assert(len(callArgs), Equals, 1)
501 c.Check(callArgs[0].Member, Equals, "::Signal")
502 }
503
504 //
505 // Notifications tests
506 func (ps *postalSuite) TestNotificationsWorks(c *C) {
507 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
508 nots, err := svc.popAll(aMsg, anAppId)
509 c.Assert(err, IsNil)
510 c.Assert(nots, HasLen, 0)
511 c.Assert(svc.mbox, IsNil)
512 svc.mbox = make(map[string]*mBox)
513 nots, err = svc.popAll(aMsg, anAppId)
514 c.Assert(err, IsNil)
515 c.Assert(nots, NotNil)
516 c.Check(nots, HasLen, 0)
517 box := new(mBox)
518 svc.mbox[anAppId] = box
519 m1 := json.RawMessage(`"m1"`)
520 m2 := json.RawMessage(`"m2"`)
521 box.Append(m1, "n1")
522 box.Append(m2, "n2")
523 nots, err = svc.popAll(aMsg, anAppId)
524 c.Assert(err, IsNil)
525 c.Assert(nots, NotNil)
526 c.Check(nots, DeepEquals, []string{string(m1), string(m2)})
527 }
528
529 func (ps *postalSuite) TestNotificationsFailsIfBadArgs(c *C) {
530 reg, err := new(PostalService).popAll(aMsg, "potato")
531 c.Check(reg, HasLen, 0)
532 c.Check(err, DeepEquals, MakeDBusNoObjectErrorWithReason(
533 aPackageOnBus, click.ErrInvalidAppId))
534 }
535
536 func (ps *postalSuite) TestMessageHandlerPublicAPI(c *C) {
537 svc := new(PostalService)
538 c.Assert(svc.msgHandler, IsNil)
539 var ext = &launch_helper.HelperOutput{}
540 f := func(_ *click.AppId, _ string, s *launch_helper.HelperOutput) bool { ext = s; return false }
541 c.Check(svc.GetMessageHandler(), IsNil)
542 svc.SetMessageHandler(f)
543 c.Check(svc.GetMessageHandler(), NotNil)
544 hOutput := &launch_helper.HelperOutput{[]byte("37"), nil}
545 c.Check(svc.msgHandler(nil, "", hOutput), Equals, false)
546 c.Check(ext, DeepEquals, hOutput)
547 }
548
549 func (ps *postalSuite) TestMessageHandlerPresents(c *C) {
550 endp := testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), uint32(1))
551 svc := NewPostalService(ps.cfg, ps.log)
552 svc.Bus = endp
553 svc.EmblemCounterEndp = endp
554 svc.AccountsEndp = ps.accountsBus
555 svc.HapticEndp = endp
556 svc.NotificationsEndp = endp
557 svc.GreeterEndp = ps.greeterBus
558 svc.FocusInfoEndp = ps.focusInfoBus
559 nopTicker := make(chan []interface{})
560 testibus.SetWatchSource(endp, "ActionInvoked", nopTicker)
561 defer close(nopTicker)
562 svc.launchers = map[string]launch_helper.HelperLauncher{}
563 svc.fallbackVibration = &launch_helper.Vibration{Pattern: []uint32{1}}
564 c.Assert(svc.Start(), IsNil)
565
566 // Persist is false so we just check the log
567 card := &launch_helper.Card{Icon: "icon-value", Summary: "summary-value", Body: "body-value", Popup: true, Persist: false}
568 vib := json.RawMessage(`true`)
569 emb := &launch_helper.EmblemCounter{Count: 2, Visible: true}
570 output := &launch_helper.HelperOutput{Notification: &launch_helper.Notification{Card: card, EmblemCounter: emb, RawVibration: vib}}
571 b := svc.messageHandler(&click.AppId{}, "", output)
572 c.Assert(b, Equals, true)
573 args := testibus.GetCallArgs(endp)
574 l := len(args)
575 if l < 4 {
576 c.Fatal("not enough elements in response from GetCallArgs")
577 }
578 mm := make([]string, 4)
579 for i, m := range args[l-4:] {
580 mm[i] = m.Member
581 }
582 sort.Strings(mm)
583 // check the Present() methods were called.
584 // For dbus-backed presenters, just check the right dbus methods are called
585 c.Check(mm, DeepEquals, []string{"::SetProperty", "::SetProperty", "Notify", "vibratePattern"})
586 // For the other ones, check the logs
587 c.Check(ps.log.Captured(), Matches, `(?sm).* no persistable card:.*`)
588 c.Check(ps.log.Captured(), Matches, `(?sm).* notification has no Sound:.*`)
589 }
590
591 func (ps *postalSuite) TestMessageHandlerReportsFailedNotifies(c *C) {
592 endp := testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), "x")
593 nopTicker := make(chan []interface{})
594 testibus.SetWatchSource(endp, "ActionInvoked", nopTicker)
595 defer close(nopTicker)
596 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
597 svc.NotificationsEndp = endp
598 c.Assert(svc.Start(), IsNil)
599 card := &launch_helper.Card{Icon: "icon-value", Summary: "summary-value", Body: "body-value", Popup: true}
600 notif := &launch_helper.Notification{Card: card}
601 output := &launch_helper.HelperOutput{Notification: notif}
602 b := svc.messageHandler(&click.AppId{}, "", output)
603 c.Check(b, Equals, false)
604 }
605
606 func (ps *postalSuite) TestMessageHandlerInhibition(c *C) {
607 endp := testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), true)
608 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
609 svc.FocusInfoEndp = endp
610 c.Assert(svc.Start(), IsNil)
611 output := &launch_helper.HelperOutput{Notification: &launch_helper.Notification{}} // Doesn't matter
612 b := svc.messageHandler(clickhelp.MustParseAppId("com.example.test_test-app_0"), "", output)
613 c.Check(b, Equals, false)
614 c.Check(ps.log.Captured(), Matches, `(?sm).* notification skipped because app is focused.*`)
615 }
616
617 func (ps *postalSuite) TestMessageHandlerReportsButIgnoresUnmarshalErrors(c *C) {
618 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
619 c.Assert(svc.Start(), IsNil)
620 output := &launch_helper.HelperOutput{[]byte(`broken`), nil}
621 b := svc.messageHandler(nil, "", output)
622 c.Check(b, Equals, false)
623 c.Check(ps.log.Captured(), Matches, "(?msi).*skipping notification: nil.*")
624 }
625
626 func (ps *postalSuite) TestMessageHandlerReportsButIgnoresNilNotifies(c *C) {
627 endp := testibus.NewTestingEndpoint(condition.Work(true), condition.Work(false))
628 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
629 c.Assert(svc.Start(), IsNil)
630 svc.NotificationsEndp = endp
631 output := &launch_helper.HelperOutput{[]byte(`{}`), nil}
632 b := svc.messageHandler(nil, "", output)
633 c.Assert(b, Equals, false)
634 c.Check(ps.log.Captured(), Matches, "(?msi).*skipping notification: nil.*")
635 }
636
637 func (ps *postalSuite) TestMessageHandlerInvalidAction(c *C) {
638 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
639 c.Assert(svc.Start(), IsNil)
640 fakeDisp := new(fakeUrlDispatcher)
641 svc.urlDispatcher = fakeDisp
642 fakeDisp.NextTestURLResult = false
643 card := launch_helper.Card{Actions: []string{"notsupported://test-app"}}
644 output := &launch_helper.HelperOutput{Notification: &launch_helper.Notification{Card: &card}}
645 appId := clickhelp.MustParseAppId("com.example.test_test-app_0")
646 b := svc.messageHandler(appId, "", output)
647 c.Check(b, Equals, false)
648 fakeDisp.Lock.Lock()
649 defer fakeDisp.Lock.Unlock()
650 c.Assert(len(fakeDisp.DispatchCalls), Equals, 0)
651 c.Assert(len(fakeDisp.TestURLCalls), Equals, 1)
652 c.Assert(fakeDisp.TestURLCalls[0][appId.DispatchPackage()], DeepEquals, []string{"notsupported://test-app"})
653 }
654
655 func (ps *postalSuite) TestHandleActionsDispatches(c *C) {
656 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
657 fmm := new(fakeMM)
658 app, _ := click.ParseAppId("com.example.test_test-app")
659 c.Assert(svc.Start(), IsNil)
660 fakeDisp := new(fakeUrlDispatcher)
661 fakeDisp.DispatchDone = make(chan bool)
662 svc.urlDispatcher = fakeDisp
663 fakeDisp.NextTestURLResult = true
664 svc.messagingMenu = fmm
665 aCh := make(chan *notifications.RawAction)
666 rCh := make(chan *reply.MMActionReply)
667 go func() {
668 aCh <- nil // just in case?
669 aCh <- &notifications.RawAction{App: app, Action: "potato://", Nid: "xyzzy"}
670 close(aCh)
671 }()
672 go svc.handleActions(aCh, rCh)
673 takeNextBool(fakeDisp.DispatchDone)
674 fakeDisp.Lock.Lock()
675 defer fakeDisp.Lock.Unlock()
676 c.Assert(len(fakeDisp.DispatchCalls), Equals, 1)
677 c.Assert(fakeDisp.DispatchCalls[0][0], Equals, "potato://")
678 c.Assert(fakeDisp.DispatchCalls[0][1], Equals, app.DispatchPackage())
679 c.Check(fmm.calls, DeepEquals, []string{"remove:xyzzy:true"})
680 }
681
682 func (ps *postalSuite) TestHandleMMUActionsDispatches(c *C) {
683 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
684 c.Assert(svc.Start(), IsNil)
685 fakeDisp := new(fakeUrlDispatcher)
686 svc.urlDispatcher = fakeDisp
687 fakeDisp.DispatchDone = make(chan bool)
688 fakeDisp.NextTestURLResult = true
689 app, _ := click.ParseAppId("com.example.test_test-app")
690 aCh := make(chan *notifications.RawAction)
691 rCh := make(chan *reply.MMActionReply)
692 go func() {
693 rCh <- nil // just in case?
694 rCh <- &reply.MMActionReply{App: app, Action: "potato://", Notification: "foo.bar"}
695 close(rCh)
696 }()
697 go svc.handleActions(aCh, rCh)
698 takeNextBool(fakeDisp.DispatchDone)
699 fakeDisp.Lock.Lock()
700 defer fakeDisp.Lock.Unlock()
701 c.Assert(len(fakeDisp.DispatchCalls), Equals, 1)
702 c.Assert(fakeDisp.DispatchCalls[0][0], Equals, "potato://")
703 c.Assert(fakeDisp.DispatchCalls[0][1], Equals, app.DispatchPackage())
704 }
705
706 func (ps *postalSuite) TestValidateActions(c *C) {
707 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
708 c.Assert(svc.Start(), IsNil)
709 card := launch_helper.Card{Actions: []string{"potato://test-app"}}
710 notif := &launch_helper.Notification{Card: &card}
711 fakeDisp := new(fakeUrlDispatcher)
712 svc.urlDispatcher = fakeDisp
713 fakeDisp.NextTestURLResult = true
714 b := svc.validateActions(clickhelp.MustParseAppId("com.example.test_test-app_0"), notif)
715 c.Check(b, Equals, true)
716 }
717
718 func (ps *postalSuite) TestValidateActionsNoActions(c *C) {
719 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
720 card := launch_helper.Card{}
721 notif := &launch_helper.Notification{Card: &card}
722 b := svc.validateActions(clickhelp.MustParseAppId("com.example.test_test-app_0"), notif)
723 c.Check(b, Equals, true)
724 }
725
726 func (ps *postalSuite) TestValidateActionsNoCard(c *C) {
727 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
728 notif := &launch_helper.Notification{}
729 b := svc.validateActions(clickhelp.MustParseAppId("com.example.test_test-app_0"), notif)
730 c.Check(b, Equals, true)
731 }
732
733 type fakeMM struct {
734 calls []string
735 }
736
737 func (*fakeMM) Present(*click.AppId, string, *launch_helper.Notification) bool { return false }
738 func (*fakeMM) GetCh() chan *reply.MMActionReply { return nil }
739 func (*fakeMM) StartCleanupLoop() {}
740 func (fmm *fakeMM) RemoveNotification(s string, b bool) {
741 fmm.calls = append(fmm.calls, fmt.Sprintf("remove:%s:%t", s, b))
742 }
743 func (fmm *fakeMM) Clear(*click.AppId, ...string) int {
744 fmm.calls = append(fmm.calls, "clear")
745 return 42
746 }
747 func (fmm *fakeMM) Tags(*click.AppId) []string {
748 fmm.calls = append(fmm.calls, "tags")
749 return []string{"hello"}
750 }
751
752 func (ps *postalSuite) TestListPersistent(c *C) {
753 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
754 fmm := new(fakeMM)
755 svc.messagingMenu = fmm
756
757 tags, err := svc.listPersistent(aMsg, anAppId)
758 c.Assert(err, IsNil)
759 c.Check(tags, DeepEquals, []string{"hello"})
760 c.Check(fmm.calls, DeepEquals, []string{"tags"})
761 }
762
763 func (ps *postalSuite) TestListPersistentErrors(c *C) {
764 reg, err := new(PostalService).listPersistent(aMsg, "bar")
765 c.Check(reg, IsNil)
766 c.Check(err, DeepEquals, MakeDBusNoObjectErrorWithReason(
767 aPackageOnBus, click.ErrInvalidAppId))
768 }
769
770 func (ps *postalSuite) TestClearPersistent(c *C) {
771 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
772 fmm := new(fakeMM)
773 svc.messagingMenu = fmm
774
775 icleared, err := svc.clearPersistentList(aMsg, anAppId, []string{"one", "two"})
776 c.Assert(err, IsNil)
777 c.Check(icleared, Equals, uint32(42))
778
779 icleared, err = svc.clearPersistent(aMsg, anAppId, "three")
780 c.Assert(err, IsNil)
781 c.Check(icleared, Equals, uint32(42))
782 }
783
784 func (ps *postalSuite) TestClearPersistentErrors(c *C) {
785 _, err := new(PostalService).clearPersistent(aMsg, "xyzzy", "")
786 c.Check(err, DeepEquals, MakeDBusNoObjectErrorWithReason(
787 aPackageOnBus, click.ErrInvalidAppId))
788
789 _, err = new(PostalService).clearPersistentList(aMsg, "xyzzy", []string{})
790 c.Check(err, DeepEquals, MakeDBusNoObjectErrorWithReason(
791 aPackageOnBus, click.ErrInvalidAppId))
792 }
793
794 func (ps *postalSuite) TestSetCounter(c *C) {
795 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
796 c.Check(svc.Start(), IsNil)
797
798 err := svc.setCounter(aMsg, anAppId, 42, true)
799 c.Assert(err, IsNil)
800
801 quoted := "/" + string(nih.Quote([]byte(anAppId)))
802
803 callArgs := testibus.GetCallArgs(svc.EmblemCounterEndp)
804 c.Assert(callArgs, HasLen, 2)
805 c.Check(callArgs[0].Member, Equals, "::SetProperty")
806 c.Check(callArgs[0].Args, DeepEquals, []interface{}{"count", quoted, dbus.MakeVariant(int32(42))})
807
808 c.Check(callArgs[1].Member, Equals, "::SetProperty")
809 c.Check(callArgs[1].Args, DeepEquals, []interface{}{"countVisible", quoted, dbus.MakeVariant(true)})
810 }
811
812 func (ps *postalSuite) TestSetCounterErrors(c *C) {
813 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
814 svc.Start()
815
816 for i, s := range []struct {
817 id string
818 count int
819 visible bool
820 err *dbus.Error
821 }{
822 {anAppId, 42, true, nil}, // for reference
823 {"xyzzy", 42, true, MakeDBusNoObjectErrorWithReason(
824 aPackageOnBus, click.ErrInvalidAppId)},
825 } {
826 err := svc.setCounter(aMsg, s.id, s.count, s.visible)
827 c.Check(err, DeepEquals, s.err, Commentf("iter %d", i))
828 }
829 }
830
831 func (ps *postalSuite) TestBlacklisted(c *C) {
832 ps.focusInfoBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), false, false, false, false)
833 ps.greeterBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), false, false, false, false)
834 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
835 svc.Start()
836 ps.notifyEnabled = true
837
838 emb := &launch_helper.EmblemCounter{Count: 2, Visible: true}
839 card := &launch_helper.Card{Icon: "icon-value", Summary: "summary-value", Persist: true}
840 output := &launch_helper.HelperOutput{Notification: &launch_helper.Notification{Card: card}}
841 embOut := &launch_helper.HelperOutput{Notification: &launch_helper.Notification{EmblemCounter: emb}}
842 app := clickhelp.MustParseAppId("com.example.app_app_1.0")
843 // sanity check: things are presented as normal if notifyEnabled == true
844 ps.notifyEnabled = true
845 c.Check(svc.messageHandler(app, "0", output), Equals, true)
846 c.Check(svc.messageHandler(app, "1", embOut), Equals, true)
847 ps.notifyEnabled = false
848 // and regular notifications (but not emblem counters) are suppressed if notifications are disabled.
849 c.Check(svc.messageHandler(app, "2", output), Equals, false)
850 c.Check(svc.messageHandler(app, "3", embOut), Equals, true)
851 }
852
853 func (ps *postalSuite) TestFocusedAppButLockedScreenNotification(c *C) {
854 appId := "com.example.test_test-app"
855 ps.focusInfoBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), true)
856 ps.greeterBus = testibus.NewTestingEndpoint(condition.Work(true), condition.Work(true), true)
857 svc := ps.replaceBuses(NewPostalService(ps.cfg, ps.log))
858 // svc.FocusInfoEndp = ps.focusInfoBus
859 svc.Start()
860
861 card := &launch_helper.Card{Icon: "icon-value", Summary: "summary-value", Persist: true}
862 output := &launch_helper.HelperOutput{Notification: &launch_helper.Notification{Card: card}}
863 app := clickhelp.MustParseAppId(fmt.Sprintf("%v_0", appId))
864
865 c.Check(svc.messageHandler(app, "0", output), Equals, true)
866 }