File: testhttpserver.cpp

package info (click to toggle)
qcoro 0.12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,700 kB
  • sloc: cpp: 8,573; python: 32; xml: 26; makefile: 23; sh: 15
file content (73 lines) | stat: -rw-r--r-- 2,032 bytes parent folder | download | duplicates (3)
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
// SPDX-FileCopyrightText: 2021 Daniel Vrátil <dvratil@kde.org>
//
// SPDX-License-Identifier: MIT

#include "testlibs/testhttpserver.h"

#include <QDebug>
#include <QEventLoop>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QTcpServer>
#include <QTest>
#include <QTimer>

Q_DECLARE_METATYPE(std::chrono::seconds)

using namespace std::chrono_literals;

class TestHttpServerTest : public QObject {
    Q_OBJECT

private Q_SLOTS:
    void init() {
        mServer.start(QHostAddress::LocalHost);
    }

    void cleanup() {
        mServer.stop();
    }

    void testGet_data() {
        QTest::addColumn<QString>("url");
        QTest::addColumn<QByteArray>("expectedData");
        QTest::addColumn<std::chrono::seconds>("timeout");

        QTest::newRow("/") << QStringLiteral("http://localhost:%1/") << QByteArray{"abcdef"} << 5s;

        QTest::newRow("/block") << QStringLiteral("http://localhost:%1/block")
                                << QByteArray{"abcdef"} << 5s;

        QTest::newRow("/stream") << QStringLiteral("http://localhost:%1/stream")
                                 << QByteArray{"Hola 0\nHola 1\nHola 2\nHola 3\nHola 4\nHola "
                                               "5\nHola 6\nHola 7\nHola 8\nHola 9\n"}
                                 << 15s;
    }

    void testGet() {
        QFETCH(QString, url);
        QFETCH(QByteArray, expectedData);
        QFETCH(std::chrono::seconds, timeout);

        QNetworkAccessManager nam;
        QEventLoop el;

        auto reply = std::unique_ptr<QNetworkReply>(
            nam.get(QNetworkRequest{QUrl{url.arg(mServer.port())}}));
        connect(reply.get(), &QNetworkReply::finished, &el, &QEventLoop::quit);

        QTimer::singleShot(timeout, &el, [&el]() mutable { el.exit(1); });

        QCOMPARE(el.exec(), 0);

        QCOMPARE(reply->readAll(), expectedData);
    }

private:
    TestHttpServer<QTcpServer> mServer;
};

QTEST_GUILESS_MAIN(TestHttpServerTest)

#include "testhttpserver.moc"