blob: 818009fe0c04147d4bd85d129b54fe37b8c5340e [file] [log] [blame]
Matteo Scandolo11006992019-08-28 11:29:46 -07001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package devices
18
19import (
20 "github.com/looplab/fsm"
21 "gotest.tools/assert"
22 "testing"
23)
24
25var (
26 originalNewFSM func(initial string, events []fsm.EventDesc, callbacks map[string]fsm.Callback) *fsm.FSM
27)
28
Matteo Scandolo10f965c2019-09-24 10:40:46 -070029func setUpHelpers() {
Matteo Scandolo11006992019-08-28 11:29:46 -070030 originalNewFSM = newFSM
31}
32
Matteo Scandolo10f965c2019-09-24 10:40:46 -070033func tearDownHelpers() {
Matteo Scandolo11006992019-08-28 11:29:46 -070034 newFSM = originalNewFSM
35}
36
Matteo Scandolo11006992019-08-28 11:29:46 -070037func Test_Helpers(t *testing.T) {
38
Matteo Scandolo10f965c2019-09-24 10:40:46 -070039 setUpHelpers()
40
Matteo Scandolo11006992019-08-28 11:29:46 -070041 // feedback values for the mock
42 called := 0
43 args := struct {
Matteo Scandolo10f965c2019-09-24 10:40:46 -070044 initial string
45 events []fsm.EventDesc
Matteo Scandolo11006992019-08-28 11:29:46 -070046 callbacks map[string]fsm.Callback
47 }{}
48
49 // creating the mock function
Matteo Scandolo10f965c2019-09-24 10:40:46 -070050 mockFSM := func(initial string, events []fsm.EventDesc, callbacks map[string]fsm.Callback) *fsm.FSM {
Matteo Scandolo11006992019-08-28 11:29:46 -070051 called++
52 args.initial = initial
53 args.events = events
54 args.callbacks = callbacks
55 return fsm.NewFSM(initial, events, callbacks)
56 }
57 newFSM = mockFSM
58
59 // params for the method under test
60 cb_called := 0
61 cb := func(e *fsm.Event) {
62 cb_called++
63 return
64 }
65
66 // calling the method under test
67 sm := getOperStateFSM(cb)
68
69 // verify
70 assert.Equal(t, called, 1, "Expected fsm.NewFSM to have been called once, instead it was called %d", called)
71 assert.Equal(t, args.initial, "down")
72
73 assert.Equal(t, args.events[0].Name, "enable")
74 assert.Equal(t, args.events[0].Src[0], "down")
75 assert.Equal(t, args.events[0].Dst, "up")
76
77 assert.Equal(t, args.events[1].Name, "disable")
78 assert.Equal(t, args.events[1].Src[0], "up")
79 assert.Equal(t, args.events[1].Dst, "down")
80
81 // this is to test that the callback is called when the state change
82 sm.Event("enable")
83 assert.Equal(t, cb_called, 1)
84
Matteo Scandolo10f965c2019-09-24 10:40:46 -070085 tearDownHelpers()
86
87}