File: base.h

package info (click to toggle)
znc 1.10.1-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 12,164 kB
  • sloc: cpp: 58,072; javascript: 11,859; python: 1,635; perl: 1,229; tcl: 219; sh: 200; ansic: 187; makefile: 82
file content (252 lines) | stat: -rw-r--r-- 7,877 bytes parent folder | download
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*
 * Copyright (C) 2004-2025 ZNC, see the NOTICE file for details.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <gtest/gtest.h>

#include <QCoreApplication>
#include <QDateTime>
#include <QLocalSocket>
#include <QProcess>
#include <QRegularExpression>
#include <QTcpSocket>

namespace znc_inttest {

template <typename Device>
class IO {
  public:
    IO(Device* device, bool verbose = false)
        : m_device(device), m_verbose(verbose) {}
    virtual ~IO() {}
    void ReadUntil(QByteArray pattern);
    void ReadUntilRe(QString pattern);
    /*
     * Reads from Device until pattern is matched and returns this pattern
     * up to and excluding the first newline. Pattern itself can contain a newline.
     * Have to use second param as the ASSERT_*'s return a non-QByteArray.
     */
    void ReadUntilAndGet(QByteArray pattern, QByteArray& match);
    // Can be used to check that something was not sent. Slow.
    QByteArray ReadRemainder();
    void Write(QByteArray s = "", bool new_line = true);
    void Close();

  private:
    // Need to flush QTcpSocket, and QIODevice doesn't have flush at all...
    static void FlushIfCan(QIODevice*) {}
    static void FlushIfCan(QTcpSocket* sock) { sock->flush(); }
    static void FlushIfCan(QLocalSocket* sock) { sock->flush(); }

    Device* m_device;
    bool m_verbose;
    QByteArray m_readed;
};

template <typename Device>
IO<Device> WrapIO(Device* d) {
    return IO<Device>(d);
}

using Socket = IO<QLocalSocket>;

class Process : public IO<QProcess> {
  public:
    Process(QString cmd, QStringList args,
            std::function<void(QProcess*)> setup = [](QProcess*) {});
    ~Process() override;
    void ShouldFinishItself(int code = 0) {
        m_kill = false;
        m_exit = code;
    }
    void CanDie() { m_allowDie = true; }
    void ShouldFinishInSec(int sec) { m_finishTimeoutSec = sec; }

    // I can't do much about SWIG...
    void CanLeak() { m_allowLeak = true; }

  private:
    bool m_kill = true;
    int m_exit = 0;
    bool m_allowDie = false;
    bool m_allowLeak = false;
    QProcess m_proc;
    int m_finishTimeoutSec = 30;
};

// Can't use QEventLoop without existing QCoreApplication
class App {
  public:
    App() : m_argv(new char{}), m_app(m_argc, &m_argv) {}
    ~App() { delete m_argv; }

  private:
    int m_argc = 1;
    char* m_argv;
    QCoreApplication m_app;
};

// Implementation

template <typename Device>
void IO<Device>::ReadUntil(QByteArray pattern) {
    auto deadline = QDateTime::currentDateTime().addSecs(60);
    while (true) {
        int search = m_readed.indexOf(pattern);
        if (search != -1) {
            m_readed.remove(0, search + pattern.length());
            return;
        }
        if (m_readed.length() > pattern.length()) {
            m_readed = m_readed.right(pattern.length());
        }
        const int timeout_ms =
            QDateTime::currentDateTime().msecsTo(deadline);
        ASSERT_GT(timeout_ms, 0) << "Wanted: " << pattern.toStdString();
        ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms))
            << "Wanted: " << pattern.toStdString();
        QByteArray chunk = m_device->readAll();
        if (m_verbose) {
            std::cout << chunk.toStdString() << std::flush;
        }
        m_readed += chunk;
    }
}

