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 "github.com/lunixbochs/struc"
27 "git.fd.io/govpp.git/adapter"
28 "git.fd.io/govpp.git/adapter/mock/binapi"
29 "git.fd.io/govpp.git/api"
32 // VppAdapter represents a mock VPP adapter that can be used for unit/integration testing instead of the vppapiclient adapter.
33 type VppAdapter struct {
34 callback func(context uint32, msgId uint16, data []byte)
36 msgNameToIds *map[string]uint16
37 msgIDsToName *map[uint16]string
39 binAPITypes map[string]reflect.Type
43 // replyHeader represents a common header of each VPP request message.
44 type requestHeader struct {
50 // replyHeader represents a common header of each VPP reply message.
51 type replyHeader struct {
56 // otherHeader represents a common header of each VPP reply message.
57 type otherHeader struct {
61 // defaultReply is a default reply message that mock adapter returns for a request.
62 type defaultReply struct {
66 // MessageDTO is a structure used for propagating information to ReplyHandlers.
67 type MessageDTO struct {
74 // ReplyHandler is a type that allows to extend the behaviour of VPP mock.
75 // Return value ok is used to signalize that mock reply is calculated and ready to be used.
76 type ReplyHandler func(request MessageDTO) (reply []byte, msgID uint16, ok bool)
79 defaultReplyMsgID = 1 // default message ID for the reply to be sent back via callback
82 var replies []api.Message // FIFO queue of messages
83 var replyHandlers []ReplyHandler // callbacks that are able to calculate mock responses
84 var repliesLock sync.Mutex // mutex for the queue
85 var mode = 0 // mode in which the mock operates
87 const useRepliesQueue = 1 // use replies in the queue instead of the default one
88 const useReplyHandlers = 2 //use ReplyHandler
90 // NewVppAdapter returns a new mock adapter.
91 func NewVppAdapter() adapter.VppAdapter {
95 // Connect emulates connecting the process to VPP.
96 func (a *VppAdapter) Connect() error {
100 // Disconnect emulates disconnecting the process from VPP.
101 func (a *VppAdapter) Disconnect() {
105 // GetMsgNameByID returns message name for specified message ID.
106 func (a *VppAdapter) GetMsgNameByID(msgID uint16) (string, bool) {
109 return "control_ping", true
111 return "control_ping_reply", true
113 return "sw_interface_dump", true
115 return "sw_interface_details", true
119 defer a.access.Unlock()
121 msgName, found := (*a.msgIDsToName)[msgID]
123 return msgName, found
126 // RegisterBinAPITypes registers binary API message types in the mock adapter.
127 func (a *VppAdapter) RegisterBinAPITypes(binAPITypes map[string]reflect.Type) {
129 defer a.access.Unlock()
131 for _, v := range binAPITypes {
132 if msg, ok := reflect.New(v).Interface().(api.Message); ok {
133 a.binAPITypes[msg.GetMessageName()] = v
138 // ReplyTypeFor returns reply message type for given request message name.
139 func (a *VppAdapter) ReplyTypeFor(requestMsgName string) (reflect.Type, uint16, bool) {
140 replyName, foundName := binapi.ReplyNameFor(requestMsgName)
142 if reply, found := a.binAPITypes[replyName]; found {
143 msgID, err := a.GetMsgID(replyName, "")
145 return reply, msgID, found
153 // ReplyFor returns reply message for given request message name.
154 func (a *VppAdapter) ReplyFor(requestMsgName string) (api.Message, uint16, bool) {
155 replType, msgID, foundReplType := a.ReplyTypeFor(requestMsgName)
157 msgVal := reflect.New(replType)
158 if msg, ok := msgVal.Interface().(api.Message); ok {
159 log.Println("FFF ", replType, msgID, foundReplType)
160 return msg, msgID, true
167 // ReplyBytes encodes the mocked reply into binary format.
168 func (a *VppAdapter) ReplyBytes(request MessageDTO, reply api.Message) ([]byte, error) {
169 replyMsgID, err := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
171 log.Println("ReplyBytesE ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID,
175 log.Println("ReplyBytes ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID)
177 buf := new(bytes.Buffer)
178 struc.Pack(buf, &replyHeader{VlMsgID: replyMsgID, Context: request.ClientID})
179 struc.Pack(buf, reply)
181 return buf.Bytes(), nil
184 // GetMsgID returns mocked message ID for the given message name and CRC.
185 func (a *VppAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
189 case "control_ping_reply":
191 case "sw_interface_dump":
193 case "sw_interface_details":
198 defer a.access.Unlock()
201 msgID, found := (*a.msgNameToIds)[msgName]
208 (*a.msgNameToIds)[msgName] = msgID
209 (*a.msgIDsToName)[msgID] = msgName
211 log.Println("VPP GetMessageId ", msgID, " name:", msgName, " crc:", msgCrc)
216 // initMaps initializes internal maps (if not already initialized).
217 func (a *VppAdapter) initMaps() {
218 if a.msgIDsToName == nil {
219 a.msgIDsToName = &map[uint16]string{}
220 a.msgNameToIds = &map[string]uint16{}
224 if a.binAPITypes == nil {
225 a.binAPITypes = map[string]reflect.Type{}
229 // SendMsg emulates sending a binary-encoded message to VPP.
230 func (a *VppAdapter) SendMsg(clientID uint32, data []byte) error {
232 case useReplyHandlers:
234 for i := len(replyHandlers) - 1; i >= 0; i-- {
235 replyHandler := replyHandlers[i]
237 buf := bytes.NewReader(data)
238 reqHeader := requestHeader{}
239 struc.Unpack(buf, &reqHeader)
242 reqMsgName, _ := (*a.msgIDsToName)[reqHeader.VlMsgID]
245 reply, msgID, finished := replyHandler(MessageDTO{reqHeader.VlMsgID, reqMsgName,
248 a.callback(clientID, msgID, reply)
253 case useRepliesQueue:
255 defer repliesLock.Unlock()
257 // pop all replies from queue
258 for i, reply := range replies {
259 if i > 0 && reply.GetMessageName() == "control_ping_reply" {
260 // hack - do not send control_ping_reply immediately, leave it for the the next callback
261 replies = []api.Message{}
262 replies = append(replies, reply)
265 msgID, _ := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
266 buf := new(bytes.Buffer)
267 if reply.GetMessageType() == api.ReplyMessage {
268 struc.Pack(buf, &replyHeader{VlMsgID: msgID, Context: clientID})
270 struc.Pack(buf, &requestHeader{VlMsgID: msgID, Context: clientID})
272 struc.Pack(buf, reply)
273 a.callback(clientID, msgID, buf.Bytes())
275 if len(replies) > 0 {
276 replies = []api.Message{}
282 // return default reply
283 buf := new(bytes.Buffer)
284 msgID := uint16(defaultReplyMsgID)
285 struc.Pack(buf, &replyHeader{VlMsgID: msgID, Context: clientID})
286 struc.Pack(buf, &defaultReply{})
287 a.callback(clientID, msgID, buf.Bytes())
292 // SetMsgCallback sets a callback function that will be called by the adapter whenever a message comes from the mock.
293 func (a *VppAdapter) SetMsgCallback(cb func(context uint32, msgID uint16, data []byte)) {
297 // WaitReady mocks waiting for VPP
298 func (a *VppAdapter) WaitReady() error {
302 // MockReply stores a message to be returned when the next request comes. It is a FIFO queue - multiple replies
303 // can be pushed into it, the first one will be popped when some request comes.
304 // Using of this method automatically switches the mock into th useRepliesQueue mode.
305 func (a *VppAdapter) MockReply(msg api.Message) {
307 defer repliesLock.Unlock()
309 replies = append(replies, msg)
310 mode = useRepliesQueue
313 // MockReplyHandler registers a handler function that is supposed to generate mock responses to incoming requests.
314 // Using of this method automatically switches the mock into th useReplyHandlers mode.
315 func (a *VppAdapter) MockReplyHandler(replyHandler ReplyHandler) {
317 defer repliesLock.Unlock()
319 replyHandlers = append(replyHandlers, replyHandler)
320 mode = useReplyHandlers