summaryrefslogtreecommitdiffstats
path: root/tests/shared/clientwrapper.h
blob: 5883a8c2200b8aa62891fe1a3e2736687e8fc87d (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
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
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#ifndef CLIENTWRAPPER_H
#define CLIENTWRAPPER_H

#include <QEventLoop>
#include <QElapsedTimer>
#include <QDebug>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonDocument>

#include "jsondb-client.h"

QT_USE_NAMESPACE_JSONDB

#define waitForResponse(eventloop, result, id_, code, notificationId, count) \
{ \
    int givenid_ = (id_); \
    (result)->mNotificationId = QVariant(); \
    (result)->mNeedId      = (givenid_ != -1); \
    (result)->mId          = QVariant(); \
    (result)->mMessage     = QString(); \
    (result)->mCode        = -1; \
    (result)->mData        = QVariant(); \
    (result)->mNotificationWaitCount = count; \
    (result)->mLastUuid    = QString(); \
    \
    QTimer timer; \
    QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); \
    QObject::connect(&timer, SIGNAL(timeout()), &eventloop, SLOT(quit())); \
    timer.start(mClientTimeout);                                       \
    mElapsedTimer.start(); \
    do { \
        eventloop.exec(QEventLoop::AllEvents); \
    } while ((result)->mNeedId && (result)->mId.toInt() < QVariant(givenid_).toInt()); \
    if (debug_output) { \
        qDebug() << "waitForResponse" << "expected id" << givenid_ << "got id" << (result)->mId; \
        qDebug() << "waitForResponse" << "expected code" << int(code) << "got code" << (result)->mCode; \
        qDebug() << "waitForResponse" << "expected notificationId" << notificationId << "got notificationId" << (result)->mNotificationId; \
    } \
    if ((result)->mNeedId) QVERIFY2(!(result)->mId.isNull(), "Failed to receive an answer from the db server"); \
    if ((result)->mNeedId) QCOMPARE((result)->mId, QVariant(givenid_)); \
    if ((result)->mNotificationId != QVariant(notificationId)) { \
        if ((result)->mNotificationId.isNull()) { \
            QVERIFY2(false, "we expected notification but did not get it :("); \
        } else { \
            QJsonValue value = QJsonValue::fromVariant((result)->mNotifications.last().mObject); \
            QString data = QString::fromUtf8(value.isArray() ? QJsonDocument(value.toArray()).toJson() : QJsonDocument(value.toObject()).toJson()); \
            QByteArray ba = QString("we didn't expect notification but got it. %1").arg(data).toLatin1(); \
            QVERIFY2(false, ba.constData()); \
        } \
    } \
    QCOMPARE((result)->mNotificationId, QVariant(notificationId)); \
    if ((result)->mCode != int(code)) \
        qDebug() << (result)->mMessage; \
    QCOMPARE((result)->mCode, int(code)); \
}
#define waitForResponse1(id) waitForResponse(mEventLoop, this, id, -1, QVariant(), 0)
#define waitForResponse2(id, code) waitForResponse(mEventLoop, this, id, code, QVariant(), 0)
#define waitForResponse3(id, code, notificationId) waitForResponse(mEventLoop, this, id, code, notificationId, 0)
#define waitForResponse4(id, code, notificationId, count) waitForResponse(mEventLoop, this, id, code, notificationId, count)

#define waitForCallbackGeneric(eventloop) \
{ \
    QTimer timer; \
    QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); \
    QObject::connect(&timer, SIGNAL(timeout()), &eventloop, SLOT(quit())); \
    timer.start(mClientTimeout);                                       \
    mElapsedTimer.start(); \
    mTimedOut = false;\
    callbackError = false; \
    eventloop.exec(QEventLoop::AllEvents); \
    QCOMPARE(false, mTimedOut); \
}

#define waitForCallback() waitForCallbackGeneric(mEventLoop)
#define waitForCallback2() waitForCallbackGeneric(mEventLoop2)