template <typename Device>
void IO<Device>::ReadUntilRe(QString pattern) {
    QRegularExpression expr(pattern);
    auto deadline = QDateTime::currentDateTime().addSecs(60);
    while (true) {
        QRegularExpressionMatch match =
            expr.match(QString::fromUtf8(m_readed), 0,
                          QRegularExpression::PartialPreferCompleteMatch);
        if (match.hasMatch()) {
            m_readed.remove(0, match.capturedEnd());
            return;
        }
        if (!match.hasPartialMatch()) {
            m_readed.clear();
        }
        const int timeout_ms =
            QDateTime::currentDateTime().msecsTo(deadline);
        ASSERT_GT(timeout_ms, 0)
            << "Wanted: " << pattern.toStdString();
        ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms))
            << "Wanted: " << pattern.toStdString();
        QByteArray chunk = m_device->readAll();
        if (m_verbose) {
            std::cout << chunk.toStdString() << std::flush;
        }
        m_readed += chunk;
    }
}

template <typename Device>
void IO<Device>::ReadUntilAndGet(QByteArray pattern, QByteArray& match) {
    auto deadline = QDateTime::currentDateTime().addSecs(60);
    while (true) {
        int search = m_readed.indexOf(pattern);
        if (search != -1) {
            int start = 0;
            /* Don't look for what we've already found */
            if (pattern != "\n") {
              int patlen = pattern.length();
              start = search;
              pattern = QByteArray("\n");
              search = m_readed.indexOf(pattern, start + patlen);
            }
            if (search != -1) {
              match += m_readed.mid(start, search - start);
              m_readed.remove(0, search + 1);
              if (match.endsWith('\r')) {
                  match.chop(1);
              }
              return;
            }
            /* No newline yet, add to retvalue and trunc output */
            match += m_readed.mid(start);
            m_readed.resize(0);
        }
        if (m_readed.length() > pattern.length()) {
            m_readed = m_readed.right(pattern.length());
        }
        const int timeout_ms =
            QDateTime::currentDateTime().msecsTo(deadline);
        ASSERT_GT(timeout_ms, 0) << "Wanted: " << pattern.toStdString();
        ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms))
            << "Wanted: " << pattern.toStdString();
        QByteArray chunk = m_device->readAll();
        if (m_verbose) {
            std::cout << chunk.toStdString() << std::flush;
        }
        m_readed += chunk;
    }
}

template <typename Device>
QByteArray IO<Device>::ReadRemainder() {
    auto deadline = QDateTime::currentDateTime().addSecs(2);
    while (QDateTime::currentDateTime() < deadline) {
        const int timeout_ms =QDateTime::currentDateTime().msecsTo(deadline);
        m_device->waitForReadyRead(std::max(1, timeout_ms));
        QByteArray chunk = m_device->readAll();
        if (m_verbose) {
            std::cout << chunk.toStdString() << std::flush;
        }
        m_readed += chunk;
    }
    QByteArray result = std::move(m_readed);
    m_readed.clear();
    return result;
}

template <typename Device>
void IO<Device>::Write(QByteArray s, bool new_line) {
    if (!m_device) return;
    if (m_verbose) {
        std::cout << s.toStdString() << std::flush;
        if (new_line) {
            std::cout << std::endl;
        }
    }
    s += "\n";
    while (!s.isEmpty()) {
        auto res = m_device->write(s);
        ASSERT_NE(res, -1);
        s.remove(0, res);
    }
    FlushIfCan(m_device);
}

inline void DisconnectFromServer(QTcpSocket* s) { s->disconnectFromHost(); }
inline void DisconnectFromServer(QLocalSocket* s) { s->disconnectFromServer(); }

template <typename Device>
void IO<Device>::Close() {
#ifdef __CYGWIN__
    // Qt on cygwin silently doesn't send the rest of buffer from socket
    // without this line
    sleep(1);
#endif
    DisconnectFromServer(m_device);
}

int PickPortNumber();

}  // namespace znc_inttest