aboutsummaryrefslogtreecommitdiffstats
path: root/tests/auto/shared.h
blob: 8f85f5d6c03817b13cc14d28fa92651edbf15cec (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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $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$
**
****************************************************************************/
#ifndef QBS_TEST_SHARED_H
#define QBS_TEST_SHARED_H

#include <tools/hostosinfo.h>
#include <tools/profile.h>
#include <tools/settings.h>

#include <QtCore/qbytearray.h>
#include <QtCore/qcryptographichash.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qdebug.h>
#include <QtCore/qdir.h>
#include <QtCore/qfile.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qstring.h>
#include <QtCore/qtemporaryfile.h>

#include <QtTest/qtest.h>

#include <memory>

#define REPLACE_IN_FILE(filePath, oldContent, newContent)                           \
    do {                                                                            \
        QFile f((filePath));                                                        \
        QVERIFY2(f.open(QIODevice::ReadWrite), qPrintable(f.errorString()));        \
        QByteArray content = f.readAll();                                           \
        const QByteArray savedContent = content;                                    \
        content.replace((oldContent), (newContent));                                \
        QVERIFY(content != savedContent);                                           \
        f.resize(0);                                                                \
        f.write(content);                                                           \
    } while (false)

inline int testTimeoutInMsecs()
{
    bool ok;
    int timeoutInSecs = qEnvironmentVariableIntValue("QBS_AUTOTEST_TIMEOUT", &ok);
    if (!ok)
        timeoutInSecs = 600;
    return timeoutInSecs * 1000;
}

// On Windows, it appears that a lock is sometimes held on files for a short while even after
// they are closed. The likelihood for that seems to increase with the slowness of the machine.
inline void waitForFileUnlock()
{
    bool ok;
    int timeoutInSecs = qEnvironmentVariableIntValue("QBS_AUTOTEST_IO_GRACE_PERIOD", &ok);
    if (!ok)
        timeoutInSecs = qbs::Internal::HostOsInfo::isWindowsHost() ? 1 : 0;
    if (timeoutInSecs > 0)
        QTest::qWait(timeoutInSecs * 1000);
}

using SettingsPtr = std::unique_ptr<qbs::Settings>;
inline SettingsPtr settings()
{
    const QString settingsDir = QLatin1String(qgetenv("QBS_AUTOTEST_SETTINGS_DIR"));
    return SettingsPtr(new qbs::Settings(settingsDir));
}

inline QString profileName()
{
    const QString suiteProfile = QLatin1String(
                qgetenv("QBS_AUTOTEST_PROFILE_" QBS_TEST_SUITE_NAME));
    if (!suiteProfile.isEmpty())
        return suiteProfile;
    const QString profile = QLatin1String(qgetenv("QBS_AUTOTEST_PROFILE"));
    return !profile.isEmpty() ? profile : QLatin1String("none");
}

inline QString relativeBuildDir(const QString &configurationName = QString())
{
    return !configurationName.isEmpty() ? configurationName : QLatin1String("default");
}

inline QString relativeBuildGraphFilePath(const QString &configName = QString()) {
    return relativeBuildDir(configName) + QLatin1Char('/') + relativeBuildDir(configName)
            + QLatin1String(".bg");
}

inline bool regularFileExists(const QString &filePath)
{
    const QFileInfo fi(filePath);
    return fi.exists() && fi.isFile();
}

inline bool directoryExists(const QString &dirPath)
{
    const QFileInfo fi(dirPath);
    return fi.exists() && fi.isDir();
}

struct ReadFileContentResult
{
    QByteArray content;
    QString errorString;
};

inline ReadFileContentResult readFileContent(const QString &filePath)
{
    ReadFileContentResult result;
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        result.errorString = file.errorString();
        return result;
    }
    result.content = file.readAll();
    return result;
}

