gtest hangs during deconstructing fixture when a mock returns a mock as default value - deadlock

I have found a strange behavior I can't understand nor resolve. I have a factory FooFactory, which delivers some real-live objects of type Foo. To test method calls of Fooobjects I mocked FooFactory, in that way that MockFooFactory returns MockFooobjects for which I can expect calls.
The tests (not included) are working fine, but after the test gmock/gtest hangs (seems like mutex problem) during the deconstruction of MockFooFactory. To be precise the deletion of the Default ON_CALL leads to problems when the Mutex is created.
There must an issue with the smart pointers, when I build a version without smart pointers, it works fine. But the software I test uses shared_ptr as smart pointers, and so I can't get rid of them.
Here is a sample I build which reproduces the error:
#include <boost/shared_ptr.hpp>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
class Foo
{
public:
void doSomething() {}
};
typedef boost::shared_ptr<Foo> FooPtr;
class FooFactory {
public:
FooPtr create() {
return FooPtr(new Foo());
}
};
typedef boost::shared_ptr<FooFactory> FooFactoryPtr;
class MockFoo : public Foo {
public:
MOCK_METHOD0(doSomething, void());
};
typedef boost::shared_ptr<MockFoo> MockFooPtr;
class MockFactory : public FooFactory
{
public:
MOCK_METHOD0(create, FooPtr());
};
typedef boost::shared_ptr<MockFactory> MockFactoryPtr;
using ::testing::Return;
class Fixture : public ::testing::Test {
protected:
virtual void SetUp() {
mockFoo = MockFooPtr(new MockFoo());
mockFactory = MockFactoryPtr(new MockFactory());
ON_CALL(*mockFactory, create()).WillByDefault(Return(mockFoo));
}
MockFactoryPtr mockFactory;
MockFooPtr mockFoo;
};
TEST_F(Fixture, Test)
{
/* Not needed */
}
Has anyone experienced the same problem or has a solution for it?

Okay after updating to the trunk version of gmock everything is fine, because they fixed this issue:
https://code.google.com/p/googlemock/issues/detail?id=79

Related

Signals emitted from a QThread worker class do not arrive

I have this simplified code:
class MyCustomObject {
};
class DeviceConnection : public QObject {
Q_OBJECT
public:
explicit DeviceConnection(QObject* const parent = nullptr);
signals:
void readFinished(MyCustomObject result);
public slots:
void readFromDevice();
};
DeviceConnection::readFromDevice() {
/* ... */
emit readFinished(MyCustomObject());
}
void MainWindow::on_actionRead_triggered() {
QThread* const thread = new QThread(this);
DeviceConnection* const connection = new DeviceConnection();
connection->moveToThread(thread);
thread->start();
connect(connection, &DeviceConnection::readFinished, this, [=](MyCustomObject data) {
/* This never runs. */
connection->deleteLater();
thread->quit();
});
QTimer::singleShot(0, connection, &DeviceConnection::readFromDevice);
}
This starts reading just fine. I can see in the debugger that I am getting to the emit line, and I am getting there in the thread. But I can also see in the debugger, and in the behavior of the code, that the readFinished lambda is never called. This is also true with slots that aren't lambdas. What's the problem?
Edit: This code runs fine when I don't use an extra thread, but of course it blocks the main thread while readFromDevice() runs.
I figured it out. Unfortunately I simplified the important bit away when I first asked the question, but I just edited it back in.
The problem is that MyCustomObject cannot be enqueued in the Qt message queue. To do that, you need to run this:
qRegisterMetaType<MyCustomObject>("MyCustomObject");
or
// ideally just after the definition for MyCustomObject
Q_DECLARE_METATYPE(MyCustomObject);
// any time before you want to enqueue one of these objects
qRegisterMetaType<MyCustomObject>();
your defined signal should take an argument of QString type.

How to define a static pointer to a class in MQL?

