-
Notifications
You must be signed in to change notification settings - Fork 302
/
events.go
284 lines (256 loc) · 6.79 KB
/
events.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
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
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package test
import (
"bytes"
"context"
"sync"
"go.thethings.network/lorawan-stack/v3/pkg/events"
"go.thethings.network/lorawan-stack/v3/pkg/ttnpb"
"google.golang.org/protobuf/proto"
)
type MockEventPubSub struct {
PublishFunc func(...events.Event)
SubscribeFunc func(context.Context, []string, []*ttnpb.EntityIdentifiers, events.Handler) error
}
// Publish calls PublishFunc if set and panics otherwise.
func (m MockEventPubSub) Publish(evs ...events.Event) {
if m.PublishFunc == nil {
panic("Publish called, but not set")
}
m.PublishFunc(evs...)
}
// Subscribe calls SubscribeFunc if set and panics otherwise.
func (m MockEventPubSub) Subscribe(ctx context.Context, names []string, ids []*ttnpb.EntityIdentifiers, hdl events.Handler) error {
if m.SubscribeFunc == nil {
panic("Subscribe called, but not set")
}
return m.SubscribeFunc(ctx, names, ids, hdl)
}
type EventPubSubPublishRequest struct {
Event events.Event
Response chan<- struct{}
}
func MakeEventPubSubPublishChFunc(reqCh chan<- EventPubSubPublishRequest) func(...events.Event) {
return func(evs ...events.Event) {
for _, ev := range evs {
respCh := make(chan struct{})
reqCh <- EventPubSubPublishRequest{
Event: ev,
Response: respCh,
}
<-respCh
}
}
}
func AssertEventPubSubPublishRequest(ctx context.Context, reqCh <-chan EventPubSubPublishRequest, assert func(ev events.Event) bool) bool {
t := MustTFromContext(ctx)
t.Helper()
select {
case <-ctx.Done():
t.Error("Timed out while waiting for events.Publish to be called")
return false
case req := <-reqCh:
t.Log("events.Publish called")
if !assert(req.Event) {
return false
}
select {
case <-ctx.Done():
t.Error("Timed out while waiting for events.Publish response to be processed")
return false
case req.Response <- struct{}{}:
return true
}
}
}
func AssertEventPubSubPublishRequests(ctx context.Context, reqCh <-chan EventPubSubPublishRequest, n int, assert func(evs ...events.Event) bool) bool {
t := MustTFromContext(ctx)
t.Helper()
var evs []events.Event
for i := 0; i < n; i++ {
if !AssertEventPubSubPublishRequest(ctx, reqCh, func(ev events.Event) bool {
t.Logf("Received event number %d out of %d expected: %v", i+1, n, ev)
evs = append(evs, ev)
return true
}) {
t.Errorf("Failed to receive event number %d out of %d expected", i+1, n)
return false
}
}
return assert(evs...)
}
type EventEqualConfig struct {
UniqueID bool
Time bool
Identifiers bool
Data bool
CorrelationIDs bool
Origin bool
Context bool
Visibility bool
Authentication bool
RemoteIP bool
UserAgent bool
}
func MakeEventEqual(conf EventEqualConfig) func(a, b events.Event) bool {
return func(a, b events.Event) bool {
if a == nil {
return b == nil
}
ap, err := events.Proto(a)
if err != nil {
return false
}
bp, err := events.Proto(b)
if err != nil {
return false
}
if !conf.UniqueID {
ap.UniqueId = ""
bp.UniqueId = ""
}
if !conf.Time {
ap.Time = nil
bp.Time = nil
}
if !conf.Identifiers {
ap.Identifiers = nil
bp.Identifiers = nil
}
if !conf.Data {
ap.Data = nil
bp.Data = nil
}
if !conf.CorrelationIDs {
ap.CorrelationIds = nil
bp.CorrelationIds = nil
}
if !conf.Origin {
ap.Origin = ""
bp.Origin = ""
}
if !conf.Context {
ap.Context = nil
bp.Context = nil
}
if !conf.Visibility {
ap.Visibility = nil
bp.Visibility = nil
}
if !conf.Authentication {
ap.Authentication = nil
bp.Authentication = nil
}
if !conf.RemoteIP {
ap.RemoteIp = ""
bp.RemoteIp = ""
}
if !conf.UserAgent {
ap.UserAgent = ""
bp.UserAgent = ""
}
apb, err := proto.Marshal(ap)
if err != nil {
return false
}
bpb, err := proto.Marshal(bp)
if err != nil {
return false
}
return bytes.Equal(apb, bpb)
}
}
var EventEqual = MakeEventEqual(EventEqualConfig{
Identifiers: true,
Data: true,
CorrelationIDs: true,
Origin: true,
Context: true,
Visibility: true,
RemoteIP: true,
UserAgent: true,
})
func EventBuilderEqual(a, b events.Builder) bool {
ctx := Context()
return EventEqual(a.New(ctx), b.New(ctx))
}
var (
eventsPubSubMu = &sync.RWMutex{}
eventsPubSub events.PubSub = &MockEventPubSub{
PublishFunc: func(...events.Event) {},
SubscribeFunc: func(context.Context, []string, []*ttnpb.EntityIdentifiers, events.Handler) error { return nil },
}
)
func init() {
events.SetDefaultPubSub(&MockEventPubSub{
PublishFunc: func(evs ...events.Event) {
eventsPubSub.Publish(evs...)
},
SubscribeFunc: func(ctx context.Context, names []string, ids []*ttnpb.EntityIdentifiers, hdl events.Handler) error {
return eventsPubSub.Subscribe(ctx, names, ids, hdl)
},
})
}
// SetDefaultEventsPubSub calls events.SetDefaultPubSub and
// returns a function that can be used to undo the action.
// Following calls to SetDefaultEventsPubSub will block until undo function is called.
func SetDefaultEventsPubSub(ps events.PubSub) func() {
eventsPubSubMu.Lock()
oldPS := eventsPubSub
eventsPubSub = ps
return func() {
eventsPubSub = oldPS
eventsPubSubMu.Unlock()
}
}
// CollectEvents collects events published by f.
func CollectEvents(f func()) []events.Event {
var evs []events.Event
defer SetDefaultEventsPubSub(&MockEventPubSub{
PublishFunc: func(evts ...events.Event) { evs = append(evs, evts...) },
})()
f()
return evs
}
// RedirectEvents redirects the published events to the
// provided channel until the returned function is called.
func RedirectEvents(ch chan events.Event) func() {
return SetDefaultEventsPubSub(&MockEventPubSub{
PublishFunc: func(evs ...events.Event) {
for _, ev := range evs {
ch <- ev
}
},
SubscribeFunc: func(ctx context.Context, names []string, ids []*ttnpb.EntityIdentifiers, hdl events.Handler) error {
return nil
},
})
}
// WaitEvent waits for a specific event to be sent to the channel.
func WaitEvent(ctx context.Context, ch chan events.Event, name string) bool {
for {
select {
case <-ctx.Done():
return false
case ev, ok := <-ch:
if !ok {
panic("channel is closed")
}
if ev.Name() == name {
return true
}
}
}
}