Mocking using boost::shared_ptr and AMOP - c++

I'm trying to write mocks using amop. I'm using Visual Studio 2008.
I have this interface class:
struct Interface {
virtual void Activate() = 0;
};
and this other class which receives pointers to this Interface, like this:
struct UserOfInterface {
void execute(Interface* iface) {
iface->Activate();
}
};
So I try to write some testing code like this:
amop::TMockObject<Interface> mock;
mock.Method(&Interface::Activate).Count(1);
UserOfInterface user;
user.execute((Interface*)mock);
mock.Verifiy();
It works! So far so good, but what I really want is a boost::shared_ptr in the execute() method, so I write this:
struct UserOfInterface {
void execute(boost::shared_ptr<Interface> iface) {
iface->Activate();
}
};
How should the test code be now? I tried some things, like:
amop::TMockObject<Interface> mock;
mock.Method(&Interface::Activate).Count(1);
UserOfInterface user;
boost::shared_ptr<Interface> mockAsPtr((Interface*)mock);
user.execute(mockAsPtr);
mock.Verifiy();
It compiles, but obviously crashes, since at the end of the scope the variable 'mock' gets double destroyed (because of the stack variable 'mock' and the shared_ptr).
I also tried to create the 'mock' variable on the heap:
amop::TMockObject<Interface>* mock(new amop::TMockObject<Interface>);
mock->Method(&Interface::Activate).Count(1);
UserOfInterface user;
boost::shared_ptr<Interface> mockAsPtr((Interface*)*mock);
user.execute(mockAsPtr);
mock->Verifiy();
But it doesn't work, somehow it enters an infinite loop, before I had a problem with boost not finding the destructor for the mocked object when the shared_ptr tried to delete the object.
Has anyone used amop with boost::shared_ptr successfully?

You may want to try using a more explicit cast. I'm not sure if this will work, but give it a try.
// Get the mock generator
boost::shared_ptr< amop::TMockObject<Interface> > mock
= boost::make_shared< amop::TMockObject<Interface> >;
// Get the mocked interface
boost::shared_ptr<Interface> imock = boost::dynamic_pointer_cast<Interface>(mock);
// Setup mock usage expectations
mock->Method(&Interface::Activate).Count(1);
// Run the test
UserOfInterface user;
user.execute(imock);
// Verify the expectations were met
mock->Verifiy();

Well, I never used amop, but perhaps this boost pattern will help..
To create a boost shared_ptr you can also use
boost::shared_ptr<Interface> mock(new amop::TMockObject<Interface>());
This way the mock object is not created on the stack and only destroyed if the reference counter in the shared_ptr gets to zero.
Because this is essentially the same as your second try, another tip:
If you encounter problems that look like c++ is not finding the right destructor, you might introduces a virtual destructor in the base (interface) class. Does amop allow this?
class Interface{
virtual ~Interface() { }
...
};

