tst_qoauth.cpp 23.5 KB
Newer Older
Jesus Fernandez's avatar
Jesus Fernandez committed
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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore>
#include <QtTest>
#include <QtNetwork>

33 34 35 36
#include <QtOAuth/qoauth1.h>
#include <QtOAuth/qabstractoauth.h>
#include <QtOAuth/private/qoauth1_p.h>
#include <QtOAuth/private/qabstractoauth_p.h>
Jesus Fernandez's avatar
Jesus Fernandez committed
37 38 39 40 41 42

Q_DECLARE_METATYPE(QNetworkAccessManager::Operation)
Q_DECLARE_METATYPE(QAbstractOAuth::Error)

typedef QSharedPointer<QNetworkReply> QNetworkReplyPtr;

Jesus Fernandez's avatar
Jesus Fernandez committed
43
class tst_QOAuth : public QObject
Jesus Fernandez's avatar
Jesus Fernandez committed
44 45 46 47 48 49 50 51
{
    Q_OBJECT

    QEventLoop *loop;
    enum RunSimpleRequestReturn { Timeout = 0, Success, Failure };
    int returnCode;

    using QObject::connect;
Jesus Fernandez's avatar
Jesus Fernandez committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    static bool connect(const QNetworkReplyPtr &ptr,
                        const char *signal,
                        const QObject *receiver,
                        const char *slot,
                        Qt::ConnectionType ct = Qt::AutoConnection)
    {
        return connect(ptr.data(), signal, receiver, slot, ct);
    }
    bool connect(const QNetworkReplyPtr &ptr,
                 const char *signal,
                 const char *slot,
                 Qt::ConnectionType ct = Qt::AutoConnection)
    {
        return connect(ptr.data(), signal, slot, ct);
    }
Jesus Fernandez's avatar
Jesus Fernandez committed
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

public:
    int waitForFinish(QNetworkReplyPtr &reply);
    void test_data();
    void fillParameters(QVariantMap *parameters, const QUrlQuery &query);


public Q_SLOTS:
    void finished();
    void gotError();

private Q_SLOTS:
    void createSignature();

    void getToken_data();
    void getToken();

    void grant_data();
    void grant();

    void authenticatedCalls_data();
    void authenticatedCalls();
};

