EXPECT_CALL not able to track the calls for methods called from the method under test - googletest

First of all, I'm new to Google test, so please forgive my ignorance, if any.
I'm writing unit tests using google test framework for the below class..
class MsgHandler
{
public:
MsgHandler(){}
~MsgHandler(){}
bool decode_data(unsigned char*, unsigned int,char *);
bool handle_req_state_data(char *, char *);
};
bool MsgHandler::handle_req_state_data(char *a, char *b)
{
printf("handle_req_state_data called\n");
return true;
}
bool MsgHandler::decode_data(unsigned char *a, unsigned int b,char *c)
{
printf("decode_data called\n");
handle_req_state_data(c, c);
return true;
}
As a first step, I have created the mock class as below
class MsgHandlerMock : public MsgHandler
{
public:
MsgHandlerMock()
{
}
virtual ~MsgHandlerMock() {}
MOCK_METHOD(bool, handle_req_state_data, (char *, char *), (const));
//MOCK_METHOD(int, decode_data, (unsigned char*, unsigned int ,char* ));
private:
};
Below is the test function
TEST_F(TestClass, test01)
{
MsgHandlerMock mockObj;
//EXPECT_CALL(mockObj, decode_data(::testing::_,::testing::_,::testing::_)).Times(1);
EXPECT_CALL(mockObj, handle_req_state_data(::testing::_,::testing::_)).Times(1);
mockObj.decode_data(0,0,0);
}
My intention of this test is to make sure 'handle_req_state_data' is called when I call 'decode_data' with a certain message. But my test fails with below error
decode_data called
handle_req_state_data called
...
Actual function call count doesn't match EXPECT_CALL(mockObj, handle_req_state_data(::testing::_,::testing::_))...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] TestClass.test01 (1 ms)
[----------] 1 test from TestClass (1 ms total)
Can someone help me on how to validate the inner method calls with EXPECT_CALL validators?

The function is not virtual, so can't be overridden by the mock, decode_data does not use dynamic dispatch and call the original method MsgHandler::handle_req_state_data.
virtual bool handle_req_state_data(char *, char *);
MOCK_METHOD(bool, handle_req_state_data, (char *, char *), (override));

Related

boost multi index - loop through key value of specific entry

I have a multi index with 2 indexes(in real code, they are of different type).
class CrUsersKeys{
int IMSI;
int TIMESTAMP;
}
After i find an entry in the multi index, I have the iterator of the entry.
auto it = multi.GetIteratorBy<IMSI_tag>(searchKey);
Now i want to loop through all the indexed members in this specific (*it) and check them. Note that i don't want to iterate through the iterator, but through the the indexed element of CrUsersKeys. How can i do it?
for(key in it)
{
if(isGoodKey(key))
std::cout<<"key "<<key <<" is good key"<<std::endl;
}
So it should check isGoodKey((*it).IMSI) and isGoodKey((*it).TIMESTAMP).
CrUsersKeys is template parameter, so i can't really know the members of CrUsersKeys.
Code example at http://coliru.stacked-crooked.com/a/d97195a6e4bb7ad4
My multi index class is in shared memory.
Your question has little to do with Boost.MultiIndex and basically asks for a way to compile-time iterate over the members of a class. If you're OK with CrUsersKeys being defined as a std::tuple (or a tuple-like class), then you can do something like this (C++17):
Edit: Showed how to adapt a non-tuple class to the framework.
Live On Coliru
#include <tuple>
template<typename Tuple,typename F>
bool all_of_tuple(const Tuple& t,F f)
{
const auto fold=[&](const auto&... x){return (...&&f(x));};
return std::apply(fold,t);
}
#include <iostream>
#include <type_traits>
bool isGoodKey(int x){return x>0;}
bool isGoodKey(const char* x){return x&&x[0]!='\0';}
template<typename Tuple>
bool areAllGoodKeys(const Tuple& t)
{
return all_of_tuple(t,[](const auto& x){return isGoodKey(x);});
}
struct CrUsersKeys
{
int IMSI;
const char* TIMESTAMP;
};
bool areAllGoodKeys(const CrUsersKeys& x)
{
return areAllGoodKeys(std::forward_as_tuple(x.IMSI,x.TIMESTAMP));
}
int main()
{
std::cout<<areAllGoodKeys(std::make_tuple(1,1))<<"\n"; // 1
std::cout<<areAllGoodKeys(std::make_tuple(1,"hello"))<<"\n"; // 1
std::cout<<areAllGoodKeys(std::make_tuple(1,0))<<"\n"; // 0
std::cout<<areAllGoodKeys(std::make_tuple("",1))<<"\n"; // 0
std::cout<<areAllGoodKeys(CrUsersKeys{1,"hello"})<<"\n"; // 1
std::cout<<areAllGoodKeys(CrUsersKeys{0,"hello"})<<"\n"; // 0
std::cout<<areAllGoodKeys(CrUsersKeys{1,""})<<"\n"; // 0
}

