summaryrefslogtreecommitdiff
path: root/tests/lib/test-thread-helper.h
blob: 3d483ed71b1aea4f93c57933c8337b3afb0ab9b5 (plain)
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
#ifndef _TelepathyQt_tests_lib_test_thread_helper_h_HEADER_GUARD_
#define _TelepathyQt_tests_lib_test_thread_helper_h_HEADER_GUARD_

#include <QObject>
#include <QThread>
#include <QCoreApplication>
#include <TelepathyQt/Callbacks>

class ThreadObjectBase : public QObject
{
    Q_OBJECT

public Q_SLOTS:
    virtual void executeCallback() = 0;

Q_SIGNALS:
    void callbackExecutionFinished();
};

template <typename Context>
class ThreadObject : public ThreadObjectBase
{
public:
    typedef Tp::Callback1<void, Context&> Callback;
    Callback mCallback;

    virtual void executeCallback()
    {
        Q_ASSERT(mCallback.isValid());
        Q_ASSERT(QThread::currentThread() != QCoreApplication::instance()->thread());

        mCallback(mContext);
        Q_EMIT callbackExecutionFinished();
    }

private:
    Context mContext;
};

class TestThreadHelperBase
{
public:
    virtual ~TestThreadHelperBase();

protected:
    TestThreadHelperBase(ThreadObjectBase *threadObject);
    void executeCallback();

protected:
    QThread *mThread;
    ThreadObjectBase *mThreadObject;
};

template <typename Context>
class TestThreadHelper : public TestThreadHelperBase
{
public:
    TestThreadHelper()
        : TestThreadHelperBase(new ThreadObject<Context>())
    { }

    void executeCallback(typename ThreadObject<Context>::Callback const & cb)
    {
        static_cast<ThreadObject<Context>*>(mThreadObject)->mCallback = cb;
        TestThreadHelperBase::executeCallback();
    }
};

#define TEST_THREAD_HELPER_EXECUTE(helper, callback) \
    do { \
        (helper)->executeCallback(Tp::ptrFun(callback)); \
        if (QTest::currentTestFailed()) { \
            return; \
        } \
    } while(0)

#endif // _TelepathyQt_tests_lib_test_thread_helper_h_HEADER_GUARD_