int tst_QOAuth::waitForFinish(QNetworkReplyPtr &reply)
{
    int count = 0;

    connect(reply, SIGNAL(finished()), SLOT(finished()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(gotError()));
    returnCode = Success;
    loop = new QEventLoop;
    QSignalSpy spy(reply.data(), SIGNAL(downloadProgress(qint64,qint64)));
    while (!reply->isFinished()) {
        QTimer::singleShot(5000, loop, SLOT(quit()));
        if ( loop->exec() == Timeout && count == spy.count() && !reply->isFinished()) {
            returnCode = Timeout;
            break;
        }
        count = spy.count();
    }
    delete loop;
    loop = 0;

    return returnCode;
}

void tst_QOAuth::test_data()
{
    QTest::addColumn<QString>("consumerKey");
    QTest::addColumn<QString>("consumerSecret");
    QTest::addColumn<QString>("requestToken");
    QTest::addColumn<QString>("requestTokenSecret");
    QTest::addColumn<QString>("accessToken");
    QTest::addColumn<QString>("accessTokenSecret");
    QTest::addColumn<QUrl>("requestTokenUrl");
    QTest::addColumn<QUrl>("accessTokenUrl");
    QTest::addColumn<QUrl>("authenticatedCallUrl");
    QTest::addColumn<QNetworkAccessManager::Operation>("requestType");

    QTest::newRow("term.ie_get") << "key"
                                 << "secret"
                                 << "requestkey"
                                 << "requestsecret"
                                 << "accesskey"
                                 << "accesssecret"
                                 << QUrl("http://term.ie/oauth/example/request_token.php")
                                 << QUrl("http://term.ie/oauth/example/access_token.php")
                                 << QUrl("http://term.ie/oauth/example/echo_api.php")
                                 << QNetworkAccessManager::GetOperation;
    QTest::newRow("term.ie_post") << "key"
                                  << "secret"
                                  << "requestkey"
                                  << "requestsecret"
                                  << "accesskey"
                                  << "accesssecret"
                                  << QUrl("http://term.ie/oauth/example/request_token.php")
                                  << QUrl("http://term.ie/oauth/example/access_token.php")
                                  << QUrl("http://term.ie/oauth/example/echo_api.php")
                                  << QNetworkAccessManager::PostOperation;
    QTest::newRow("oauthbin.com_get") << "key"
                                      << "secret"
                                      << "requestkey"
                                      << "requestsecret"
                                      << "accesskey"
                                      << "accesssecret"
                                      << QUrl("http://oauthbin.com/v1/request-token")
                                      << QUrl("http://oauthbin.com/v1/access-token")
                                      << QUrl("http://oauthbin.com/v1/echo")
                                      << QNetworkAccessManager::GetOperation;
    QTest::newRow("oauthbin.com_post") << "key"
                                       << "secret"
                                       << "requestkey"
                                       << "requestsecret"
                                       << "accesskey"
                                       << "accesssecret"
                                       << QUrl("http://oauthbin.com/v1/request-token")
                                       << QUrl("http://oauthbin.com/v1/access-token")
                                       << QUrl("http://oauthbin.com/v1/echo")
                                       << QNetworkAccessManager::PostOperation;
}

void tst_QOAuth::fillParameters(QVariantMap *parameters, const QUrlQuery &query)
{
    const auto list = query.queryItems();
    for (auto it = list.begin(), end = list.end(); it != end; ++it)
        parameters->insert(it->first, it->second);
}

void tst_QOAuth::finished()
{
    loop->exit(returnCode = Success);
}

void tst_QOAuth::gotError()
{
    loop->exit(returnCode = Failure);
    disconnect(QObject::sender(), SIGNAL(finished()), this, 0);
}

void tst_QOAuth::createSignature()
{
    // Example from https://dev.twitter.com/oauth/overview/creating-signatures

    QByteArray parameterString, signatureBase, signature;

Jesus Fernandez's avatar
Jesus Fernandez committed
193
    const QUrl url(QStringLiteral("https://api.twitter.com/1/statuses/update.json?include_entities=true"));
Jesus Fernandez's avatar
Jesus Fernandez committed
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
    const QString data = QUrl::fromPercentEncoding("status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21");
    const auto consumerSecret = QStringLiteral("kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw");
    const auto oauthTokenSecret = QStringLiteral("LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE");

    QNetworkAccessManager::Operation operation = QNetworkAccessManager::PostOperation;
    QVariantMap oauthParams;

    oauthParams.insert(QStringLiteral("oauth_consumer_key"),
                       QStringLiteral("xvz1evFS4wEEPTGEFPHBog"));
    oauthParams.insert(QStringLiteral("oauth_nonce"),
                       QStringLiteral("kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"));
    oauthParams.insert(QStringLiteral("oauth_signature_method"),
                       QStringLiteral("HMAC-SHA1"));
    oauthParams.insert(QStringLiteral("oauth_timestamp"), QStringLiteral("1318622958"));
    oauthParams.insert(QStringLiteral("oauth_token"),
                       QStringLiteral("370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"));
    oauthParams.insert(QStringLiteral("oauth_version"), QStringLiteral("1.0"));

    QVariantMap otherParametersFromData;
    fillParameters(&otherParametersFromData, QUrlQuery(data));

    // HTTP Method
    QCOMPARE(QOAuth1Private::operationName(operation), QStringLiteral("POST"));
    // Base URL
    QCOMPARE(url.toString(QUrl::RemoveQuery),
             QStringLiteral("https://api.twitter.com/1/statuses/update.json"));

    struct OAuthSubClass : QOAuth1 {
        using QOAuth1::parameterString;
Jesus Fernandez's avatar
Jesus Fernandez committed
223 224
        using QOAuth1::signatureBaseString;
        using QOAuth1::signature;
Jesus Fernandez's avatar
Jesus Fernandez committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    };

    // Creating parameter string
    {
        QVariantMap parameters = oauthParams;
        parameters.unite(otherParametersFromData);
        fillParameters(&parameters, QUrlQuery(url.query()));
        parameterString = OAuthSubClass::parameterString(parameters);

        parameters.insertMulti(parameters.keys().first(), QString());
        QTest::ignoreMessage(QtWarningMsg, QRegularExpression("^QOAuth: duplicated key .*$"));
        OAuthSubClass::parameterString(parameters);
    }

    QCOMPARE(parameterString, QByteArray("include_entities=true"
                                         "&oauth_consumer_key=xvz1evFS4wEEPTGEFPHBog"
                                         "&oauth_nonce=kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"
                                         "&oauth_signature_method=HMAC-SHA1"
                                         "&oauth_timestamp=1318622958"
                                         "&oauth_token=370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"
                                         "&oauth_version=1.0"
                                         "&status=Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed%20OAuth%20request%21"));

    // Collecting parameters
    oauthParams.unite(otherParametersFromData);
Jesus Fernandez's avatar
Jesus Fernandez committed
250
    signatureBase = OAuthSubClass::signatureBaseString(oauthParams, url, operation);
Jesus Fernandez's avatar
Jesus Fernandez committed
251 252 253 254 255 256 257 258
    QCOMPARE(signatureBase, QByteArray("POST&https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json"
                                       "&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog"
                                       "%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"
                                       "%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958"
                                       "%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"
                                       "%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521"));

    // Getting a signing key
Jesus Fernandez's avatar
Jesus Fernandez committed
259
    signature = OAuthSubClass::signature(oauthParams, url, operation, consumerSecret, oauthTokenSecret);
Jesus Fernandez's avatar
Jesus Fernandez committed
260 261 262 263 264
    QCOMPARE(signature, QByteArray("tnnArxj06cWHq44gCs1OSKk/jLY="));
}

void tst_QOAuth::getToken_data()
{
Jesus Fernandez's avatar
Jesus Fernandez committed
265 266 267
    QTest::addColumn<QPair<QString, QString>>("clientCredentials");
    QTest::addColumn<QPair<QString, QString>>("token");
    QTest::addColumn<QPair<QString, QString>>("expectedToken");
Jesus Fernandez's avatar
Jesus Fernandez committed
268 269 270 271 272
    QTest::addColumn<QUrl>("url");
    QTest::addColumn<QNetworkAccessManager::Operation>("requestType");

    // term.ie

Jesus Fernandez's avatar
Jesus Fernandez committed
273 274 275 276 277 278 279
    const QPair<QString, QString> emptyCredentials;

    QTest::newRow("term.ie_request_get") << qMakePair(QStringLiteral("key"),
                                                      QStringLiteral("secret"))
                                         << emptyCredentials
                                         << qMakePair(QStringLiteral("requestkey"),
                                                      QStringLiteral("requestsecret"))
Jesus Fernandez's avatar
Jesus Fernandez committed
280 281 282
                                         << QUrl("http://term.ie/oauth/example/request_token.php")
                                         << QNetworkAccessManager::GetOperation;

Jesus Fernandez's avatar
Jesus Fernandez committed
283 284 285 286 287
    QTest::newRow("term.ie_request_post") << qMakePair(QStringLiteral("key"),
                                                       QStringLiteral("secret"))
                                          << emptyCredentials
                                          << qMakePair(QStringLiteral("requestkey"),
                                                       QStringLiteral("requestsecret"))
Jesus Fernandez's avatar
Jesus Fernandez committed
288 289 290
                                          << QUrl("http://term.ie/oauth/example/request_token.php")
                                          << QNetworkAccessManager::PostOperation;

Jesus Fernandez's avatar
Jesus Fernandez committed
291 292 293 294 295 296
    QTest::newRow("term.ie_access_get") << qMakePair(QStringLiteral("key"),
                                                     QStringLiteral("secret"))
                                        << qMakePair(QStringLiteral("requestkey"),
                                                     QStringLiteral("requestsecret"))
                                        << qMakePair(QStringLiteral("accesskey"),
                                                     QStringLiteral("accesssecret"))
Jesus Fernandez's avatar
Jesus Fernandez committed
297 298 299
                                        << QUrl("http://term.ie/oauth/example/access_token.php")
                                        << QNetworkAccessManager::GetOperation;

Jesus Fernandez's avatar
Jesus Fernandez committed
300 301 302 303 304
    QTest::newRow("term.ie_access_post") << qMakePair(QStringLiteral("key"),
                                                      QStringLiteral("secret"))
                                         << qMakePair(QStringLiteral("requestkey"),
                                                      QStringLiteral("requestsecret"))
                                         << qMakePair(QStringLiteral("accesskey"),
Jesus Fernandez's avatar
Jesus Fernandez committed
305
                                                                QStringLiteral("accesssecret"))
Jesus Fernandez's avatar
Jesus Fernandez committed
306 307 308 309 310
                                         << QUrl("http://term.ie/oauth/example/access_token.php")
                                         << QNetworkAccessManager::PostOperation;

    // oauthbin.com

Jesus Fernandez's avatar
Jesus Fernandez committed
311 312 313 314 315
    QTest::newRow("oauthbin.com_request_get") << qMakePair(QStringLiteral("key"),
                                                           QStringLiteral("secret"))
                                              << emptyCredentials
                                              << qMakePair(QStringLiteral("requestkey"),
                                                           QStringLiteral("requestsecret"))
Jesus Fernandez's avatar
Jesus Fernandez committed
316 317 318
                                              << QUrl("http://oauthbin.com/v1/request-token")
                                              << QNetworkAccessManager::GetOperation;

Jesus Fernandez's avatar
Jesus Fernandez committed
319 320 321 322 323
    QTest::newRow("oauthbin.com_request_post") << qMakePair(QStringLiteral("key"),
                                                            QStringLiteral("secret"))
                                               << emptyCredentials
                                               << qMakePair(QStringLiteral("requestkey"),
                                                            QStringLiteral("requestsecret"))
Jesus Fernandez's avatar
Jesus Fernandez committed
324 325 326
                                               << QUrl("http://oauthbin.com/v1/request-token")
                                               << QNetworkAccessManager::PostOperation;

Jesus Fernandez's avatar
Jesus Fernandez committed
327 328 329 330 331 332
    QTest::newRow("oauthbin.com_access_get") << qMakePair(QStringLiteral("key"),
                                                          QStringLiteral("secret"))
                                             << qMakePair(QStringLiteral("requestkey"),
                                                          QStringLiteral("requestsecret"))
                                             << qMakePair(QStringLiteral("accesskey"),
                                                          QStringLiteral("accesssecret"))
Jesus Fernandez's avatar
Jesus Fernandez committed
333 334 335
                                             << QUrl("http://oauthbin.com/v1/access-token")
                                             << QNetworkAccessManager::GetOperation;

Jesus Fernandez's avatar
Jesus Fernandez committed
336 337 338 339 340 341
    QTest::newRow("oauthbin.com_access_post") << qMakePair(QStringLiteral("key"),
                                                           QStringLiteral("secret"))
                                              << qMakePair(QStringLiteral("requestkey"),
                                                           QStringLiteral("requestsecret"))
                                              << qMakePair(QStringLiteral("accesskey"),
                                                           QStringLiteral("accesssecret"))
Jesus Fernandez's avatar
Jesus Fernandez committed
342 343 344 345 346 347
                                              << QUrl("http://oauthbin.com/v1/access-token")
                                              << QNetworkAccessManager::PostOperation;
}

void tst_QOAuth::getToken()
{
Jesus Fernandez's avatar
Jesus Fernandez committed
348 349 350 351
    using StringPair = QPair<QString, QString>;
    QFETCH(StringPair, clientCredentials);
    QFETCH(StringPair, token);
    QFETCH(StringPair, expectedToken);
Jesus Fernandez's avatar
Jesus Fernandez committed
352 353 354
    QFETCH(QUrl, url);
    QFETCH(QNetworkAccessManager::Operation, requestType);

Jesus Fernandez's avatar
Jesus Fernandez committed
355
    QPair<QString, QString> tokenReceived;
Jesus Fernandez's avatar
Jesus Fernandez committed
356 357 358
    QNetworkAccessManager networkAccessManager;
    QNetworkReplyPtr reply;

Jesus Fernandez's avatar
Jesus Fernandez committed
359 360 361 362 363
    struct OAuth1 : QOAuth1
    {
        using QOAuth1::QOAuth1;
        using QOAuth1::requestTokenCredentials;
    }o1(&networkAccessManager);
Jesus Fernandez's avatar
Jesus Fernandez committed
364

Jesus Fernandez's avatar
Jesus Fernandez committed
365 366
    o1.setClientCredentials(clientCredentials.first, clientCredentials.second);
    o1.setTokenCredentials(token);
Jesus Fernandez's avatar
Jesus Fernandez committed
367
    o1.setTemporaryCredentialsUrl(url);
Jesus Fernandez's avatar
Jesus Fernandez committed
368
    reply.reset(o1.requestTokenCredentials(requestType, url, token));
Jesus Fernandez's avatar
Jesus Fernandez committed
369
    QVERIFY(!reply.isNull());
Jesus Fernandez's avatar
Jesus Fernandez committed
370 371 372 373 374
    connect(&o1, &QOAuth1::tokenChanged, [&tokenReceived](const QString &token){
        tokenReceived.first = token;
    });
    connect(&o1, &QOAuth1::tokenSecretChanged, [&tokenReceived](const QString &tokenSecret) {
        tokenReceived.second = tokenSecret;
Jesus Fernandez's avatar
Jesus Fernandez committed
375 376
    });
    QVERIFY(waitForFinish(reply) == Success);
Jesus Fernandez's avatar
Jesus Fernandez committed
377
    QVERIFY(!tokenReceived.first.isEmpty() && !tokenReceived.second.isEmpty());
Jesus Fernandez's avatar
Jesus Fernandez committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
}

void tst_QOAuth::grant_data()
{
    test_data();
}

void tst_QOAuth::grant()
{
    QFETCH(QString, consumerKey);
    QFETCH(QString, consumerSecret);
    QFETCH(QString, requestToken);
    QFETCH(QString, requestTokenSecret);
    QFETCH(QString, accessToken);
    QFETCH(QString, accessTokenSecret);
    QFETCH(QUrl, requestTokenUrl);
    QFETCH(QUrl, accessTokenUrl);

    bool tokenReceived = false;
    QNetworkAccessManager networkAccessManager;

    QOAuth1 o1(&networkAccessManager);

    {
Jesus Fernandez's avatar
Jesus Fernandez committed
402 403 404 405 406
        QSignalSpy clientIdentifierSpy(&o1, &QOAuth1::clientIdentifierChanged);
        QSignalSpy clientSharedSecret(&o1, &QOAuth1::clientSharedSecretChanged);
        o1.setClientCredentials(consumerKey, consumerSecret);
        QCOMPARE(clientIdentifierSpy.count(), 1);
        QCOMPARE(clientSharedSecret.count(), 1);
Jesus Fernandez's avatar
Jesus Fernandez committed
407 408
    }
    {
Jesus Fernandez's avatar
Jesus Fernandez committed
409 410
        QSignalSpy spy(&o1, &QOAuth1::temporaryCredentialsUrlChanged);
        o1.setTemporaryCredentialsUrl(requestTokenUrl);
Jesus Fernandez's avatar
Jesus Fernandez committed
411 412 413
        QCOMPARE(spy.count(), 1);
    }
    {
Jesus Fernandez's avatar
Jesus Fernandez committed
414 415
        QSignalSpy spy(&o1, &QOAuth1::tokenCredentialsUrlChanged);
        o1.setTokenCredentialsUrl(accessTokenUrl);
Jesus Fernandez's avatar
Jesus Fernandez committed
416 417 418
        QCOMPARE(spy.count(), 1);
    }
    connect(&o1, &QAbstractOAuth::statusChanged, [&](QAbstractOAuth::Status status) {
Jesus Fernandez's avatar
Jesus Fernandez committed
419
        if (status == QAbstractOAuth::Status::TemporaryTokenReceived) {
Jesus Fernandez's avatar
Jesus Fernandez committed
420
            if (!requestToken.isEmpty())
Jesus Fernandez's avatar
Jesus Fernandez committed
421
                QCOMPARE(requestToken, o1.tokenCredentials().first);
Jesus Fernandez's avatar
Jesus Fernandez committed
422
            if (!requestTokenSecret.isEmpty())
Jesus Fernandez's avatar
Jesus Fernandez committed
423
                QCOMPARE(requestTokenSecret, o1.tokenCredentials().second);
Jesus Fernandez's avatar
Jesus Fernandez committed
424 425
            tokenReceived = true;
        }
Jesus Fernandez's avatar
Jesus Fernandez committed
426
        else if (status == QAbstractOAuth::Status::Granted) {
Jesus Fernandez's avatar
Jesus Fernandez committed
427
            if (!accessToken.isEmpty())
Jesus Fernandez's avatar
Jesus Fernandez committed
428
                QCOMPARE(accessToken, o1.tokenCredentials().first);
Jesus Fernandez's avatar
Jesus Fernandez committed
429
            if (!accessTokenSecret.isEmpty())
Jesus Fernandez's avatar
Jesus Fernandez committed
430
                QCOMPARE(accessTokenSecret, o1.tokenCredentials().second);
Jesus Fernandez's avatar
Jesus Fernandez committed
431 432 433 434 435 436 437 438 439 440 441
            tokenReceived = true;
        }
    });

    QEventLoop loop;

    QTimer::singleShot(10000, &loop, &QEventLoop::quit);
    connect(&o1, &QOAuth1::granted, &loop, &QEventLoop::quit);
    o1.grant();
    loop.exec();
    QVERIFY(tokenReceived);
Jesus Fernandez's avatar
Jesus Fernandez committed
442
    QCOMPARE(o1.status(), QAbstractOAuth::Status::Granted);
Jesus Fernandez's avatar
Jesus Fernandez committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
}

void tst_QOAuth::authenticatedCalls_data()
{
    QTest::addColumn<QString>("consumerKey");
    QTest::addColumn<QString>("consumerSecret");
    QTest::addColumn<QString>("accessKey");
    QTest::addColumn<QString>("accessKeySecret");
    QTest::addColumn<QUrl>("url");
    QTest::addColumn<QVariantMap>("parameters");
    QTest::addColumn<QNetworkAccessManager::Operation>("operation");

    const QVariantMap parameters { { QStringLiteral("first"), QStringLiteral("first") },
                                   { QStringLiteral("second"), QStringLiteral("second") },
                                   { QStringLiteral("third"), QStringLiteral("third") } };

    QTest::newRow("term.ie_get") << "key"
                                 << "secret"
                                 << "accesskey"
                                 << "accesssecret"
                                 << QUrl("http://term.ie/oauth/example/echo_api.php")
                                 << parameters
                                 << QNetworkAccessManager::GetOperation;
    QTest::newRow("term.ie_post") << "key"
                                  << "secret"
                                  << "accesskey"
                                  << "accesssecret"
                                  << QUrl("http://term.ie/oauth/example/echo_api.php")
                                  << parameters
                                  << QNetworkAccessManager::PostOperation;
    QTest::newRow("oauthbin.com_get") << "key"
                                      << "secret"
                                      << "accesskey"
                                      << "accesssecret"
                                      << QUrl("http://oauthbin.com/v1/echo")
                                      << parameters
                                      << QNetworkAccessManager::GetOperation;
    QTest::newRow("oauthbin.com_post") << "key"
                                       << "secret"
                                       << "accesskey"
                                       << "accesssecret"
                                       << QUrl("http://oauthbin.com/v1/echo")
                                       << parameters
                                       << QNetworkAccessManager::PostOperation;
}

void tst_QOAuth::authenticatedCalls()
{
    QFETCH(QString, consumerKey);
    QFETCH(QString, consumerSecret);
    QFETCH(QString, accessKey);
    QFETCH(QString, accessKeySecret);
    QFETCH(QUrl, url);
    QFETCH(QVariantMap, parameters);
    QFETCH(QNetworkAccessManager::Operation, operation);

    QNetworkAccessManager networkAccessManager;
    QNetworkReplyPtr reply;
    QString receivedData;
    QString parametersString;
    {
        bool first = true;
        for (auto it = parameters.begin(), end = parameters.end(); it != end; ++it) {
            if (first)
                first = false;
            else
                parametersString += QLatin1Char('&');
            parametersString += it.key() + QLatin1Char('=') + it.value().toString();
        }
    }

    QOAuth1 o1(&networkAccessManager);
Jesus Fernandez's avatar
Jesus Fernandez committed
515 516
    o1.setClientCredentials(consumerKey, consumerSecret);
    o1.setTokenCredentials(accessKey, accessKeySecret);
Jesus Fernandez's avatar
Jesus Fernandez committed
517
    if (operation == QNetworkAccessManager::GetOperation)
Jesus Fernandez's avatar
Jesus Fernandez committed
518
        reply.reset(o1.get(url, parameters));
Jesus Fernandez's avatar
Jesus Fernandez committed
519
    else if (operation == QNetworkAccessManager::PostOperation)
Jesus Fernandez's avatar
Jesus Fernandez committed
520
        reply.reset(o1.post(url, parameters));
Jesus Fernandez's avatar
Jesus Fernandez committed
521 522 523
    QVERIFY(!reply.isNull());
    QVERIFY(!reply->isFinished());

Jesus Fernandez's avatar
Jesus Fernandez committed
524 525
    connect(&networkAccessManager, &QNetworkAccessManager::finished,
            [&receivedData](QNetworkReply *reply) {
Jesus Fernandez's avatar
Jesus Fernandez committed
526 527 528 529 530 531 532 533 534
        receivedData = QString::fromUtf8(reply->readAll());
    });
    QVERIFY(waitForFinish(reply) == Success);
    QCOMPARE(receivedData, parametersString);
    reply.clear();
}

QTEST_MAIN(tst_QOAuth)
#include "tst_qoauth.moc"