Is there an equivalent to __attribute__((ns_returns_retained)) for a malloc'd pointer?

I'm looking for an annotation something like
-(SomeStruct *) structFromInternals __attribute__((returns_malloced_ptr))
{
SomeStruct *ret = malloc(sizeof(SomeStruct));
//do stuff
return ret;
}
to soothe the clang static analyzer beasts.
The only viable attributes link I can find is for GCC, but it doesn't even include ns_returns_retained, which is in an extension, I assume.
EDIT:
as to why this is needed, I have a scenario that I can't repro in a simple case, so it may have to do with a c lib in an Objective-C project... The gist is, I get a static analyzer warning that the malloc in createStruct is leaked:
typedef struct{
void * data;
size_t len;
}MyStruct;
void destroyStruct(MyStruct * s)
{
if (s && s->data) {
free(s->data);
}
if (s) {
free(s);
}
}
MyStruct * createStructNoCopy(size_t len, void * data)
{
MyStruct * retStruct = malloc(sizeof(MyStruct));
retStruct->len = len;
retStruct->data = data;
return retStruct;
}
MyStruct * createStruct(size_t len, void * data)
{
char * tmpData = malloc(len);
memcpy(tmpData, data, len);
return createStructNoCopy(len, tmpData);
}
MyStruct * copyStruct(MyStruct * s)
{
return createStruct(s->len, s->data);
}
The function annotation ownership_returns(malloc) will tell the Clang static analyser that the function returns a pointer that should be passed to free() at some point (or a function with ownership_takes(malloc, ...)). For example:
void __attribute((ownership_returns(malloc))) *my_malloc(size_t);
void __attribute((ownership_takes(malloc, 1))) my_free(void *);
...
void af1() {
int *p = my_malloc(1);
return; // expected-warning{{Potential leak of memory pointed to by}}
}
void af2() {
int *p = my_malloc(1);
my_free(p);
return; // no-warning
}
(See the malloc-annotations.c test file for some more examples of their use.)
At the moment, these annotations only take effect when the alpha.unix.MallocWithAnnotations checker is run (which is not run by default). If you're using Xcode, you'll need to add -Xclang -analyzer-checker=alpha.unix.MallocWithAnnotations to your build flags.

Logical error in code

Code that I am supposed to fill out which was easy enough.
#define MAX_NAME_LEN 128
typedef struct {
char name[MAX_NAME_LEN];
unsigned long sid;
} Student;
/* return the name of student s */
const char* getName(const Student* s) {
return s->name;
}
/* set the name of student s */
void setName(Student* s, const char* name) {
/* fill me in */
}/* return the SID of student s */
unsigned long getStudentID(const Student* s) {
/* fill me in */
}
/* set the SID of student s */
void setStudentID(Student* s, unsigned long sid) {
/* fill me in */
}
However it says what is the logical error in the following function?
Student* makeDefault(void) {
Student s;
setName(&s, "John");
setStudentID(&s, 12345678);
return &s;
}
I do not see any problems. I tested it. It works fine.
Is it because this should probably be a void function and does not need to be returning anything?
You can't return a pointer to a locally declared variable (Student s). The variable "s" will disappear (become garbage) after the return.
Instead, you need to allocate a student first.
You should probably do this:
void makeDefault(Student* pS) {
setName( pS, "John");
setStudentID( pS, 12345678);
}
And then let the calling application allocate the student.

How to get runtime Block type metadata in Objective-c?