You can give the shared_ptr a custom functor that will be called instead of delete when the reference count goes to zero.
The code then will look like this (I didn't try to compile it):
struct NoOpDel
{
void operator() (void *) { }
}
amop::TMockObject<Interface> mock;
mock.Method(&Interface::Activate).Count(1);
UserOfInterface user;
boost::shared_ptr<Interface> imock((Interface*)mock, NoOpDel())
user.execute(imock);
mock.Verify();
See Boost API doc for more details, you are interested in this constructor:
template<class Y, class D> shared_ptr(Y * p, D d);

Disclaimer: I'm the author of HippoMocks
Using HippoMocks you can specify that you expect the destructor is called at the end of your test. It also implicitly validates your expectations at the end of your test. That way it can even guard against a stray shared_ptr on the heap that you forgot to delete or a class that doesn't take ownership or forgets to delete the pointer in the case that you don't use a shared_ptr.

There is a way to use shared_ptr with amop
struct Interface {
virtual ~Interface() {}
virtual void Activate() = 0;
};
TEST(MockObjectMethodDestructor)
{
TMockObject<Interface> mock;
mock.Method(Destructor());
boost::shared_ptr<Interface> ptr((IInterface*)mock);
ptr.reset();
}

Related

How to write a test case which garbage collects in the middle of a function execution?

I have a native class:
class NativeClass
{
int someVariable;
public:
void someNativeFunction(){}
};
I have a managed class, which lightly wraps this native class.
class ManagedClass
{
NativeClass *nativeClassObject;
public:
void someManagedFunction()
{
nativeClassObject->someNativeFunction();
}
};
I use this managed class in my C# application:
static void Main(string[] args)
{
ManagedClass objManagedClass = new ManagedClass();
objManagedClass.someManagedFunction();//line_1
//At this point onwards objManagedClass still has a reference on the stack, but is not used again.
//So, GC can delete this object.
}
Since objManagedClass is not referenced after line_1, garbage collector is free to destroy the object, even if it is processing the internal native call. This will lead to destruction of objManagedClass, which will in turn destroy *nativeClassObject. This is only likely to happen if someNativeFunction is allocating a lot of memory or is taking a long time, but just to be sure, I must add a reference to objManagedClass later after the call.
class ManagedClass
{
NativeClass *nativeClassObject;
public:
void someManagedFunction()
{
nativeClassObject->someNativeFunction();
...
...
System::GC::KeepAlive(this);
}
};
KeepAlive() call should prevent GC from destroying it. Is there any way I can test this scenario? Some test case I could write that would fail if I did not provide KeepAlive(), but would pass once I called it? Would Thread.Sleep(5000) call in between the managed function help?
You can force garbage collection to start by calling GC::Collect and then wait until garbage collection is finished using GC::WaitForPendingFinalizers. This should allow you to test your scenarios.
Take a look at the example on MSDN

Google mock global mock object memory leak

I am using VS2005, and C++ for unit testing using google mock.
I had a global free function in unit testing, and I used the following code to mock free function:
NiceMock <MockA> mockObj;
struct IFoo {
virtual A* foo() = 0;
virtual ~IFoo() {}
};
struct FooMock : public IFoo {
FooMock() {}
virtual ~FooMock() {}
MOCK_METHOD0(foo, A*());
};
FooMock fooMock;
// foo() implementation
A* foo() {
return fooMock.foo();
}
In the SetUp() function, I set Expectations on the global object like
EXPECT_CALL(fooMock,foo())
.Times(1)
.WillOnce(Return(&mockObj));
TEST(..., instA) {
// ...
}
and in TearDown(), I delete the global mock object fooMock
virtual TearDown(){
delete &fooMock;
}
When I run the code, I get the following error
Error: Memory Leak in xyz.instA,
also,
0 bytes in 0 Free Blocks.
-61 bytes in -1 Normal Blocks.
68 bytes in 7 CRT Blocks.
0 bytes in 0 Ignore Blocks.
0 bytes in 0 Client Blocks.
Largest number used: 11025 byte
Total allocations: 50602 bytes.
Can anyone tell me what is happening here? If I don't delete fooMock, I get the error "fooMock should be delete but never is", or Heap corruption detected.
From the error, I can see that somewhere my heap is being mishandled, but I cannot find the point. I have tried to debug it step by step as well.
Some help would be really great! :)
As Ian stated:
Googlemock/googletest expect the mock to be defined either within the body of the test, or within a test fixture class.
The idea behind it is explained in the Cookbook:
When it's being destroyed, your friendly mock object will automatically verify that all expectations on it have been satisfied, and will generate Google Test failures if not. This is convenient as it leaves you with one less thing to worry about. That is, unless you are not sure if your mock object will be destroyed.
In your case fooMock is a global variable (and as you stated it must stay this way) so after each test you just need to run manual verification:
using ::testing::Mock;
TEST(..., instA)
{
ASSERT_TRUE(
Mock::VerifyAndClearExpectations(
&fooMock));
}
Since it is a global variable you can also just do:
Mock::AllowLeak(&fooMock);
More details in Cookbook - Forcing a Verification and CheatSheet - Verifying and Resetting a Mock:
It looks like the problem is that you're instantiating a global instance of FooMock. Googlemock/googletest expect the mock to be defined either within the body of the test, or within a test fixture class.
In the example above, you'd simply instantiate fooMock inside the test:
TEST(..., instA) {
FooMock fooMock;
// ...
}
So I stumbled upon this question and couldn't figure out a way. But then being a software engineer, I needed to find a solution. So here is what I did.
Suppose you want to mock a Queue. The one function you want to mock is dequeue. I will assume you want to dequeue integers to keep things simple because I want to demonstrate how to make global mocks without memory leaks.
class QueueInterface {
public:
virtual ~QueueInterface() {};
virtual int dequeue() = 0;
};
class QueueMock : public QueueInterface {
public:
virtual ~QueueMock() {};
MOCK_METHOD(int, dequeue, (), (override));
};
// Instead of a global object, have a global pointer
QueueMock *globalQueue;
class TestFixture : public ::testing::Test {
protected:
QueueMock mockedQueue;
void SetUp() {
globalQueue = &mockedQueue; // Point the global pointer to this queue
}
void TearDown() {
globalQueue = NULL;
}
}
// Now you can use this global queue pointer in free function or
// C style functions and override the existing implementations.
// This way you can mock a global object.
int dequeueFromQueue() {
return globalQueue->dequeue();
}
TEST_F(TestFixture, DEQUEUE_TEST) {
// Write your test here to use global queue pointer
// Deref pointer to get mocked object
EXPECT_CALL(*globalQueue, dequeue);
}
In this way, whenever a new test is executed, the member variable mockedQueue is allocated and then deallocated at the end of the test. The globalQueue would point to the member instance of each test every time.
Hope this helps! :)
I ran into the same problem and here is the solution (not sure what exactly happened inside because the global mock obj will be destructed eventually).
std::unique_ptr ptrMockObj(new FooMock ());
At the end of the test case, delete the mock obj ptr
TEST(..., instA)
{
...
ptrMock.Obj.reset()
}

