forked from nytimes/gizmo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sub.go
85 lines (71 loc) · 2.02 KB
/
sub.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
package pubsubtest
import (
"encoding/json"
"github.com/NYTimes/gizmo/pubsub"
"github.com/golang/protobuf/proto"
)
type (
// TestSubscriber is a simple implementation of pubsub.Subscriber meant to
// help mock out any implementations.
TestSubscriber struct {
// ProtoMessages will be marshalled into []byte and used to mock out
// a feed if it is populated.
ProtoMessages []proto.Message
// JSONMessages will be marshalled into []byte and used to mock out
// a feed if it is populated.
JSONMessages []interface{}
// GivenErrError will be returned by the TestSubscriber on Err().
// Good for testing error scenarios.
GivenErrError error
// GivenStopError will be returned by the TestSubscriber on Stop().
// Good for testing error scenarios.
GivenStopError error
// FoundError will contain any errors encountered while marshalling
// the JSON and protobuf struct.
FoundError error
}
// TestSubsMessage represents a test subscriber message.
TestSubsMessage struct {
Msg []byte
Doned bool
}
)
// Message returns the subscriber message.
func (m *TestSubsMessage) Message() []byte {
return m.Msg
}
// Done sets the Doned field to true.
func (m *TestSubsMessage) Done() error {
m.Doned = true
return nil
}
// Start will populate and return the test channel for the subscriber
func (t *TestSubscriber) Start() <-chan pubsub.SubscriberMessage {
msgs := make(chan pubsub.SubscriberMessage, len(t.JSONMessages)+len(t.ProtoMessages))
for _, pmsg := range t.ProtoMessages {
msg, err := proto.Marshal(pmsg)
if err != nil {
t.FoundError = err
continue
}
msgs <- &TestSubsMessage{Msg: msg}
}
for _, jmsg := range t.JSONMessages {
msg, err := json.Marshal(jmsg)
if err != nil {
t.FoundError = err
continue
}
msgs <- &TestSubsMessage{Msg: msg}
}
close(msgs)
return msgs
}
// Err returns the GivenErrError value.
func (t *TestSubscriber) Err() error {
return t.GivenErrError
}
// Stop returns the GivenStopError value.
func (t *TestSubscriber) Stop() error {
return t.GivenStopError
}