I've got the following MQL code:
class Collection {
public: void *Get(void *_object) { return NULL; }
};
class Timer {
protected:
string name;
uint start, end;
public:
void Timer(string _name = "") : name(_name) { };
void TimerStart() { start = GetTickCount(); }
void TimerStop() { end = GetTickCount(); }
};
class Profiler {
public:
static Collection *timers;
static ulong min_time;
void Profiler() { };
void ~Profiler() { Deinit(); };
static void Deinit() { delete Profiler::timers; };
};
// Initialize static global variables.
Collection *Profiler::timers = new Collection();
ulong Profiler::min_time = 1;
void main() {
// Define local variable.
static Timer *_timer = new Timer(__FUNCTION__); // This line doesn't.
//Timer *_timer = new Timer(__FUNCTION__); // This line works.
// Start a timer.
((Timer *) Profiler::timers.Get(_timer)).TimerStart();
/* Some code here. */
// Stop a timer.
((Timer *) Profiler::timers.Get(_timer)).TimerStop();
}
which defines a Timer class which is used as a timer to profile the functions how long it took. The original version uses a list of timers to store time separately on each call, however, the code has been simplified to provide a minimum working example and focus on the actual compilation problem.
The problem is when I'm using the following line in order to initialize a static variable:
static Timer *_timer = new Timer(__FUNCTION__); // Line 30.
the compilation fails with:
'Timer' - local variables cannot be used TestProfiler.mqh 30 30
When I drop static word, the code compiles fine.
But it doesn't help me, as I want to define this variable as a static pointer to the class, as I don't want to destroy my object each time when the same function is called over and over again, so the timers can be added to the list which can be read later on. I don't really see why the MQL compiler would prevent from compiling the above code. I also believe this syntax worked fine in the previous builds.
I'm using MetaEditor 5.00 build 1601 (May 2017).
What is wrong with my static variable declaration and how can I correct it, so it can point to a Timer class?
Keyword static has two different meanings in MQL4/5: it indicates that a member of a class is static (which is obvious), and it also says that a variable is static... for instance, if you have a variable that is used only in one function, you probably do not need to declare it globally but as a static. You can find an example of isNewBar() function that has static datetime lastBar=0; in the articles about new bar at mql5.com. This keyword in such a function says that the variable is not deleted after function is finished, but remains in memory and is used with the next call. And if you need a variable in OnTick() function - it does not make sence to have it static, declare it globally.

Calling qmlRegisterType() in the registered class on debug crashes application

I want to use qmlRegiterType() in registered class itself. I tried to use method from this topic but whenever I try to run application in debug mode it crashes the application with error
read access violation at 0x0
Crashes on macro QML_GETTYPENAMES inside qqml.h (235 line).
TestClass.h:
class RegisterQmlTest : public QObject
{
Q_OBJECT
public:
explicit RegisterQmlTest(QObject *parent = 0);
};
TestClass.cpp:
QML_REGISTER(RegisterQmlTest);
RegisterQmlTest::RegisterQmlTest(QObject *parent) : QObject(parent)
{ }
void RegisterQmlTest::foo()
{
qDebug() << "Foo test";
}
I tried to compile application on MSVC2013x64 on Qt 5.6.2, on Windows.
You are not the only one that it is happening to : https://github.com/benlau/quickflux/issues/7, and I believe it is likely due to the
static initialization order fiasco.
One solution could be to use Q_COREAPP_STARTUP_FUNCTION to ensure the call to qmlRegisterType is not done too early.
You can use this macro in a .cpp file like so :
static void registerMyQmlTypes() {
qmlRegisterType<MyType>("MyImortUri", 1, 0, "MyType");
}
Q_COREAPP_STARTUP_FUNCTION(registerMyQmlTypes)
I had the exact same issue. The problem is that the staticMetaObject associated to your class is not initialized at the moment the macro invokes the call to qmlRegisterType. As already stated in this answer (from the same topic), you're more flexible without macros. I solved this by introducing one static type per custom class.
appQmlRegister.hpp
#include <functional>
#include <QtQml>
#include <QList>
namespace app {
namespace Qml {
namespace Register {
auto Init() -> void;
static auto GetList()->QList<std::function<void(void)>>&;
template <class T>
struct Type {
Type() {
auto initializer = []() {
qmlRegisterType<T>();
};
GetList().append(initializer);
}
};
}
}
}
appQmlRegister.cpp
#include "appQmlRegister.hpp"
namespace app {
namespace Qml {
namespace Register {
auto Init() -> void {
for (auto registerFunc : GetList()) {
registerFunc();
}
}
auto GetList()->QList<std::function<void(void)>>& {
static QList<std::function<void(void)>> List;
return List;
}
}
}
}
The type app::Qml::Register::Type takes a template argument (the type of your custom class) and wraps the call to qmlRegisterType in a lambda. And that's the basic concept. Instead of an immediate call you now have full control of when to register all your custom types via app::Qml::Register::Init(). By calling that function at runtime but before starting the QML engine you can ensure that the staticMetaObjects are initialized properly and you're safe to register them.
This requires a bit of typing on a per-custom-class level though. You'd have to declare a static member in the header of the class you want to register in QML:
MyCustomClass.hpp
#include "appQmlRegister.hpp"
namespace app {
class MyCustomClass : public QObject {
Q_OBJECT
private:
static Qml::Register::Type<MyCustomClass> Register;
// stuff...
}
}
and then define it in the .cpp file like this:
MyCustomClass.cpp
#include "MyCustomClass.hpp"
namespace app {
Qml::Register::Type<MyCustomClass> MyCustomClass::Register;
}
This can of course be extended to support other sorts of type registration like registering uncreatable types, custom versions/names etc. I implemented this in a QML showcase/template project on GitHub
Hope this helps!