class JsonDbTestNotification
{
public:
    JsonDbTestNotification(const QString &notifyUuid, const QVariant &object, const QString &action)
        : mNotifyUuid(notifyUuid), mObject(object), mAction(action) {}

    QString  mNotifyUuid;
    QVariant mObject;
    QString  mAction;
};

class ClientWrapper : public QObject
{
    Q_OBJECT
public:
    ClientWrapper(QObject *parent = 0)
        : QObject(parent), debug_output(false)
        , mClient(0), mCode(0), mNeedId(false), mNotificationWaitCount(0), mClientTimeout(20000)
    {
        if (qgetenv("JSONDB_CLIENT_TIMEOUT").size())
            mClientTimeout = QString::fromLatin1(qgetenv("JSONDB_CLIENT_TIMEOUT")).toLong();
    }

    void connectToServer()
    {
        mClient = new QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient)(this);
        connect(mClient, SIGNAL(response(int,QVariant)),
                this, SLOT(response(int,QVariant)));
        connect(mClient, SIGNAL(error(int,int,QString)),
                this, SLOT(error(int,int,QString)));
        connect(mClient, SIGNAL(notified(QString,QtAddOn::JsonDb::JsonDbNotification)),
                this, SLOT(notified(QString,QtAddOn::JsonDb::JsonDbNotification)));
    }

    QString addNotification(JsonDbClient::NotifyTypes types, const QString &query, const QString &partition = QString()) {
        QEventLoop ev;
        QString uuid = mClient->registerNotification(types, query, partition, 0, 0, &ev, SLOT(quit()));
        ev.exec();
        return uuid;
    }

    bool debug_output;

    QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient) *mClient;

    QEventLoop mEventLoop;
    QString mMessage;
    int  mCode;
    bool mNeedId;
    QVariant mId, mData, mNotificationId;
    QString mLastUuid, mLastVersion;
    int mNotificationWaitCount;
    QList<JsonDbTestNotification> mNotifications;
    quint32 mClientTimeout;
    QElapsedTimer mElapsedTimer;

protected slots:
    virtual void notified(const QString &notifyUuid, const QtAddOn::JsonDb::JsonDbNotification &notification)
    {
        if (debug_output)
            qDebug() << "notified" << notifyUuid << notification.action() << endl << notification.object();
        mNotificationId = notifyUuid;
        QString action;
        switch (notification.action()) {
        case QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient)::NotifyCreate: action = QLatin1String("create"); break;
        case QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient)::NotifyUpdate: action = QLatin1String("update"); break;
        case QT_PREPEND_NAMESPACE_JSONDB(JsonDbClient)::NotifyRemove: action = QLatin1String("remove"); break;
        }

        mNotifications << JsonDbTestNotification(notifyUuid, notification.object(), action);
        mNotificationWaitCount -= 1;
        if (mId.isValid() && !mNotificationWaitCount)
            mEventLoop.quit();
        if (!mNeedId && !mNotificationWaitCount)
            mEventLoop.quit();
    }

    virtual void response(int id, const QVariant &data)
    {
        if (debug_output)
            qDebug() << "response" << id << endl << data;
        mId = id;
        mData = data;
        mLastUuid = data.toMap().value("_uuid").toString();
        mLastVersion = data.toMap().value("_version").toString();
        if (mId.isValid() && !mNotificationWaitCount)
            mEventLoop.quit();
        if (!mNeedId && !mNotificationWaitCount)
            mEventLoop.quit();
    }

    virtual void error(int id, int code, const QString &message)
    {
        if (debug_output)
            qDebug() << "response" << id << code << message;
        mId = id;
        mCode = code;
        mMessage = message;
        mEventLoop.quit();
    }
    virtual void disconnected()
    {
    }
    virtual void timeout()
    {
        qDebug() << "timeout" << mElapsedTimer.elapsed();
    }
};

#endif // CLIENTWRAPPER_H