I'm writing a class where you register an object and a property to observe. When the property gets set to something non-nil, a registered callback selector is called (like target-action). The selector may have three different signatures, and the right one is called depending on which type was registered.
This works fine, but now I want to add the ability to register a Block instead of a selector as the "callback function". Is it possible to find out the function signature of the supplied Block and handle the callback differently depending on the type of Block supplied?
For example:
- (void)registerCallbackBlock:(id)block
{
if ([self isBlock:block] {
if ([self isMethodSignatureOne:block]) { /* */ }
else if ([self isMethodSignatureTwo:block]) { /* */ }
else { assert(false); } // bad Block signature
block_ = block; // assuming ARC code
}
else { assert(false); } // not a block
}
- (void)callBlock
{
if ([self isMethodSignatureOne:block_] {
block_(arg1_, arg2_); // needs casting?
}
else if ([self isMethodSignatureTwo:block_) {
block_(arg1_, arg2_, arg3_); // needs casting?
}
}
Any ideas?
I know I can make different register functions with specific typedef'ed Block arguments but I would rather have a single function, if possible.
If you're compiling with clang, you can get this information.
From the Clang block ABI spec:
The ABI of blocks consist of their layout and the runtime functions required by the compiler.
A Block consists of a structure of the following form:
struct Block_literal_1 {
void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock
int flags;
int reserved;
void (*invoke)(void *, ...);
struct Block_descriptor_1 {
unsigned long int reserved; // NULL
unsigned long int size; // sizeof(struct Block_literal_1)
// optional helper functions
void (*copy_helper)(void *dst, void *src); // IFF (1<<25)
void (*dispose_helper)(void *src); // IFF (1<<25)
// required ABI.2010.3.16
const char *signature; // IFF (1<<30)
} *descriptor;
// imported variables
};
The following flags bits are in use thusly for a possible ABI.2010.3.16:
enum {
BLOCK_HAS_COPY_DISPOSE = (1 << 25),
BLOCK_HAS_CTOR = (1 << 26), // helpers have C++ code
BLOCK_IS_GLOBAL = (1 << 28),
BLOCK_HAS_STRET = (1 << 29), // IFF BLOCK_HAS_SIGNATURE
BLOCK_HAS_SIGNATURE = (1 << 30),
};
In practice, the current version of clang does encode signature information. According to a comment here, the format is just a standard objective-c method encoding string. That said, the signature format isn't documented (as fas as I can tell), so I'm not sure how much you can assume it won't break with compiler updates.
I don't believe this is actually possible with the current ABI. However, you could do something like this:
- (void)registerSimpleCallback: (BlockWith2Args)block {
BlockWith3Args wrapper = ^ (id arg1, id arg2, id arg3) {
block(a, b);
};
[self registerComplexCallback: wrapper];
}
- (void)registerComplexCallback: (BlockWith3Args)block {
[block_ release];
block_ = [block copy];
}
- (void)callBlock {
if (block_)
block_(arg1, arg2, arg3);
}
Yes we can, as I answered in another question.
The block struct is a published clang standard, and AFAIK, can be used all you want.

Multiple dispatch and multi-methods

What are they, what's the different between them?
Many sources, like Wikipedia, claim they're the same thing, but others explicitly say the opposite, like sbi in this question:
First: "Visitor Pattern is a way to simulate Double Dispatching in C++." This is, erm, not fully right. Actually, double dispatch is one form of multiple dispatch, which is a way to simulate (the missing) multi-methods in C++.
They are the same.
When you call a virtual method in C++, the actual method to run is based on the runtime type of the object them method is invoked on. This is called "single dispatch" because it depends on the type of a single argument (in this case, the implicit 'this' argument). So, for example, the following:
class Base {
public:
virtual int Foo() { return 3; }
}
class Derived : public Base {
public:
virtual int Foo() { return 123; }
}
int main(int argc, char *argv[]) {
Base* base = new Derived;
cout << "The result is " << base->Foo();
delete base;
return 0;
}
When run, the above program prints 123, not 3. So far so good.
Multiple-dispatch is the ability of a language or runtime to dispatch on both the type of the 'this' pointer and the type of the arguments to the method. Consider (sticking with C++ syntax for the moment):
class Derived;
class Base {
public:
virtual int Foo(Base *b) { cout << "Called Base::Foo with a Base*"; }
virtual int Foo(Derived *d) { cout << "Called Base::Foo with a Derived*"; }
}
class Derived : public Base {
public:
virtual int Foo(Base *b) { cout << "Called Derived::Foo with a Base*"; }
virtual int Foo(Derived *d) { cout << "Called Derived::Foo with a Derived*"; }
}
int main(int argc, char *argv[]) {
Base* base = new Derived;
Base* arg = new Derived;
base->Foo(arg);
delete base;
delete arg;
return 0;
}
If C++ had multiple-dispatch, the program would print out "Called Derived::Foo with a Dervied*". (Sadly, C++ does not have multiple-dispatch, and so the program prints out "Called Derived::Foo with a Base*".)
Double-dispatch is a special case of multiple-dispatch, often easier to emulate, but not terribly common as a language feature. Most languages do either single-dispatch or multiple-dispatch.