inline QByteArray diffText(const QByteArray &actual, const QByteArray &expected)
{
    QByteArray result;
    QList<QByteArray> actualLines = actual.split('\n');
    QList<QByteArray> expectedLines = expected.split('\n');
    int n = 1;
    while (!actualLines.isEmpty() && !expectedLines.isEmpty()) {
        QByteArray actualLine = actualLines.takeFirst();
        QByteArray expectedLine = expectedLines.takeFirst();
        if (actualLine != expectedLine) {
            result += QStringLiteral("%1:  actual: %2\n%1:expected: %3\n")
                    .arg(n, 2)
                    .arg(QString::fromUtf8(actualLine))
                    .arg(QString::fromUtf8(expectedLine))
                    .toUtf8();
        }
        n++;
    }
    auto addLines = [&result, &n] (const QList<QByteArray> &lines) {
        for (const QByteArray &line : qAsConst(lines)) {
            result += QStringLiteral("%1:          %2\n").arg(n).arg(QString::fromUtf8(line));
            n++;
        }
    };
    if (!actualLines.isEmpty()) {
        result += "Extra unexpected lines:\n";
        addLines(actualLines);
    }
    if (!expectedLines.isEmpty()) {
        result += "Missing expected lines:\n";
        addLines(expectedLines);
    }
    return result;
}

#define READ_TEXT_FILE(filePath, contentVariable)                                                  \
    QByteArray contentVariable;                                                                    \
    {                                                                                              \
        auto c = readFileContent(filePath);                                                        \
        QVERIFY2(c.errorString.isEmpty(),                                                          \
                 qUtf8Printable(QStringLiteral("Cannot open file %1. %2")                          \
                                .arg(filePath, c.errorString)));                                   \
        contentVariable = std::move(c.content);                                                    \
    }

#define TEXT_FILE_COMPARE(actualFilePath, expectedFilePath)                                        \
    {                                                                                              \
        READ_TEXT_FILE(actualFilePath, ba1);                                                       \
        READ_TEXT_FILE(expectedFilePath, ba2);                                                     \
        if (ba1 != ba2) {                                                                          \
            QByteArray msg = "File contents differ:\n" + diffText(ba1, ba2);                       \
            QFAIL(msg.constData());                                                                \
        }                                                                                          \
    }

template <typename T>
inline QString prefixedIfNonEmpty(const T &prefix, const QString &str)
{
    if (str.isEmpty())
        return QString();
    return prefix + str;
}

inline QString uniqueProductName(const QString &productName,
                                 const QString &multiplexConfigurationId)
{
    return productName + prefixedIfNonEmpty(QLatin1Char('.'), multiplexConfigurationId);
}

inline QString relativeProductBuildDir(const QString &productName,
                                       const QString &configurationName = QString(),
                                       const QString &multiplexConfigurationId = QString())
{
    const QString fullName = uniqueProductName(productName, multiplexConfigurationId);
    QString dirName = qbs::Internal::HostOsInfo::rfc1034Identifier(fullName);
    const QByteArray hash = QCryptographicHash::hash(fullName.toUtf8(), QCryptographicHash::Sha1);
    dirName.append('.').append(hash.toHex().left(8));
    return relativeBuildDir(configurationName) + '/' + dirName;
}

inline QString relativeExecutableFilePath(const QString &productName,
                                          const QString &configName = QString())
{
    return relativeProductBuildDir(productName, configName) + '/'
            + qbs::Internal::HostOsInfo::appendExecutableSuffix(productName);
}

