File: LibCMocks.h

package info (click to toggle)
zookeeper 3.9.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,804 kB
  • sloc: java: 121,943; cpp: 13,986; ansic: 12,419; javascript: 11,754; xml: 4,965; python: 2,829; sh: 2,444; makefile: 241; perl: 114
file content (408 lines) | stat: -rw-r--r-- 11,538 bytes parent folder | download | duplicates (9)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef LIBCMOCKS_H_
#define LIBCMOCKS_H_

#include <string>
#include <vector>
#include <deque>

#include <errno.h>
#include <string.h>

#include "MocksBase.h"
#include "LibCSymTable.h"
#include "ThreadingUtil.h"

// *****************************************************************************
// gethostbyname

class Mock_gethostbyname: public Mock
{
public:
    struct HostEntry: public hostent {
        HostEntry(const char* hostName,short addrtype);
        ~HostEntry();
        HostEntry& addAlias(const char* alias);
        HostEntry& addAddress(const char* addr4);
    };

    Mock_gethostbyname():current(0){mock_=this;}
    virtual ~Mock_gethostbyname();
    HostEntry& addHostEntry(const char* hostName,short addrtype=AF_INET);
    virtual hostent* call(const char* name);

    typedef std::vector<HostEntry*> HostEntryCollection;
    HostEntryCollection gethostbynameReturns;
    int current;
    static Mock_gethostbyname* mock_;
};

class MockFailed_gethostbyname: public Mock_gethostbyname
{
public:
    MockFailed_gethostbyname():h_errnoReturn(HOST_NOT_FOUND) {}

    int h_errnoReturn;
    virtual hostent* call(const char* name) {
        h_errno=h_errnoReturn;
        return 0;
    }
};

// *****************************************************************************
// calloc

class Mock_calloc: public Mock
{
public:
    Mock_calloc():errnoOnFailure(ENOMEM),callsBeforeFailure(-1),counter(0) {
        mock_=this;
    }
    virtual ~Mock_calloc() {mock_=0;}

    int errnoOnFailure;
    int callsBeforeFailure;
    int counter;
    virtual void* call(size_t p1, size_t p2);

    static Mock_calloc* mock_;
};

// *****************************************************************************
// realloc

class Mock_realloc: public Mock
{
public:
    Mock_realloc():errnoOnFailure(ENOMEM),callsBeforeFailure(-1),counter(0) {
        mock_=this;
    }
    virtual ~Mock_realloc() {mock_=0;}

    int errnoOnFailure;
    int callsBeforeFailure;
    int counter;
    virtual void* call(void* p, size_t s);

    static Mock_realloc* mock_;
};

// *****************************************************************************
// random

class Mock_random: public Mock
{
public:
    Mock_random():currentIdx(0) {mock_=this;}
    virtual ~Mock_random() {mock_=0;}

    int currentIdx;
    std::vector<int> randomReturns;
    virtual int call();
    void setSeed(unsigned long){currentIdx=0;}

    static Mock_random* mock_;
};

// *****************************************************************************
// no-op free; keeps track of all deallocation requests
class Mock_free_noop: public Mock
{
    Mutex mx;
    std::vector<void*> requested;
public:
    Mock_free_noop():nested(0),callCounter(0){mock_=this;}
    virtual ~Mock_free_noop(){
        mock_=0;
        freeRequested();
    }
    
    int nested;
    int callCounter;
    virtual void call(void* p);
    void freeRequested();
    void disable(){mock_=0;}
    // returns number of times the pointer was freed
    int getFreeCount(void*);
    bool isFreed(void*);
    
    static Mock_free_noop* mock_;
};

// *****************************************************************************
// socket and related system calls

class Mock_socket: public Mock
{
public:
    static const int FD=63;
    Mock_socket():socketReturns(FD),closeReturns(0),getsocketoptReturns(0),
        optvalSO_ERROR(0),
        setsockoptReturns(0),connectReturns(0),connectErrno(0),
        sendErrno(0),recvErrno(0)
    {
        mock_=this;
    }
    virtual ~Mock_socket(){mock_=0;}

