aboutsummaryrefslogtreecommitdiffstats
path: root/internal/notify/service_test.go
blob: f7d719526ef3a32b1d98498e85611c456e2ff157 (plain)
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

package notify

import (
	"encoding/json"
	"image/png"
	"os"
	"path/filepath"
	"strconv"
	"testing"
	"time"

	"github.com/godbus/dbus/v5"
)

// The integration tests need a session bus this process can own the name on.
// Run them with dbus-run-session -- go test ./internal/notify
func busOrSkip(t *testing.T) *dbus.Conn {
	t.Helper()
	conn, err := dbus.SessionBus()
	if err != nil {
		t.Skipf("no session bus: %v", err)
	}
	reply, err := conn.RequestName(Name, dbus.NameFlagDoNotQueue)
	if err != nil {
		t.Skipf("cannot request the name: %v", err)
	}
	// AlreadyOwner happens on the second bus test in one process, because
	// dbus.SessionBus is a shared connection. That is fine: the name is ours.
	if reply != dbus.RequestNameReplyPrimaryOwner && reply != dbus.RequestNameReplyAlreadyOwner {
		t.Skipf("cannot own the name, run under dbus-run-session (reply %v)", reply)
	}
	return conn
}

func TestIdentityAndCapabilities(t *testing.T) {
	s := &Service{}
	name, vendor, _, spec, err := s.GetServerInformation()
	if err != nil {
		t.Fatalf("GetServerInformation: %v", err)
	}
	if name != "danix" || vendor != "danix" || spec != "1.2" {
		t.Errorf("identity = %q/%q spec %q, want danix/danix 1.2", name, vendor, spec)
	}
	caps, err := s.GetCapabilities()
	if err != nil {
		t.Fatalf("GetCapabilities: %v", err)
	}
	for _, want := range []string{"actions", "body-markup", "icon-static", "persistence"} {
		found := false
		for _, c := range caps {
			if c == want {
				found = true
			}
		}
		if !found {
			t.Errorf("missing capability %q in %v", want, caps)
		}
	}
}

func TestCapabilitiesIncludeBodyImages(t *testing.T) {
	caps, err := NewService(nil, t.TempDir()).GetCapabilities()
	if err != nil {
		t.Fatal(err)
	}
	found := false
	for _, c := range caps {
		if c == "body-images" {
			found = true
		}
	}
	if !found {
		t.Fatalf("body-images missing from %v", caps)
	}
}

func TestNotifyPublishesImagePath(t *testing.T) {
	var live []Popup
	s := &Service{dir: t.TempDir(), timers: map[uint32]*time.Timer{}}
	s.store = NewStore(s.emitClosed, func(l, _ []Popup) { live = l }, s.removeImage)
	hints := map[string]dbus.Variant{"image-path": dbus.MakeVariant("/tmp/shot.png")}
	if _, err := s.Notify("t", 0, "", "s", "b", nil, hints, -1); err != nil {
		t.Fatal(err)
	}
	if len(live) != 1 || live[0].Image != "/tmp/shot.png" {
		t.Fatalf("published %+v", live)
	}
}

func TestNotifyMaterialisesImageData(t *testing.T) {
	var live []Popup
	s := &Service{dir: t.TempDir(), timers: map[uint32]*time.Timer{}}
	s.store = NewStore(s.emitClosed, func(l, _ []Popup) { live = l }, s.removeImage)
	// A 2x2 RGBA image, row stride exactly width*channels.
	data := []byte{
		255, 0, 0, 255, 0, 255, 0, 255,
		0, 0, 255, 255, 255, 255, 255, 255,
	}
	hints := map[string]dbus.Variant{"image-data": dbus.MakeVariant([]interface{}{
		int32(2), int32(2), int32(8), true, int32(8), int32(4), data,
	})}
	id, dbusErr := s.Notify("t", 0, "", "s", "b", nil, hints, -1)
	if dbusErr != nil {
		t.Fatal(dbusErr)
	}
	path := filepath.Join(ImagesDir(s.dir), strconv.FormatUint(uint64(id), 10)+".png")
	f, err := os.Open(path)
	if err != nil {
		t.Fatalf("image not written: %v", err)
	}
	defer f.Close()
	img, err := png.Decode(f)
	if err != nil {
		t.Fatalf("image does not decode: %v", err)
	}
	if b := img.Bounds(); b.Dx() != 2 || b.Dy() != 2 {
		t.Fatalf("decoded %v, want 2x2", b)
	}
	// The first publish precedes SetImage, so the last one must carry the path.
	if len(live) != 1 || live[0].Image != path {
		t.Fatalf("published %+v, want image %q", live, path)
	}
}