inline void waitForNewTimestamp(const QString &testDir)
{
    // Waits for the time that corresponds to the host file system's time stamp granularity.
    if (qbs::Internal::HostOsInfo::isWindowsHost()) {
        QTest::qWait(1);        // NTFS has 100 ns precision. Let's ignore exFAT.
    } else {
        const QString nameTemplate = testDir + "/XXXXXX";
        QTemporaryFile f1(nameTemplate);
        if (!f1.open())
            qFatal("Failed to open temp file");
        const QDateTime initialTime = QFileInfo(f1).lastModified();
        int totalMsPassed = 0;
        while (totalMsPassed <= 2000) {
            static const int increment = 50;
            QTest::qWait(increment);
            totalMsPassed += increment;
            QTemporaryFile f2(nameTemplate);
            if (!f2.open())
                qFatal("Failed to open temp file");
            if (QFileInfo(f2).lastModified() > initialTime)
                return;
        }
        qWarning("Got no new timestamp after two seconds, going ahead anyway. Subsequent "
                 "test failure might not be genuine.");
    }
}

inline void touch(const QString &fn)
{
    QFile f(fn);
    int s = f.size();
    if (!f.open(QFile::ReadWrite))
        qFatal("cannot open file %s", qPrintable(fn));
    f.resize(s+1);
    f.resize(s);
}

inline void copyFileAndUpdateTimestamp(const QString &source, const QString &target)
{
    QFile::remove(target);
    if (!QFile::copy(source, target))
        qFatal("Failed to copy '%s' to '%s'", qPrintable(source), qPrintable(target));
    touch(target);
}

inline QString objectFileName(const QString &baseName, const QString &profileName)
{
    const SettingsPtr s = settings();
    qbs::Profile profile(profileName, s.get());
    const auto tc = profile.value("qbs.toolchainType").toString();
    const auto tcList = profile.value("qbs.toolchain").toStringList();
    const bool isMsvc = tc == "msvc" || tcList.contains("msvc")
            || (tc.isEmpty() && tcList.isEmpty() && qbs::Internal::HostOsInfo::isWindowsHost());
    const QString suffix = isMsvc ? "obj" : "o";
    return baseName + '.' + suffix;
}

inline QString inputDirHash(const QString &dir)
{
    return QCryptographicHash::hash(dir.toLatin1(), QCryptographicHash::Sha1).toHex().left(16);
}

inline QString testWorkDir(const QString &testName)
{
    QString dir = QDir::fromNativeSeparators(QString::fromLocal8Bit(qgetenv("QBS_TEST_WORK_ROOT")));
    if (dir.isEmpty()) {
        dir = QCoreApplication::applicationDirPath() + QStringLiteral("/../tests/auto/");
    } else {
        if (!dir.endsWith(QLatin1Char('/')))
            dir += QLatin1Char('/');
    }
    return dir + testName + "/testWorkDir";
}

inline bool copyDllExportHeader(const QString &srcDataDir, const QString &targetDataDir)
{
    QFile sourceFile(srcDataDir + "/../../dllexport.h");
    const QString targetPath = targetDataDir + "/dllexport.h";
    QFile::remove(targetPath);
    return sourceFile.copy(targetPath);
}

inline qbs::Internal::HostOsInfo::HostOs targetOs()
{
    const SettingsPtr s = settings();
    const qbs::Profile buildProfile(profileName(), s.get());
    const QString targetPlatform = buildProfile.value("qbs.targetPlatform").toString();
    if (!targetPlatform.isEmpty()) {
        const std::vector<std::string> targetOS = qbs::Internal::HostOsInfo::canonicalOSIdentifiers(
                    targetPlatform.toStdString());
        if (qbs::Internal::contains(targetOS, "windows"))
            return qbs::Internal::HostOsInfo::HostOsWindows;
        if (qbs::Internal::contains(targetOS, "linux"))
            return qbs::Internal::HostOsInfo::HostOsLinux;
        if (qbs::Internal::contains(targetOS, "macos"))
            return qbs::Internal::HostOsInfo::HostOsMacos;
        if (qbs::Internal::contains(targetOS, "unix"))
            return qbs::Internal::HostOsInfo::HostOsOtherUnix;
        return qbs::Internal::HostOsInfo::HostOsOther;
    }
    return qbs::Internal::HostOsInfo::hostOs();
}

#endif // Include guard.