    int socketReturns;
    virtual int callSocket(int domain, int type, int protocol){
        return socketReturns;
    }
    int closeReturns;
    virtual int callClose(int fd){
        return closeReturns;
    }
    int getsocketoptReturns;
    int optvalSO_ERROR;
    virtual int callGet(int s,int level,int optname,void *optval,socklen_t *len){
        if(level==SOL_SOCKET && optname==SO_ERROR){
            setSO_ERROR(optval,*len);
        }
        return getsocketoptReturns;
    }
    virtual void setSO_ERROR(void *optval,socklen_t len){
        memcpy(optval,&optvalSO_ERROR,len);
    }
    
    int setsockoptReturns;
    virtual int callSet(int s,int level,int optname,const void *optval,socklen_t len){
        return setsockoptReturns;
    }
    int connectReturns;
    int connectErrno;
    virtual int callConnect(int s,const struct sockaddr *addr,socklen_t len){
        errno=connectErrno;
        return connectReturns;
    }
    
    virtual void notifyBufferSent(const std::string& buffer){}
    
    int sendErrno;
    std::string sendBuffer;
    virtual ssize_t callSend(int s,const void *buf,size_t len,int flags){
        if(sendErrno!=0){
            errno=sendErrno;
            return -1;
        }
        // first call to send() is always the length of the buffer to follow
        bool sendingLength=sendBuffer.size()==0;
        // overwrite the length bytes
        sendBuffer.assign((const char*)buf,len);
        if(!sendingLength){
            notifyBufferSent(sendBuffer);
            sendBuffer.erase();
        }
        return len;
    }

    int recvErrno;
    std::string recvReturnBuffer;
    virtual ssize_t callRecv(int s,void *buf,size_t len,int flags){
        if(recvErrno!=0){
            errno=recvErrno;
            return -1;
        }
        int k=std::min(len,recvReturnBuffer.length());
        if(k==0)
            return 0;
        memcpy(buf,recvReturnBuffer.data(),k);
        recvReturnBuffer.erase(0,k);
        return k;
    }
    virtual bool hasMoreRecv() const{
        return recvReturnBuffer.size()!=0;
    }
    static Mock_socket* mock_;
};

// *****************************************************************************
// fcntl
class Mock_fcntl: public Mock
{
public:
    Mock_fcntl():callReturns(0),trapFD(-1){mock_=this;}
    ~Mock_fcntl(){mock_=0;}
    
    int callReturns;
    int trapFD;
    virtual int call(int fd, int cmd, void* arg){
        if(trapFD==-1)
            return LIBC_SYMBOLS.fcntl(fd,cmd,arg);
        return callReturns;
    }

    static Mock_fcntl* mock_;
};

// *****************************************************************************
// select
class Mock_select: public Mock
{
public:
    Mock_select(Mock_socket* s,int fd):sock(s),
        callReturns(0),myFD(fd),timeout(50)
    {
        mock_=this;
    }
    ~Mock_select(){mock_=0;}
    
    Mock_socket* sock;
    int callReturns;
    int myFD;
    int timeout; //in millis
    virtual int call(int nfds,fd_set *rfds,fd_set *wfds,fd_set *efds,struct timeval *tv){
        bool isWritableRequested=(wfds && FD_ISSET(myFD,wfds));
        if(rfds) FD_CLR(myFD,rfds);
        if(wfds) FD_CLR(myFD,wfds);
        // this timeout is only to prevent a tight loop
        timeval myTimeout={0,0};
        if(!isWritableRequested && !isFDReadable()){
            myTimeout.tv_sec=timeout/1000;
            myTimeout.tv_usec=(timeout%1000)*1000;
        }
        LIBC_SYMBOLS.select(nfds,rfds,wfds,efds,&myTimeout);
        // myFD is always writable
        if(isWritableRequested) FD_SET(myFD,wfds);
        // myFD is only readable if the socket has anything to read
        if(isFDReadable() && rfds) FD_SET(myFD,rfds);
        return callReturns;
    }