// The deprecated icon_data must lose to the image-path URI it outranked when
// the keys were read in one tier.
func TestNotifyIconDataDoesNotBeatImagePath(t *testing.T) {
	var live []Popup
	s := &Service{dir: t.TempDir(), timers: map[uint32]*time.Timer{}}
	s.store = NewStore(s.emitClosed, func(l, _ []Popup) { live = l }, s.removeImage)
	rgba := []byte{255, 0, 0, 255, 0, 255, 0, 255}
	hints := map[string]dbus.Variant{
		"icon_data":  dbus.MakeVariant([]interface{}{int32(2), int32(1), int32(8), true, int32(8), int32(4), rgba}),
		"image-path": dbus.MakeVariant("/tmp/shot.png"),
	}
	if _, dbusErr := s.Notify("t", 0, "", "s", "b", nil, hints, -1); dbusErr != nil {
		t.Fatal(dbusErr)
	}
	if len(live) != 1 || live[0].Image != "/tmp/shot.png" {
		t.Fatalf("published %+v, want image-path", live)
	}
}

// image-data is tier 1, above both image-path and icon_data.
func TestNotifyImageDataBeatsIconDataAndPath(t *testing.T) {
	var live []Popup
	s := &Service{dir: t.TempDir(), timers: map[uint32]*time.Timer{}}
	s.store = NewStore(s.emitClosed, func(l, _ []Popup) { live = l }, s.removeImage)
	rgba := []byte{255, 0, 0, 255, 0, 255, 0, 255}
	hints := map[string]dbus.Variant{
		"image-data": dbus.MakeVariant([]interface{}{int32(2), int32(1), int32(8), true, int32(8), int32(4), rgba}),
		"icon_data":  dbus.MakeVariant([]interface{}{int32(9), int32(1), int32(8), true, int32(8), int32(4), rgba}),
		"image-path": dbus.MakeVariant("/tmp/shot.png"),
	}
	id, dbusErr := s.Notify("t", 0, "", "s", "b", nil, hints, -1)
	if dbusErr != nil {
		t.Fatal(dbusErr)
	}
	want := filepath.Join(ImagesDir(s.dir), strconv.FormatUint(uint64(id), 10)+".png")
	if len(live) != 1 || live[0].Image != want {
		t.Fatalf("published %+v, want image-data %q", live, want)
	}
}

func TestNotifyReturnsAnIDAndPublishes(t *testing.T) {
	conn := busOrSkip(t)
	dir := t.TempDir()
	svc := NewService(conn, dir)
	if err := svc.Start(); err != nil {
		t.Fatalf("Start: %v", err)
	}

	obj := conn.Object(Name, dbus.ObjectPath(objPath))
	call := obj.Call(iface+".Notify", 0,
		"app", uint32(0), "icon", "summary", "body",
		[]string{"default", "open"},
		map[string]dbus.Variant{"urgency": dbus.MakeVariant(byte(1))},
		int32(-1))
	if call.Err != nil {
		t.Fatalf("Notify: %v", call.Err)
	}
	var id uint32
	if err := call.Store(&id); err != nil {
		t.Fatalf("Notify reply: %v", err)
	}
	if id == 0 {
		t.Fatal("Notify returned id 0")
	}

	data, err := os.ReadFile(filepath.Join(dir, "queue.json"))
	if err != nil {
		t.Fatalf("read queue: %v", err)
	}
	var live []Popup
	if err := json.Unmarshal(data, &live); err != nil {
		t.Fatalf("queue not JSON: %v", err)
	}
	if len(live) != 1 || live[0].Summary != "summary" {
		t.Fatalf("queue = %+v, want one summary", live)
	}
	if live[0].Expires == 0 {
		t.Error("expires is zero, want a normal timeout")
	}
}

