1 // Copyright (c) 2017 Cisco and/or its affiliates.
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:
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 // Package mock is an alternative VPP adapter aimed for unit/integration testing where the
16 // actual communication with VPP is not demanded.
25 "git.fd.io/govpp.git/core"
26 "github.com/lunixbochs/struc"
28 "git.fd.io/govpp.git/adapter"
29 "git.fd.io/govpp.git/adapter/mock/binapi"
30 "git.fd.io/govpp.git/api"
33 // VppAdapter represents a mock VPP adapter that can be used for unit/integration testing instead of the vppapiclient adapter.
34 type VppAdapter struct {
35 callback func(context uint32, msgId uint16, data []byte)
37 msgNameToIds map[string]uint16
38 msgIDsToName map[uint16]string
40 binAPITypes map[string]reflect.Type
44 // defaultReply is a default reply message that mock adapter returns for a request.
45 type defaultReply struct {
49 // MessageDTO is a structure used for propagating information to ReplyHandlers.
50 type MessageDTO struct {
57 // ReplyHandler is a type that allows to extend the behaviour of VPP mock.
58 // Return value ok is used to signalize that mock reply is calculated and ready to be used.
59 type ReplyHandler func(request MessageDTO) (reply []byte, msgID uint16, ok bool)
62 defaultReplyMsgID = 1 // default message ID for the reply to be sent back via callback
65 var replies []api.Message // FIFO queue of messages
66 var replyHandlers []ReplyHandler // callbacks that are able to calculate mock responses
67 var repliesLock sync.Mutex // mutex for the queue
68 var mode = 0 // mode in which the mock operates
70 const useRepliesQueue = 1 // use replies in the queue instead of the default one
71 const useReplyHandlers = 2 //use ReplyHandler
73 // NewVppAdapter returns a new mock adapter.
74 func NewVppAdapter() adapter.VppAdapter {
78 // Connect emulates connecting the process to VPP.
79 func (a *VppAdapter) Connect() error {
83 // Disconnect emulates disconnecting the process from VPP.
84 func (a *VppAdapter) Disconnect() {
88 // GetMsgNameByID returns message name for specified message ID.
89 func (a *VppAdapter) GetMsgNameByID(msgID uint16) (string, bool) {
92 return "control_ping", true
94 return "control_ping_reply", true
96 return "sw_interface_dump", true
98 return "sw_interface_details", true
102 defer a.access.Unlock()
104 msgName, found := a.msgIDsToName[msgID]
106 return msgName, found
109 // RegisterBinAPITypes registers binary API message types in the mock adapter.
110 func (a *VppAdapter) RegisterBinAPITypes(binAPITypes map[string]reflect.Type) {
112 defer a.access.Unlock()
114 for _, v := range binAPITypes {
115 if msg, ok := reflect.New(v).Interface().(api.Message); ok {
116 a.binAPITypes[msg.GetMessageName()] = v
121 // ReplyTypeFor returns reply message type for given request message name.
122 func (a *VppAdapter) ReplyTypeFor(requestMsgName string) (reflect.Type, uint16, bool) {
123 replyName, foundName := binapi.ReplyNameFor(requestMsgName)
125 if reply, found := a.binAPITypes[replyName]; found {
126 msgID, err := a.GetMsgID(replyName, "")
128 return reply, msgID, found
136 // ReplyFor returns reply message for given request message name.
137 func (a *VppAdapter) ReplyFor(requestMsgName string) (api.Message, uint16, bool) {
138 replType, msgID, foundReplType := a.ReplyTypeFor(requestMsgName)
140 msgVal := reflect.New(replType)
141 if msg, ok := msgVal.Interface().(api.Message); ok {
142 log.Println("FFF ", replType, msgID, foundReplType)
143 return msg, msgID, true
150 // ReplyBytes encodes the mocked reply into binary format.
151 func (a *VppAdapter) ReplyBytes(request MessageDTO, reply api.Message) ([]byte, error) {
152 replyMsgID, err := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
154 log.Println("ReplyBytesE ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID,
158 log.Println("ReplyBytes ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID)
160 buf := new(bytes.Buffer)
161 struc.Pack(buf, &core.VppReplyHeader{VlMsgID: replyMsgID, Context: request.ClientID})
162 struc.Pack(buf, reply)
164 return buf.Bytes(), nil
167 // GetMsgID returns mocked message ID for the given message name and CRC.
168 func (a *VppAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
172 case "control_ping_reply":
174 case "sw_interface_dump":
176 case "sw_interface_details":
181 defer a.access.Unlock()
184 msgID, found := a.msgNameToIds[msgName]
191 a.msgNameToIds[msgName] = msgID
192 a.msgIDsToName[msgID] = msgName
194 log.Println("VPP GetMessageId ", msgID, " name:", msgName, " crc:", msgCrc)
199 // initMaps initializes internal maps (if not already initialized).
200 func (a *VppAdapter) initMaps() {
201 if a.msgIDsToName == nil {
202 a.msgIDsToName = map[uint16]string{}
203 a.msgNameToIds = map[string]uint16{}
207 if a.binAPITypes == nil {
208 a.binAPITypes = map[string]reflect.Type{}
212 // SendMsg emulates sending a binary-encoded message to VPP.
213 func (a *VppAdapter) SendMsg(clientID uint32, data []byte) error {
215 case useReplyHandlers:
217 for i := len(replyHandlers) - 1; i >= 0; i-- {
218 replyHandler := replyHandlers[i]
220 buf := bytes.NewReader(data)
221 reqHeader := core.VppRequestHeader{}
222 struc.Unpack(buf, &reqHeader)
225 reqMsgName, _ := a.msgIDsToName[reqHeader.VlMsgID]
228 reply, msgID, finished := replyHandler(MessageDTO{reqHeader.VlMsgID, reqMsgName,
231 a.callback(clientID, msgID, reply)
236 case useRepliesQueue:
238 defer repliesLock.Unlock()
240 // pop all replies from queue
241 for i, reply := range replies {
242 if i > 0 && reply.GetMessageName() == "control_ping_reply" {
243 // hack - do not send control_ping_reply immediately, leave it for the the next callback
244 replies = []api.Message{}
245 replies = append(replies, reply)
248 msgID, _ := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
249 buf := new(bytes.Buffer)
250 if reply.GetMessageType() == api.ReplyMessage {
251 struc.Pack(buf, &core.VppReplyHeader{VlMsgID: msgID, Context: clientID})
252 } else if reply.GetMessageType() == api.EventMessage {
253 struc.Pack(buf, &core.VppEventHeader{VlMsgID: msgID, Context: clientID})
254 } else if reply.GetMessageType() == api.RequestMessage {
255 struc.Pack(buf, &core.VppRequestHeader{VlMsgID: msgID, Context: clientID})
257 struc.Pack(buf, &core.VppOtherHeader{VlMsgID: msgID})
259 struc.Pack(buf, reply)
260 a.callback(clientID, msgID, buf.Bytes())
262 if len(replies) > 0 {
263 replies = []api.Message{}
269 // return default reply
270 buf := new(bytes.Buffer)
271 msgID := uint16(defaultReplyMsgID)
272 struc.Pack(buf, &core.VppReplyHeader{VlMsgID: msgID, Context: clientID})
273 struc.Pack(buf, &defaultReply{})
274 a.callback(clientID, msgID, buf.Bytes())
279 // SetMsgCallback sets a callback function that will be called by the adapter whenever a message comes from the mock.
280 func (a *VppAdapter) SetMsgCallback(cb func(context uint32, msgID uint16, data []byte)) {
284 // WaitReady mocks waiting for VPP
285 func (a *VppAdapter) WaitReady() error {
289 // MockReply stores a message to be returned when the next request comes. It is a FIFO queue - multiple replies
290 // can be pushed into it, the first one will be popped when some request comes.
291 // Using of this method automatically switches the mock into th useRepliesQueue mode.
292 func (a *VppAdapter) MockReply(msg api.Message) {
294 defer repliesLock.Unlock()
296 replies = append(replies, msg)
297 mode = useRepliesQueue
300 // MockReplyHandler registers a handler function that is supposed to generate mock responses to incoming requests.
301 // Using of this method automatically switches the mock into th useReplyHandlers mode.
302 func (a *VppAdapter) MockReplyHandler(replyHandler ReplyHandler) {
304 defer repliesLock.Unlock()
306 replyHandlers = append(replyHandlers, replyHandler)
307 mode = useReplyHandlers