    virtual bool isFDReadable() const {
        return sock->hasMoreRecv();
    }
    
    static Mock_select* mock_;
};

// *****************************************************************************
// poll
// the last element of the pollfd array is expected to be test FD
class Mock_poll: public Mock
{
public:
    Mock_poll(Mock_socket* s,int fd):sock(s),
        callReturns(1),myFD(fd),timeout(50)
    {
        mock_=this;
    }
    ~Mock_poll(){mock_=0;}
    
    Mock_socket* sock;
    int callReturns;
    int myFD;
    int timeout; //in millis
    virtual int call(struct pollfd *fds, POLL_NFDS_TYPE nfds, int to) {
        pollfd* myPoll=0;
        if(fds[nfds-1].fd==myFD)
            myPoll=&fds[nfds-1];
        bool isWritableRequested=false;
        if(myPoll!=0){
            isWritableRequested=myPoll->events&POLLOUT;
            nfds--;
        }
        LIBC_SYMBOLS.poll(fds,nfds,(!isWritableRequested&&!isFDReadable())?timeout:0);
        if(myPoll!=0){
            // myFD is always writable if requested
            myPoll->revents=isWritableRequested?POLLOUT:0;
            // myFD is only readable if the socket has anything to read
            myPoll->revents|=isFDReadable()?POLLIN:0;
        }
        return callReturns;
    }

    virtual bool isFDReadable() const {
        return sock->hasMoreRecv();
    }
    
    static Mock_poll* mock_;
};

// *****************************************************************************
// gettimeofday
class Mock_gettimeofday: public Mock
{
public:
    Mock_gettimeofday(){
        LIBC_SYMBOLS.gettimeofday(&tv,0);
        mock_=this;
    }
    Mock_gettimeofday(const Mock_gettimeofday& other):tv(other.tv){}
    Mock_gettimeofday(int32_t sec,int32_t usec){
        tv.tv_sec=sec;
        tv.tv_usec=usec;
    }
    ~Mock_gettimeofday(){mock_=0;}
    
    timeval tv;
    virtual int call(struct timeval *tp, GETTIMEOFDAY_ARG2_TYPE tzp){
        *tp=tv;
        return 0;
    }
    operator timeval() const{
        return tv;
    }
    // advance secs
    virtual void tick(int howmuch=1){tv.tv_sec+=howmuch;}
    // advance milliseconds
    // can move the clock forward as well as backward by providing a negative
    // number
    virtual void millitick(int howmuch=1){
        int ms=tv.tv_usec/1000+howmuch;
        tv.tv_sec+=ms/1000;
        // going backward?
        if(ms<0){
            ms=1000-(-ms%1000); //wrap millis around
        }
        tv.tv_usec=(ms%1000)*1000;
    }
    virtual void tick(const timeval& howmuch){
        // add milliseconds (discarding microsecond portion)
        long ms=tv.tv_usec/1000+howmuch.tv_usec/1000;
        tv.tv_sec+=howmuch.tv_sec+ms/1000;
        tv.tv_usec=(ms%1000)*1000;
    }
    static Mock_gettimeofday* mock_;
};

// discard microseconds!
inline bool operator==(const timeval& lhs, const timeval& rhs){
    return rhs.tv_sec==lhs.tv_sec && rhs.tv_usec/1000==lhs.tv_usec/1000;
}

// simplistic implementation: no normalization, assume lhs >= rhs,
// discarding microseconds
inline timeval operator-(const timeval& lhs, const timeval& rhs){
    timeval res;
    res.tv_sec=lhs.tv_sec-rhs.tv_sec;
    res.tv_usec=(lhs.tv_usec/1000-rhs.tv_usec/1000)*1000;
    if(res.tv_usec<0){
        res.tv_sec--;
        res.tv_usec=1000000+res.tv_usec%1000000; // wrap the millis around
    }
    return res;
}

inline int32_t toMilliseconds(const timeval& tv){
    return tv.tv_sec*1000+tv.tv_usec/1000;    
}

#endif /*LIBCMOCKS_H_*/