func TestCloseNotificationEmitsReasonThree(t *testing.T) {
	conn := busOrSkip(t)
	dir := t.TempDir()
	svc := NewService(conn, dir)
	if err := svc.Start(); err != nil {
		t.Fatalf("Start: %v", err)
	}
	signals := make(chan *dbus.Signal, 4)
	conn.Signal(signals)
	if err := conn.AddMatchSignal(dbus.WithMatchObjectPath(dbus.ObjectPath(objPath))); err != nil {
		t.Fatalf("AddMatchSignal: %v", err)
	}

	obj := conn.Object(Name, dbus.ObjectPath(objPath))
	call := obj.Call(iface+".Notify", 0, "app", uint32(0), "", "s", "b", []string{}, map[string]dbus.Variant{}, int32(-1))
	var id uint32
	if err := call.Store(&id); err != nil {
		t.Fatalf("Notify reply: %v", err)
	}
	if err := obj.Call(iface+".CloseNotification", 0, id).Err; err != nil {
		t.Fatalf("CloseNotification: %v", err)
	}

	select {
	case sig := <-signals:
		if sig.Name != iface+".NotificationClosed" {
			t.Fatalf("signal %q, want NotificationClosed", sig.Name)
		}
		if sig.Body[0].(uint32) != id || sig.Body[1].(uint32) != 3 {
			t.Errorf("signal body = %v, want id %d reason 3", sig.Body, id)
		}
	case <-time.After(2 * time.Second):
		t.Fatal("no NotificationClosed signal")
	}
}

func TestRemoveImageRefusesPathsOutsideTheImageDir(t *testing.T) {
	dir := t.TempDir()
	imgDir := ImagesDir(dir)
	if err := os.MkdirAll(imgDir, 0o700); err != nil {
		t.Fatal(err)
	}
	sibling := filepath.Join(dir, "queue.json")
	if err := os.WriteFile(sibling, []byte("x"), 0o600); err != nil {
		t.Fatal(err)
	}
	owned := filepath.Join(imgDir, "1.png")
	if err := os.WriteFile(owned, []byte("x"), 0o600); err != nil {
		t.Fatal(err)
	}
	s := &Service{dir: dir}

	s.removeImage(filepath.Join(imgDir, "..", "queue.json"))
	if _, err := os.Stat(sibling); err != nil {
		t.Fatalf("traversal removed a sibling: %v", err)
	}
	s.removeImage(sibling)
	if _, err := os.Stat(sibling); err != nil {
		t.Fatalf("unrelated path removed a sibling: %v", err)
	}
	s.removeImage("")
	if _, err := os.Stat(sibling); err != nil {
		t.Fatalf("empty path removed a sibling: %v", err)
	}
	s.removeImage(owned)
	if _, err := os.Stat(owned); !os.IsNotExist(err) {
		t.Fatalf("owned image not removed: %v", err)
	}
}

// A natural expiry must drop the timer entry, or the map grows by one timer per
// id for the whole session. No bus is needed: the store's emit is a no-op here,
// so the test exercises arm's closure directly.
func TestNaturalExpiryDeletesTheTimerEntry(t *testing.T) {
	s := &Service{dir: t.TempDir(), timers: map[uint32]*time.Timer{}}
	s.store = NewStore(func(id, reason uint32) {}, func(live, history []Popup) {}, nil)
	id, err := s.Notify("app", 0, "", "s", "b", nil, nil, 50)
	if err != nil {
		t.Fatalf("Notify: %v", err)
	}

	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		s.mu.Lock()
		_, present := s.timers[id]
		s.mu.Unlock()
		if !present {
			return
		}
		time.Sleep(5 * time.Millisecond)
	}
	t.Fatalf("timer entry for id %d still present after expiry", id)
}