Returning managed pointer from a clone method

In C++11, two types of "managed" pointer types were introduced - shared_ptr and unique_ptr. Let's now assume we have a set of classes that support a clone() method, such as foo->clone() would return a copy of the foo object. If your goal was to return a managed pointer from the clone() method, how would you allow the user of the interface to select which kind of pointer he wants to be returned?
As a sub-question, would you rather return a raw pointer from the clone() method and let the user construct either shared_ptr or unique_ptr by himself? If not, why?
The standard smart pointer to manage a dynamic allocation is always unique_ptr. By contrast, shared_ptr is a very specific tool with specialized features (e.g. type-erased deleter, weak pointer observers) and higher costs (virtual dispatch, locked atomic operations) that should only be used when you definitely know you want it. Public raw pointers are a taboo out of principle, and so the natural clone interface looks like this:
struct Base
{
// must have virtual destructor to destroy through base pointer
virtual ~Base() {}
// non-leaf classes are abstract
virtual std::unique_ptr<Base> clone() const = 0;
};
struct Derived : Base
{
virtual std::unique_ptr<Base> clone() const override
{
return std::unique_ptr<Derived>(new Derived(*this));
// or "return std::make_unique<Derived>(*this)" in C++14
}
};
(Unfortunately, we cannot use any kind of covariant return types here, since the template classes unique_ptr<Base> and unique_ptr<Derived> are unrelated. If you prefer to have a clone function that returns the derived type, you could add a non-virtual function like direct_clone that returns a std::unique_ptr<Derived>, and implement the virtual clone() in terms of that.)
Something along this lines would give you the means to select the kind of smart pointer returned. Would probably be better if encapsulated in a mixin Clonable class template, for maintainability and reusability of the idea.
#include <iostream>
#include <memory>
class Base {
public:
virtual ~Base() {
std::cout << "deleting Base\n";
}
template <template <typename ...Args> class SmartPtr>
SmartPtr<Base> clone() {
return SmartPtr<Base>(this->inner_clone());
}
virtual void speak() const = 0;
private:
virtual Base *inner_clone() const = 0;
};
class C: public Base {
public:
~C() {
std::cout << "deleting C\n";
}
template <template <typename ...Args> class SmartPtr>
SmartPtr<C> clone() {
return SmartPtr<C>(this->inner_clone());
}
void speak() const {
std::cout << "I am C and I inherit from Base!\n";
}
private:
C *inner_clone() const override {
return new C(*this);
}
};
// End boilerplate.
int main()
{
auto original = C{};
// the declarations below should use auto, and are just explicitly typed to
// show the correct return type of clone();
std::shared_ptr<C> shared = original.clone<std::shared_ptr>();
std::unique_ptr<C> unique = original.clone<std::unique_ptr>();
// the declarations below show it working through conversion to a base class
// smart pointer type
std::shared_ptr<Base> sharedBase = original.clone<std::shared_ptr>();
std::unique_ptr<Base> uniqueBase = original.clone<std::unique_ptr>();
// the declarations below show it working through the base class for real
std::shared_ptr<Base> sharedBaseFromBase = sharedBase->clone<std::shared_ptr>();
std::unique_ptr<Base> uniqueBaseFromBase = uniqueBase->clone<std::unique_ptr>();
shared->speak();
unique->speak();
sharedBase->speak();
uniqueBase->speak();
sharedBaseFromBase->speak();
uniqueBaseFromBase->speak();
}
Compiles with gcc 4.8.1, and should in any compiler supporting variadics.
I would still prefer to simply return a unique_ptr and move the result into a shared_ptr, which would be automatic since the call to clone() is in itself an rvalue.