Type-casting to an abstract class?

I'm writing an event-based messaging system to be used between the various singleton managers in my game project. Every manager type (InputManager, AudioManager, etc) is derived from a base Manager class and also inherits from an EventHandler class to facilitate message processing, as follows:
class Manager
{ ... }
class EventHandler
{ ...
virtual void onEvent(Event& e) =0;
...
}
class InputManager : public Manager, public EventHandler
{ ...
virtual void InputManager::onEvent(Event& e);
{ ... }
}
Elsewhere I have an EventManager that keeps track of all EventHandlers and is used for broadcasting events to multiple recievers.
class EventManager
{...
addHandlerToGroup(EventHandler& eh);
{ ... }
...
}
Naturally when I'm initializing all of my singleton Managers, I want to be adding them as they're created to the EventManager's list. My problem is that MVC++ complains at compile-time (and as I'm coding with squiggly lines) whenever I attempt to cast my Managers to EventHandlers. I thought it would work as follows:
int main()
{ ...
EventManager* eventM = new EventManager();
...
InputManager* inputM = new InputManager();
eventM->addHandlerToGroup(dynamic_cast<EventHandler>(inputM));
}
The compiler, however, informs me that "a cast to abstract class is not allowed." I was under the impression that you can...after all, polymorphism doesn't do you much good without passing objects back and forth with a bit of flexibility as to how close to the base class they are interpreted. My current workaround looks like this:
int main()
{ ...
EventManager* eventM = new EventManager();
EventHandler* temp;
...
InputManager* inputM = new InputManager();
temp = inputM;
eventM->addHandlerToGroup(*inputM);
}
Which, as far as I can tell, is the same conceptually for what I'm trying to accomplish, if a bit more verbose and less intuitive. Am I completely off as far as how typecasting with polymorphism works? Where am I going wrong?
in EventManager, declare the method addHandlerToGroup as
void addHandlerToGroup(EventHandler* handler);
then, just remove the cast. pass the pointer (in the example inputM) as it is to the addHandler method, and you should be fine :)
InputManager* inputM = new InputManager();
eventM->addHandlerToGroup(dynamic_cast<EventHandler>(inputM));
I think you just lost track of what you were doing. In this code, inputM is an InputManager* and you are trying to cast it to an EventHandler. That is, you are trying to cast a pointer to one class to an instance of another class. That, of course, makes no sense.
You can cast a pointer to an instance of a derived class to a pointer to an instance of one of its base classes. I think that's what you meant to do.

