aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/autotest/testconfiguration.cpp
blob: c5ff92026044edbb7bca963a6e623cea88c753d7 (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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/

#include "testconfiguration.h"
#include "testoutputreader.h"
#include "testrunconfiguration.h"

#include <cpptools/cppmodelmanager.h>
#include <cpptools/projectinfo.h>

#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/buildsystem.h>
#include <projectexplorer/buildtargetinfo.h>
#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/environmentaspect.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>

#include <QLoggingCategory>

static Q_LOGGING_CATEGORY(LOG, "qtc.autotest.testconfiguration", QtWarningMsg)

using namespace ProjectExplorer;
using namespace Utils;

namespace Autotest {

TestConfiguration::TestConfiguration(ITestFramework *framework)
    : m_framework(framework)
{
}

TestConfiguration::~TestConfiguration()
{
    m_testCases.clear();
}

static bool isLocal(Target *target)
{
    Kit *kit = target ? target->kit() : nullptr;
    return DeviceTypeKitAspect::deviceTypeId(kit) == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE;
}

static FilePath ensureExeEnding(const FilePath &file)
{
    if (!HostOsInfo::isWindowsHost() || file.isEmpty() || file.toString().toLower().endsWith(".exe"))
        return file;
    return FilePath::fromString(HostOsInfo::withExecutableSuffix(file.toString()));
}

void TestConfiguration::completeTestInformation(ProjectExplorer::RunConfiguration *rc,
                                                TestRunMode runMode)
{
    QTC_ASSERT(rc, return);
    QTC_ASSERT(m_project, return);

    if (hasExecutable()) {
        qCDebug(LOG) << "Executable has been set already - not completing configuration again.";
        return;
    }
    Project *project = SessionManager::startupProject();
    if (!project || project != m_project)
        return;

    Target *target = project->activeTarget();
    if (!target)
        return;

    if (!target->runConfigurations().contains(rc))
        return;

    m_runnable = rc->runnable();
    m_displayName = rc->displayName();

    BuildTargetInfo targetInfo = rc->buildTargetInfo();
    if (!targetInfo.targetFilePath.isEmpty())
        m_runnable.executable = ensureExeEnding(targetInfo.targetFilePath);

    QString buildBase;
    if (auto buildConfig = target->activeBuildConfiguration()) {
        buildBase = buildConfig->buildDirectory().toString();
        const QString projBase = m_project->projectDirectory().toString();
        if (m_projectFile.startsWith(projBase))
            m_buildDir = QFileInfo(buildBase + m_projectFile.mid(projBase.length())).absolutePath();
    }
    if (runMode == TestRunMode::Debug || runMode == TestRunMode::DebugWithoutDeploy)
        m_runConfig = new Internal::TestRunConfiguration(rc->target(), this);
}

void TestConfiguration::completeTestInformation(TestRunMode runMode)
{
    QTC_ASSERT(!m_projectFile.isEmpty(), return);
    QTC_ASSERT(!m_buildTargets.isEmpty(), return);
    QTC_ASSERT(m_project, return);

    if (m_origRunConfig) {
        qCDebug(LOG) << "Using run configuration specified by user or found by first call";
        completeTestInformation(m_origRunConfig, runMode);
        if (hasExecutable()) {
            qCDebug(LOG) << "Completed.\nRunnable:" << m_runnable.executable
                         << "\nArgs:" << m_runnable.commandLineArguments
                         << "\nWorking directory:" << m_runnable.workingDirectory;
            return;
        }
        qCDebug(LOG) << "Failed to complete - using 'normal' way.";
    }
    Project *project = SessionManager::startupProject();
    if (!project || project != m_project) {
        m_project = nullptr;
        return;
    }

    Target *target = project->activeTarget();
    if (!target)
        return;
    qCDebug(LOG) << "ActiveTargetName\n    " << target->displayName();
    if (const auto kit = target->kit())
        qCDebug(LOG) << "SupportedPlatforms\n    " << kit->supportedPlatforms();

    const QSet<QString> buildSystemTargets = m_buildTargets;
    qCDebug(LOG) << "BuildSystemTargets\n    " << buildSystemTargets;
    const QList<BuildTargetInfo> buildTargets
            = Utils::filtered(target->buildSystem()->applicationTargets(),
                              [&buildSystemTargets](const BuildTargetInfo &bti) {
        return buildSystemTargets.contains(bti.buildKey);
    });
    if (buildTargets.size() > 1 )  // there are multiple executables with the same build target
        return;                    // let the user decide which one to run

    const BuildTargetInfo targetInfo = buildTargets.first();

    // we might end up with an empty targetFilePath - e.g. when having a library we just link to
    // there would be no BuildTargetInfo that could match
    if (targetInfo.targetFilePath.isEmpty()) {
        qCDebug(LOG) << "BuildTargetInfos";
        // if there is only one build target just use it (but be honest that we're deducing)
        m_deducedConfiguration = true;
        m_deducedFrom = targetInfo.buildKey;
    }

    const FilePath localExecutable = ensureExeEnding(targetInfo.targetFilePath);
    if (localExecutable.isEmpty())
        return;

    QString buildBase;
    if (auto buildConfig = target->activeBuildConfiguration()) {
        buildBase = buildConfig->buildDirectory().toString();
        const QString projBase = project->projectDirectory().toString();
        if (m_projectFile.startsWith(projBase))
            m_buildDir = QFileInfo(buildBase + m_projectFile.mid(projBase.length())).absolutePath();
    }

    // deployment information should get taken into account, but it pretty much seems as if
    // each build system uses it differently
    const DeploymentData &deployData = target->deploymentData();
    const DeployableFile deploy = deployData.deployableForLocalFile(localExecutable);
    // we might have a deployable executable
    const FilePath deployedExecutable = ensureExeEnding((deploy.isValid() && deploy.isExecutable())
            ? FilePath::fromString(QDir::cleanPath(deploy.remoteFilePath())) : localExecutable);

    qCDebug(LOG) << " LocalExecutable" << localExecutable;
    qCDebug(LOG) << " DeployedExecutable" << deployedExecutable;
    qCDebug(LOG) << "Iterating run configurations";
    for (RunConfiguration *runConfig : target->runConfigurations()) {
        qCDebug(LOG) << "RunConfiguration" << runConfig->id();
        if (!isLocal(target)) { // TODO add device support
            qCDebug(LOG) << " Skipped as not being local";
            continue;
        }

        const Runnable runnable = runConfig->runnable();
        // not the best approach - but depending on the build system and whether the executables
        // are going to get installed or not we have to soften the condition...
        const FilePath currentExecutable = ensureExeEnding(runnable.executable);
        const QString currentBST = runConfig->buildKey();
        qCDebug(LOG) << " CurrentExecutable" << currentExecutable;
        qCDebug(LOG) << " BST of RunConfig" << currentBST;
        if ((localExecutable == currentExecutable)
                || (deployedExecutable == currentExecutable)
                || (buildSystemTargets.contains(currentBST))) {
            qCDebug(LOG) << "  Using this RunConfig.";
            m_origRunConfig = runConfig;
            m_runnable = runnable;
            m_runnable.executable = currentExecutable;
            m_displayName = runConfig->displayName();
            if (runMode == TestRunMode::Debug || runMode == TestRunMode::DebugWithoutDeploy)
                m_runConfig = new Internal::TestRunConfiguration(target, this);
            break;
        }
    }

    // RunConfiguration for this target could be explicitly removed or not created at all
    // or we might have end up using the (wrong) path of a locally installed executable
    // for this case try the original executable path of the BuildTargetInfo (the executable
    // before installation) to have at least something to execute
    if (!hasExecutable() && !localExecutable.isEmpty())
        m_runnable.executable = localExecutable;
    if (m_displayName.isEmpty() && hasExecutable()) {
        qCDebug(LOG) << "   Fallback";
        // we failed to find a valid runconfiguration - but we've got the executable already
        if (auto rc = target->activeRunConfiguration()) {
            if (isLocal(target)) { // FIXME for now only Desktop support
                const Runnable runnable = rc->runnable();
                m_runnable.environment = runnable.environment;
                m_deducedConfiguration = true;
                m_deducedFrom = rc->displayName();
                if (runMode == TestRunMode::Debug)
                    m_runConfig = new Internal::TestRunConfiguration(rc->target(), this);
            } else {
                qCDebug(LOG) << "not using the fallback as the current active run configuration "
                                "appears to be non-Desktop";
            }
        }
    }

    if (m_displayName.isEmpty()) // happens e.g. when deducing the TestConfiguration or error
        m_displayName = (*buildSystemTargets.begin());
}

/**
 * @brief sets the test cases for this test configuration.
 *
 * Watch out for special handling of test configurations, because this method also
 * updates the test case count to the current size of \a testCases.
 *
 * @param testCases list of names of the test functions / test cases
 */
void TestConfiguration::setTestCases(const QStringList &testCases)
{
    m_testCases.clear();
    m_testCases << testCases;
    m_testCaseCount = m_testCases.size();
}

void TestConfiguration::setTestCaseCount(int count)
{
    m_testCaseCount = count;
}

void TestConfiguration::setExecutableFile(const QString &executableFile)
{
    m_runnable.executable = Utils::FilePath::fromString(executableFile);
}

void TestConfiguration::setProjectFile(const QString &projectFile)
{
    m_projectFile = projectFile;
}

void TestConfiguration::setWorkingDirectory(const QString &workingDirectory)
{
    m_runnable.workingDirectory = workingDirectory;
}

void TestConfiguration::setBuildDirectory(const QString &buildDirectory)
{
    m_buildDir = buildDirectory;
}

void TestConfiguration::setDisplayName(const QString &displayName)
{
    m_displayName = displayName;
}

void TestConfiguration::setEnvironment(const Utils::Environment &env)
{
    m_runnable.environment = env;
}

void TestConfiguration::setProject(Project *project)
{
    m_project = project;
}

void TestConfiguration::setInternalTarget(const QString &target)
{
    m_buildTargets.clear();
    m_buildTargets.insert(target);
}

void TestConfiguration::setInternalTargets(const QSet<QString> &targets)
{
    m_buildTargets = targets;
}

void TestConfiguration::setOriginalRunConfiguration(RunConfiguration *runConfig)
{
    m_origRunConfig = runConfig;
}

QString TestConfiguration::executableFilePath() const
{
    if (!hasExecutable())
        return QString();

    QFileInfo commandFileInfo = m_runnable.executable.toFileInfo();
    if (commandFileInfo.isExecutable() && commandFileInfo.path() != ".") {
        return commandFileInfo.absoluteFilePath();
    } else if (commandFileInfo.path() == "."){
        QString fullCommandFileName = m_runnable.executable.toString();
        // TODO: check if we can use searchInPath() from Utils::Environment
        const QStringList &pathList = m_runnable.environment.toProcessEnvironment().value("PATH")
                .split(Utils::HostOsInfo::pathListSeparator());

        foreach (const QString &path, pathList) {
            QString filePath(path + QDir::separator() + fullCommandFileName);
            if (QFileInfo(filePath).isExecutable())
                return commandFileInfo.absoluteFilePath();
        }
    }
    return QString();
}

QString TestConfiguration::workingDirectory() const
{
    if (!m_runnable.workingDirectory.isEmpty()) {
        const QFileInfo info(m_runnable.workingDirectory);
        if (info.isDir()) // ensure wanted working dir does exist
            return info.absoluteFilePath();
    }

    const QString executable = executableFilePath();
    return executable.isEmpty() ? executable : QFileInfo(executable).absolutePath();
}

bool DebuggableTestConfiguration::isDebugRunMode() const
{
    return m_runMode == TestRunMode::Debug || m_runMode == TestRunMode::DebugWithoutDeploy;
}

bool TestConfiguration::hasExecutable() const
{
    return !m_runnable.executable.isEmpty();
}

ITestFramework *TestConfiguration::framework() const
{
    return m_framework;
}

} // namespace Autotest