Null pattern with QObject

(C++/Qt) I have a smart pointer to a QObject. Let's say a QWeakPointer. For some external reason (something that might happen in another object or due to an event), it is possible that the pointed object gets destroyed. Since I have a smart pointer there will be no dangling reference, so there's no problem. But I always have to check if the pointer is null or not.
I'm thinking of using the null pattern in order to avoid checking this all the time but I'm not sure if this is possible or convenient with a QObject. The idea would be that the pointer points to the object and in case it gets destroyed, the smart pointer changes its pointed object to a null object. Is this a good idea or should I forget it and just check if the pointer is NULL all the time?
Let's show you an example. We have a worker who uses a tool to do its work:
class Worker : public QObject
{
Q_OBJECT
public:
Worker(QObject *parent = 0);
void work()
{
if(m_tool)
m_tool->use();
emit workCompleted();
};
signals:
workCompleted();
public slots:
void setTool(QWeakPointer<Tool> tool);
private:
QWeakPointer<Tool> m_tool;
};
class Tool : public QObject
{
Q_OBJECT
public:
Tool();
public slots:
void use() =0;
};
class Screwdriver : public Tool
{
Q_OBJECT
public:
Screwdriver() : Tool();
public slots:
void use()
{
// do something
};
};
class Hammer : public Tool;
class Saw : public Tool;
...
In this case, the Tool is a public domain object of a library, which is used by the Worker. I'm developing such library. So the worker is using a screwdriver but it gets broken and gets destroyed. No problem:
if(m_tool)
m_tool->use();
emit workCompleted();
m_tool is 0 so it simply does nothing. But we have to check that it's not null everytime.
Now let's say we had a NullTool object:
class NullTool : public Tool
{
Q_OBJECT
public:
NullTool() : Tool();
public slots:
void use()
{
// does nothing
};
};
When the tool was destroyed, our pointer would be smart and would know it should point to a NullTool instance. So Worker::work() could be implemented like this:
void Worker::work()
{
m_tool->use();
emit workCompleted();
};
m_tool->use() would then get called on the NullTool which does nothing, so there would be no need to check the pointer is not null.
Is this a good idea? Is it possible with the smart pointer classes Qt provides or should I subclass QWeakPointer?
I think the null object pattern makes most sense for value-like classes. Examples are QString or QVariant, were you don't want to have code like if ( str && !str->isEmpty() ) but just do if ( !str.isEmpty() ). For QObjects, which are not values but have "an identity", I never found this useful.
I don't understand clearly your use case, but your program can be signaled when the object has been destroy by connecting the following signal from QObject:
void destroyed ( QObject * obj = 0 );
I don't see any problem in your idea. You just have to compare the work that it takes to implement it compared to the work for checking the pointer every time. Let's your checking the pointer 10.000 times it's a good idea to use your approach. Side note: Your null object pattern rely on the fact that Tool::use() has no side effects whatsoever.
Take care that possible side affects in Tool::use() don't get in the way when you replace it polymorphically with NullTool::use(). In other words: Be sure you don't break the Liskov Substitution Principle.

Resources