Optional Member Objects

Okay, so you have a load of methods sprinkled around your system's main class. So you do the right thing and refactor by creating a new class and perform move method(s) into a new class. The new class has a single responsibility and all is right with the world again:
class Feature
{
public:
Feature(){};
void doSomething();
void doSomething1();
void doSomething2();
};
So now your original class has a member variable of type object:
Feature _feature;
Which you will call in the main class. Now if you do this many times, you will have many member-objects in your main class.
Now these features may or not be required based on configuration so in a way it's costly having all these objects that may or not be needed.
Can anyone suggest a way of improving this?
EDIT: Based on suggestion to use The Null Object Design Pattern I've come up with this:
An Abstract Class Defining the Interface of the Feature:
class IFeature
{
public:
virtual void doSomething()=0;
virtual void doSomething1()=0;
virtual void doSomething2()=0;
virtual ~IFeature(){}
};
I then define two classes which implement the interface, one real implementation and one Null Object:
class RealFeature:public IFeature
{
public:
RealFeature(){};
void doSomething(){std::cout<<"RealFeature doSomething()"<<std::endl;}
void doSomething1(){std::cout<<"RealFeature doSomething()"<<std::endl;}
void doSomething2(){std::cout<<"RealFeature doSomething()"<<std::endl;}
};
class NullFeature:public IFeature
{
public:
NullFeature(){};
void doSomething(){std::cout<<"NULL doSomething()"<<std::endl;};
void doSomething1(){std::cout<<"NULL doSomething1()"<<std::endl;};
void doSomething2(){std::cout<<"NULL doSomething2()"<<std::endl;};
};
I then define a Proxy class which will delegate to either the real object or the null object depending on configuration:
class Feature:public IFeature
{
public:
Feature();
~Feature();
void doSomething();
void doSomething1();
void doSomething2();
private:
std::auto_ptr<IFeature> _feature;
};
Implementation:
Feature::Feature()
{
std::cout<<"Feature() CTOR"<<std::endl;
if(configuration::isEnabled() )
{
_feature = auto_ptr<IFeature>( new RealFeature() );
}
else
{
_feature = auto_ptr<IFeature>( new NullFeature() );
}
}
void Feature::doSomething()
{
_feature->doSomething();
}
//And so one for each of the implementation methods
I then use the proxy class in my main class (or wherever it's required):
Feature _feature;
_feature.doSomething();
If a feature is missing and the correct thing to do is ignore that fact and do nothing, you can get rid of your checks by using the Null Object pattern:
class MainThing {
IFeature _feature;
void DoStuff() {
_feature.Method1();
_feature.Method2();
}
interface IFeature {
void Method1();
void Method2();
}
class SomeFeature { /* ... */ }
class NullFeature {
void Method1() { /* do nothing */ }
void Method2() { /* do nothing */ }
}
Now, in MainThing, if the optional feature isn't there, you give it a reference to a NullFeature instead of an actual null reference. That way, MainThing can always safely assume that _feature isn't null.
An auto_ptr by itself won't buy you much. But having a pointer to an object that you lazily load only when and if you need it might. Something like:
class Foo {
private:
Feature* _feature;
public:
Foo() : _feature(NULL) {}
Feature* getFeature() {
if (! _feature) {
_feature = new Feature();
}
return _feature;
}
};
Now you can wrap that Feature* in a smart pointer if you want help with the memory management. But the key isn't in the memory management, it's the lazy creation. The advantage to this instead of selectively configuring what you want to go create during startup is that you don't have to configure – you simply pay as you go. Sometimes that's all you need.
Note that a downside to this particular implementation is that the creation now takes place the first time the client invokes what they think is just a getter. If creation of the object is time-consuming, this could be a bit of a shock to, or even a problem for, to your client. It also makes the getter non-const, which could also be a problem. Finally, it assumes you have everything you need to create the object on demand, which could be a problem for objects that are tricky to construct.
There is one moment in your problem description, that actually would lead to failure. You shouldn't "just return" if your feature is unavailable, you should check the availability of your feature before calling it!
Try designing that main class using different approach. Think of having some abstract descriptor of your class called FeatureMap or something like that, which actually stores available features for current class.
When you implement your FeatureMap everything goes plain and simple. Just ensure (before calling), that your class has this feature and only then call it. If you face a situation when an unsupported feature is being called, throw an exception.
Also to mention, this feature-lookup routine should be fast (I guess so) and won't impact your performance.
I'm not sure if I'm answering directly to your question (because I don't have any ideas about your problem domain and, well, better solutions are always domain-specific), but hope this will make you think in the right way.
Regarding your edit on the Null Object Pattern: If you already have a public interface / private implementation for a feature, it makes no sense to also create a null implementation, as the public interface can be your null implementation with no problems whatsoever).
Concretely, you can have:
class FeatureImpl
{
public:
void doSomething() { /*real work here*/ }
};
class Feature
{
class FeatureImpl * _impl;
public:
Feature() : _impl(0) {}
void doSomething()
{
if(_impl)
_impl->doSomething();
// else case ... here's your null object implementation :)
}
// code to (optionally) initialize the implementation left out due to laziness
};
This code only benefits from a NULL implementation if it is performance-critical (and even then, the cost of an if(_impl) is in most cases negligible).

Reconciling classes, inheritance, and C callbacks

In my C++ project, I've chosen to use a C library. In my zeal to have a well-abstracted and simple design, I've ended up doing a bit of a kludge. Part of my design requirement is that I can easily support multiple APIs and libraries for a given task (due, primarily, to my requirement for cross-platform support). So, I chose to create an abstract base class which would uniformly handle a given selection of libraries.
Consider this simplification of my design:
class BaseClass
{
public:
BaseClass() {}
~BaseClass() {}
bool init() { return doInit(); }
bool run() { return doWork(); }
void shutdown() { destroy(); }
private:
virtual bool doInit() = 0;
virtual bool doWork() = 0;
virtual void destroy() = 0;
};
And a class that inherits from it:
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass()
: BaseClass(), state_manager(new SomeOtherClass()) {}
int callbackA(int a, int b);
private:
virtual bool doInit();
virtual bool doWork();
virtual void destroy();
SomeOtherClass* state_manager;
};
// LSC.cpp:
bool LibrarySupportClass::doInit()
{
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&LibrarySupportClass::callbackA);
return true;
}
// ... and so on
The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form int (*)(int, int), but the library doesn't support an extra userdata pointer for these callbacks. I would prefer doing all of these callbacks within the class because the class carries a state object.
What I ended up doing is...
static LibrarySupportClass* _inst_ptr = NULL;
static int callbackADispatch(int a, int b)
{
_inst_ptr->callbackA(a, b);
}
bool LibrarySupportClass::doInit()
{
_inst_ptr = this;
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&callbackADispatch);
return true;
}
This will clearly do Bad Things(TM) if LibrarySupportClass is instantiated more than once, so I considered using the singleton design, but for this one reason, I can't justify that choice.
Is there a better way?
You can justify that choice: your justification is that the C library only supports one callback instance.
Singletons scare me: It's not clear how to correctly destroy a singleton, and inheritance just complicates matters. I'll take another look at this approach.
Here's how I'd do it.
LibrarySupportClass.h
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass();
~LibrarySupportClass();
static int static_callbackA(int a, int b);
int callbackA(int a, int b);
private:
//copy and assignment are rivate and not implemented
LibrarySupportClass(const LibrarySupportClass&);
LibrarySupportClass& operator=(const LibrarySupportClass&);
private:
static LibrarySupportClass* singleton_instance;
};
LibrarySupportClass.cpp
LibrarySupportClass* LibrarySupportClass::singleton_instance = 0;
int LibrarySupportClass::static_callbackA(int a, int b)
{
if (!singleton_instance)
{
WHAT? unexpected callback while no instance exists
}
else
{
return singleton_instance->callback(a, b);
}
}
LibrarySupportClass::LibrarySupportClass()
{
if (singleton_instance)
{
WHAT? unexpected creation of a second concurrent instance
throw some kind of exception here
}
singleton_instance = this;
}
LibrarySupportClass::~LibrarySupportClass()
{
singleton_instance = 0;
}
My point is that you don't need to give it the external interface of a canonical 'singleton' (which e.g. makes it difficult to destroy).
Instead, the fact that there is only one of it can be a private implementation detail, and enforced by a private implementation detail (e.g. by the throw statement in the constructor) ... assuming that the application code is already such that it will not try to create more than one instance of this class.
Having an API like this (instead of the more canonical 'singleton' API) means that you can for example create an instance of this class on the stack if you want to (provided you don't try to create more than one of it).
The external constraint of the c library dictates that when your callback is called you don't have the identification of the "owning" instance of the callback. Therefore I think that your approach is correct.
I would suggest to declare the callbackDispatch method a static member of the class, and make the class itself a singleton (there are lots of examples of how to implement a singleton). This will let you implement similar classes for other libraries.
Dani beat me to the answer, but one other idea is that you could have a messaging system where the call back function dispatch the results to all or some of the instances of your class. If there isn't a clean way to figure out which instance is supposed to get the results, then just let the ones that don't need it ignore the results.
Of course this has the problem of performance if you have a lot of instances, and you have to iterate through the entire list.
The problem the way I see it is that because your method is not static, you can very easily end up having an internal state in a function that isn't supposed to have one, which, because there's a single instance on the top of the file, can be carried over between invocations, which is a -really- bad thing (tm). At the very least, as Dani suggested above, whatever methods you're calling from inside your C callback would have to be static so that you guarantee no residual state is left from an invocation of your callback.
The above assumes you have static LibrarySupportClass* _inst_ptr declared at the very top. As an alternative, consider having a factory function which will create working copies of your LibrarySupportClass on demand from a pool. These copies can then return to the pool after you're done with them and be recycled, so that you don't go around creating an instance every time you need that functionality.
This way you can have your objects keep state during a single callback invocation, since there's going to be a clear point where your instance is released and gets a green light to be reused. You will also be in a much better position for a multi-threaded environment, in which case each thread gets its own LibrarySupportClass instance.
The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form int (*)(int, int), but the library doesn't support an extra userdata pointer for these callbacks
Can you elaborate? Is choosing a callback type based on userdata a problem?
Could your callback choose an instance based on a and/or b? If so, then register your library support classes in a global/static map and then have callbackADispatch() look up the correct instance in the map.
Serializing access to the map with a mutex would be a reasonable way to make this thread-safe, but beware: if the library holds any locks when it invokes your callback, then you may have to do something more clever to avoid deadlocks, depending on your lock hierarchy.