-
Notifications
You must be signed in to change notification settings - Fork 1
/
beacon_test.go
91 lines (84 loc) · 2.68 KB
/
beacon_test.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
// Copyright 2020 The go-zeromq Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package zyre
import (
"bytes"
"math/rand"
"reflect"
"testing"
"time"
)
func TestAPICommand(t *testing.T) {
b := &Beacon{}
reqs := []struct {
id string
payload interface{}
got func() interface{}
}{
{id: "CONFIGURE", payload: 5555,
got: func() interface{} { return b.port }},
{id: "PUBLISH", payload: []byte("bla"),
got: func() interface{} { return b.transmit }},
{id: "SILENCE", payload: []byte(nil),
got: func() interface{} { return b.transmit }},
{id: "UNSUBSCRIBE", payload: []byte(nil),
got: func() interface{} { return b.filter }},
{id: "INTERVAL", payload: 1 * time.Second,
got: func() interface{} { return b.interval }},
{id: "INTERFACE", payload: "eth",
got: func() interface{} { return b.ifc }},
{id: "SUBSCRIBE", payload: []byte("bar"),
got: func() interface{} { return b.filter }},
{id: "VERBOSE", payload: true,
got: func() interface{} { return b.verbose }},
}
for _, tt := range reqs {
tick := time.Tick(1 * time.Second)
t.Run(tt.id, func(t *testing.T) {
b.handleCommand(&Cmd{ID: tt.id, Payload: tt.payload}, &tick)
if got := tt.got(); !reflect.DeepEqual(got, tt.payload) {
t.Errorf("expected %v, got %v", tt.payload, got)
}
})
b.handleCommand(&Cmd{ID: "INVALID"}, &tick)
}
}
func TestBeacon(t *testing.T) {
port := random(5670, 15670)
beacon1 := makeBeacon(port, "BEACON1", "BEACON", t)
defer beacon1.Close()
beacon2 := makeBeacon(port, "BEACON2", "BEACON1", t)
defer beacon2.Close()
beacon3 := makeBeacon(port, "FOO", "BAR", t)
defer beacon3.Close()
for i := 0; i < 5; i++ {
select {
case signal := <-beacon1.Signals:
expected := []byte("BEACON2")
if !bytes.Equal(expected, signal.Transmit) {
t.Errorf("expected %s, got %s", expected, signal.Transmit)
}
case signal := <-beacon2.Signals:
expected := []byte("BEACON1")
if !bytes.Equal(expected, signal.Transmit) {
t.Errorf("expected %s, got %s", expected, signal.Transmit)
}
case signal := <-beacon3.Signals:
t.Errorf("beacon3 shouldn't receive anything, got %q, %q", signal.Addr,
signal.Transmit)
}
}
}
func makeBeacon(port int, publish string, subscribe string, t *testing.T) *Beacon {
b := NewBeacon()
b.SetBeaconCmd(&Cmd{ID: "CONFIGURE", Payload: port})
b.SetBeaconCmd(&Cmd{ID: "INTERVAL", Payload: 1 * time.Millisecond})
b.SetBeaconCmd(&Cmd{ID: "SUBSCRIBE", Payload: []byte(subscribe)})
b.SetBeaconCmd(&Cmd{ID: "PUBLISH", Payload: []byte(publish)})
return b
}
func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}