File: testhttpserver.h

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 (188 lines) | stat: -rw-r--r-- 5,227 bytes parent folder | download | duplicates (2)
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
// SPDX-FileCopyrightText: 2021 Daniel Vrátil <dvratil@kde.org>
//
// SPDX-License-Identifier: MIT

#pragma once

#include <QDebug>
#include <QThread>
#include <QTest>

#include <condition_variable>
#include <mutex>
#include <atomic>

class QTcpServer;
class QTcpSocket;
class QLocalServer;
class QLocalSocket;

template<typename Func>
class Thread : public QThread {
public:
    explicit Thread(Func &&f) : mFunc(std::forward<Func>(f)) {}

    ~Thread() = default;

    void run() override {
        mFunc();
    }

private:
    Func mFunc;
};

template<typename Func>
Thread(Func &&) -> Thread<Func>;

template<typename ServerType>
struct socket_for_server {};

template<> struct socket_for_server<QTcpServer> {
    using type = QTcpSocket;
};
template<> struct socket_for_server<QLocalServer> {
    using type = QLocalSocket;
};

template<typename ServerType>
class TestHttpServer {
    using SocketType = typename socket_for_server<ServerType>::type;

public:
    template<typename T>
    void start(const T &name) {
        mPort = 0;
        mHasConnection = false;
        mStop = false;
        mExpectTimeout = false;
        // Can't use QThread::create, it's only available when Qt is built with C++17,
        // which some distros don't have :(
        mThread.reset(new Thread([this, name]() { run(name); }));
        mThread->start();
        std::unique_lock lock(mReadyMutex);
        mServerReady.wait(lock, [this]() { return mPort != 0; });
    }

    void stop() {
        mStop = true;
        if (mThread->isRunning()) {
            mThread->wait();
        }
        mThread.reset();
        mPort = 0;
        mHasConnection = false;
    }

    uint16_t port() const {
        return mPort;
    }

    void setExpectTimeout(bool expectTimeout) {
        mExpectTimeout = expectTimeout;
    }

    bool waitForConnection() {
        std::unique_lock lock(mReadyMutex);
        return mServerReady.wait_for(lock, std::chrono::seconds(5), [this]() { return mHasConnection; });
    }

private:
    template<typename T>
    void run(const T &name) {
        using namespace std::chrono_literals;

        ServerType server{};
        if (!server.listen(name)) {
            qDebug() << "Error listening:" << server.serverError();
            return;
        }
        assert(server.isListening());

        {
            std::scoped_lock lock(mReadyMutex);
            if constexpr (std::is_same_v<ServerType, QTcpServer>) {
                mPort = server.serverPort();
            } else {
                mPort = 1;
            }
        }

        SocketType *conn = nullptr;
        mServerReady.notify_all();
        for (int i = 0; i < 10 && !mStop; ++i) {
            if (server.waitForNewConnection(1000)) {
                conn = server.nextPendingConnection();
                break;
            }
        }

        if (!conn) {
            if (!mExpectTimeout) {
                QFAIL("No incoming connection within timeout!");
            }
            mPort = 0;
            return;
        }

        mHasConnection = true;
        mServerReady.notify_all();

        if (conn->waitForReadyRead(10000)) {
            const auto request = conn->readLine();
            qDebug() << request;
            if (request == "GET /stream HTTP/1.1\r\n") {
                QStringList lines;
                for (int i = 0; i < 10; ++i) {
                    lines.push_back(QStringLiteral("Hola %1\n").arg(i));
                }

                const auto len =
                    std::accumulate(lines.cbegin(), lines.cend(), 0,
                                    [](int l, const QString &s) { return l + s.size(); });
                conn->write("HTTP/1.1 200 OK\r\n"
                            "Content-Type: text/plain\r\n"
                            "Content-Length: " +
                            QByteArray::number(len) +
                            "\r\n"
                            "\r\n");
                conn->flush();
                for (const auto &line : lines) {
                    conn->write(line.toUtf8());
                    conn->flush();
                    std::this_thread::sleep_for(100ms);
                }
            } else {
                if (request == "GET /block HTTP/1.1\r\n") {
                    std::this_thread::sleep_for(500ms);
                }

                conn->write("HTTP/1.1 200 OK\r\n"
                            "Content-Type: text/plain\r\n"
                            "\r\n"
                            "abcdef");
            }
            conn->flush();
            conn->close();
        } else if (!mStop) {
            if (conn->state() == std::remove_cvref_t<decltype(*conn)>::ConnectedState) {
                if (!mExpectTimeout) {
                    QFAIL("No request within 10 seconds");
                }
            } else {
                qDebug() << "Client disconnected without sending request";
            }
        }

        delete conn;
        mPort = 0;
    }

    std::unique_ptr<QThread> mThread;
    std::mutex mReadyMutex;
    std::condition_variable mServerReady;
    uint16_t mPort = 0;
    bool mHasConnection = false;
    std::atomic_bool mStop = false;
    std::atomic_bool mExpectTimeout = false;
};