1// Copyright 2016 VMware, Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package event
16
17import (
18	"testing"
19
20	"github.com/vmware/vic/lib/portlayer/event/collector/vsphere"
21	"github.com/vmware/vic/lib/portlayer/event/events"
22
23	"github.com/vmware/govmomi/vim25/types"
24
25	"github.com/stretchr/testify/assert"
26)
27
28func TestNewManager(t *testing.T) {
29	mgr := NewEventManager()
30	assert.NotNil(t, mgr)
31}
32
33func TestTopic(t *testing.T) {
34	vmEvent := newVMEvent()
35	assert.Equal(t, vmEvent.Topic(), "vsphere.VMEvent")
36}
37
38func TestSubscribe(t *testing.T) {
39	mgr := NewEventManager()
40	topic := events.NewEventType(vsphere.VMEvent{}).Topic()
41	mgr.Subscribe(topic, "tester", callback)
42	subs := mgr.Subscribers()
43	assert.Equal(t, 1, len(subs))
44	assert.Equal(t, 1, mgr.Subscribed())
45
46	mgr.Subscribe(topic, "tester2", callback)
47	subs = mgr.Subscribers()
48
49	// should still have 1 topic
50	assert.Equal(t, 1, len(subs))
51	// now two subscribers for that topic
52	assert.Equal(t, 2, mgr.Subscribed())
53
54	mgr.Subscribe(events.NewEventType(&vsphere.VMEvent{}).Topic(), "tester3", callback)
55	subs = mgr.Subscribers()
56	// should still have 1 topic
57	assert.Equal(t, 1, len(subs))
58	// now two subscribers for that topic
59	assert.Equal(t, 3, mgr.Subscribed())
60
61	mgr.Unsubscribe(topic, "tester2")
62	subs = mgr.Subscribers()
63	// should still have 1 topic
64	assert.Equal(t, 1, len(subs))
65	// now two subscribers for that topic
66	assert.Equal(t, 2, mgr.Subscribed())
67
68	mgr.Unsubscribe(events.NewEventType(&vsphere.VMEvent{}).Topic(), "tester3")
69	subs = mgr.Subscribers()
70	// should still have 1 topic
71	assert.Equal(t, 1, len(subs))
72	// now one subscribers for that topic
73	assert.Equal(t, 1, mgr.Subscribed())
74
75}
76
77func TestRegisterCollector(t *testing.T) {
78	mgr := NewEventManager()
79	// register nil
80	mgr.RegisterCollector(nil)
81	assert.Equal(t, 0, len(mgr.Collectors()))
82}
83
84// utility methods
85func newVMMO() *types.ManagedObjectReference {
86	return &types.ManagedObjectReference{Value: "101", Type: "vm"}
87}
88
89func newBaseEvent() types.BaseEvent {
90	vm := newVMMO()
91	return types.BaseEvent(&types.VmPoweredOnEvent{VmEvent: types.VmEvent{Event: types.Event{Vm: &types.VmEventArgument{Vm: *vm}}}})
92}
93
94func newVMEvent() *vsphere.VMEvent {
95	return vsphere.NewVMEvent(newBaseEvent())
96}
97
98func callback(e events.Event) {}
99