cppmodelmanager_test.cpp 46.6 KB
Newer Older
1 2
/****************************************************************************
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
5 6 7 8 9 10 11
**
** 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
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15 16 17
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
27 28 29 30
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

31
#include "baseeditordocumentprocessor.h"
32
#include "builtineditordocumentparser.h"
33
#include "cppsourceprocessor.h"
34 35
#include "cpptoolsplugin.h"
#include "cpptoolstestcase.h"
36
#include "editordocumenthandle.h"
37 38
#include "modelmanagertesthelper.h"

39
#include <coreplugin/documentmanager.h>
40
#include <coreplugin/editormanager/editormanager.h>
41
#include <coreplugin/fileutils.h>
42
#include <coreplugin/testdatadir.h>
43 44
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
45 46

#include <cplusplus/LookupContext.h>
47
#include <utils/executeondestruction.h>
48
#include <utils/hostosinfo.h>
49

50
#include <QDebug>
51
#include <QtTest>
52

53 54 55 56
#define VERIFY_DOCUMENT_REVISION(document, expectedRevision) \
    QVERIFY(document); \
    QCOMPARE(document->revision(), expectedRevision);

57
using namespace CppTools;
58
using namespace CppTools::Internal;
59
using namespace CppTools::Tests;
hjk's avatar
hjk committed
60
using namespace ProjectExplorer;
61

62
typedef CPlusPlus::Document Document;
63

64
Q_DECLARE_METATYPE(QVector<ProjectFile>)
65

66 67
namespace {

68 69
inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }

70
class MyTestDataDir : public Core::Tests::TestDataDir
71
{
72
public:
73
    MyTestDataDir(const QString &dir)
74
        : TestDataDir(_(SRCDIR "/../../../tests/cppmodelmanager/") + dir)
75
    {}
76

77
    QString includeDir(bool cleaned = true) const
78
    { return directory(_("include"), cleaned); }
79 80

    QString frameworksDir(bool cleaned = true) const
81
    { return directory(_("frameworks"), cleaned); }
82 83

    QString fileFromSourcesDir(const QString &fileName) const
84
    { return directory(_("sources")) + QLatin1Char('/') + fileName; }
85 86
};

87 88 89 90 91 92 93 94 95
QStringList toAbsolutePaths(const QStringList &relativePathList,
                            const Tests::TemporaryCopiedDir &temporaryDir)
{
    QStringList result;
    foreach (const QString &file, relativePathList)
        result << temporaryDir.absolutePath(file.toUtf8());
    return result;
}

96 97 98 99 100 101 102 103 104
// TODO: When possible, use this helper class in all tests
class ProjectCreator
{
public:
    ProjectCreator(ModelManagerTestHelper *modelManagerTestHelper)
        : modelManagerTestHelper(modelManagerTestHelper)
    {}

    /// 'files' is expected to be a list of file names that reside in 'dir'.
105
    void create(const QString &name, const QString &dir, const QStringList &files)
106
    {
107
        const MyTestDataDir projectDir(dir);
108 109 110 111
        foreach (const QString &file, files)
            projectFiles << projectDir.file(file);

        Project *project = modelManagerTestHelper->createProject(name);
112
        projectInfo = ProjectInfo(project);
113 114

        ProjectPart::Ptr part(new ProjectPart);
115
        part->languageVersion = ProjectPart::CXX14;
116 117 118 119 120
        part->qtVersion = ProjectPart::Qt5;
        foreach (const QString &file, projectFiles) {
            ProjectFile projectFile(file, ProjectFile::classify(file));
            part->files.append(projectFile);
        }
121
        projectInfo.appendProjectPart(part);
122
        projectInfo.finish();
123 124 125 126 127 128 129
    }

    ModelManagerTestHelper *modelManagerTestHelper;
    ProjectInfo projectInfo;
    QStringList projectFiles;
};

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
/// Changes a file on the disk and restores its original contents on destruction
class FileChangerAndRestorer
{
public:
    FileChangerAndRestorer(const QString &filePath)
        : m_filePath(filePath)
    {
    }

    ~FileChangerAndRestorer()
    {
        restoreContents();
    }

    /// Saves the contents also internally so it can be restored on destruction
    bool readContents(QByteArray *contents)
    {
        Utils::FileReader fileReader;
        const bool isFetchOk = fileReader.fetch(m_filePath);
        if (isFetchOk) {
            m_originalFileContents = fileReader.data();
            if (contents)
                *contents = m_originalFileContents;
        }
        return isFetchOk;
    }

157
    bool writeContents(const QByteArray &contents) const
158
    {
159
        return TestCase::writeFile(m_filePath, contents);
160 161 162 163 164
    }

private:
    void restoreContents() const
    {
165
        TestCase::writeFile(m_filePath, m_originalFileContents);
166 167 168 169 170 171
    }

    QByteArray m_originalFileContents;
    const QString &m_filePath;
};

172
ProjectPart::Ptr projectPartOfEditorDocument(const QString &filePath)
173
{
174 175 176
    auto *editorDocument = CppModelManager::instance()->cppEditorDocument(filePath);
    QTC_ASSERT(editorDocument, return ProjectPart::Ptr());
    return editorDocument->processor()->parser()->projectPart();
177 178
}

179 180
} // anonymous namespace

181 182
/// Check: The preprocessor cleans include and framework paths.
void CppToolsPlugin::test_modelmanager_paths_are_clean()
183 184 185 186
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

187
    const MyTestDataDir testDataDir(_("testdata"));
188

189
    Project *project = helper.createProject(_("test_modelmanager_paths_are_clean"));
190
    ProjectInfo pi = ProjectInfo(project);
191

192
    typedef ProjectPartHeaderPath HeaderPath;
193

194
    ProjectPart::Ptr part(new ProjectPart);
195
    part->languageVersion = ProjectPart::CXX14;
196
    part->qtVersion = ProjectPart::Qt5;
197
    part->projectDefines = QByteArray("#define OH_BEHAVE -1\n");
198 199
    part->headerPaths = { HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath),
                          HeaderPath(testDataDir.frameworksDir(false), HeaderPath::FrameworkPath) };
200
    pi.appendProjectPart(part);
201
    pi.finish();
202 203 204

    mm->updateProjectInfo(pi);

205
    ProjectPartHeaderPaths headerPaths = mm->headerPaths();
206 207 208 209
    QCOMPARE(headerPaths.size(), 2);
    QVERIFY(headerPaths.contains(HeaderPath(testDataDir.includeDir(), HeaderPath::IncludePath)));
    QVERIFY(headerPaths.contains(HeaderPath(testDataDir.frameworksDir(),
                                            HeaderPath::FrameworkPath)));
210
}
211

212
/// Check: Frameworks headers are resolved.
213 214
void CppToolsPlugin::test_modelmanager_framework_headers()
{
215
    if (Utils::HostOsInfo::isWindowsHost())
216
        QSKIP("Can't resolve framework soft links on Windows.");
217

218 219 220
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

221
    const MyTestDataDir testDataDir(_("testdata"));
222

223
    Project *project = helper.createProject(_("test_modelmanager_framework_headers"));
224
    ProjectInfo pi = ProjectInfo(project);
225

226
    typedef ProjectPartHeaderPath HeaderPath;
227

228
    ProjectPart::Ptr part(new ProjectPart);
229
    part->languageVersion = ProjectPart::CXX14;
230
    part->qtVersion = ProjectPart::Qt5;
231
    part->projectDefines = QByteArray("#define OH_BEHAVE -1\n");
232 233
    part->headerPaths = { HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath),
                          HeaderPath(testDataDir.frameworksDir(false), HeaderPath::FrameworkPath) };
234
    const QString &source = testDataDir.fileFromSourcesDir(
235
        _("test_modelmanager_framework_headers.cpp"));
236
    part->files << ProjectFile(source, ProjectFile::CXXSource);
237
    pi.appendProjectPart(part);
238
    pi.finish();
239

240
    mm->updateProjectInfo(pi).waitForFinished();
241 242
    QCoreApplication::processEvents();

243
    QVERIFY(mm->snapshot().contains(source));
244
    Document::Ptr doc = mm->document(source);
245 246 247 248 249 250 251 252 253 254 255 256 257 258
    QVERIFY(!doc.isNull());
    CPlusPlus::Namespace *ns = doc->globalNamespace();
    QVERIFY(ns);
    QVERIFY(ns->memberCount() > 0);
    for (unsigned i = 0, ei = ns->memberCount(); i < ei; ++i) {
        CPlusPlus::Symbol *s = ns->memberAt(i);
        QVERIFY(s);
        QVERIFY(s->name());
        const CPlusPlus::Identifier *id = s->name()->asNameId();
        QVERIFY(id);
        QByteArray chars = id->chars();
        QVERIFY(chars.startsWith("success"));
    }
}
259 260

/// QTCREATORBUG-9056
261 262 263
/// Check: If the project configuration changes, all project files and their
///        includes have to be reparsed.
void CppToolsPlugin::test_modelmanager_refresh_also_includes_of_project_files()
264 265 266 267
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

268
    const MyTestDataDir testDataDir(_("testdata"));
269

270 271
    const QString testCpp(testDataDir.fileFromSourcesDir(_("test_modelmanager_refresh.cpp")));
    const QString testHeader(testDataDir.fileFromSourcesDir( _("test_modelmanager_refresh.h")));
272

273
    Project *project = helper.createProject(
274
                _("test_modelmanager_refresh_also_includes_of_project_files"));
275
    ProjectInfo pi = ProjectInfo(project);
276

277
    typedef ProjectPartHeaderPath HeaderPath;
278

279
    ProjectPart::Ptr part(new ProjectPart);
280
    part->languageVersion = ProjectPart::CXX14;
281
    part->qtVersion = ProjectPart::Qt5;
282
    part->projectDefines = QByteArray("#define OH_BEHAVE -1\n");
283
    part->headerPaths = { HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath) };
284
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
285
    pi.appendProjectPart(part);
286
    pi.finish();
287

288
    QSet<QString> refreshedFiles = helper.updateProjectInfo(pi);
289 290 291 292 293 294
    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testCpp));
    CPlusPlus::Snapshot snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader));
    QVERIFY(snapshot.contains(testCpp));

295 296 297 298
    Document::Ptr headerDocumentBefore = snapshot.document(testHeader);
    const QList<CPlusPlus::Macro> macrosInHeaderBefore = headerDocumentBefore->definedMacros();
    QCOMPARE(macrosInHeaderBefore.size(), 1);
    QVERIFY(macrosInHeaderBefore.first().name() == "test_modelmanager_refresh_h");
299

300
    // Introduce a define that will enable another define once the document is reparsed.
301
    part->projectDefines = QByteArray("#define TEST_DEFINE 1\n");
302
    pi = ProjectInfo(project);
303
    pi.appendProjectPart(part);
304
    pi.finish();
305

306
    refreshedFiles = helper.updateProjectInfo(pi);
307 308 309 310 311 312

    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testCpp));
    snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader));
    QVERIFY(snapshot.contains(testCpp));
313 314 315 316 317 318

    Document::Ptr headerDocumentAfter = snapshot.document(testHeader);
    const QList<CPlusPlus::Macro> macrosInHeaderAfter = headerDocumentAfter->definedMacros();
    QCOMPARE(macrosInHeaderAfter.size(), 2);
    QVERIFY(macrosInHeaderAfter.at(0).name() == "test_modelmanager_refresh_h");
    QVERIFY(macrosInHeaderAfter.at(1).name() == "TEST_DEFINE_DEFINED");
319
}
320 321

/// QTCREATORBUG-9205
322
/// Check: When reparsing the same files again, no errors occur
323
///        (The CppSourceProcessor's already seen files are properly cleared!).
324
void CppToolsPlugin::test_modelmanager_refresh_several_times()
325 326 327 328
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

329
    const MyTestDataDir testDataDir(_("testdata_refresh"));
330

331 332 333
    const QString testHeader1(testDataDir.file(_("defines.h")));
    const QString testHeader2(testDataDir.file(_("header.h")));
    const QString testCpp(testDataDir.file(_("source.cpp")));
334

335
    Project *project = helper.createProject(_("test_modelmanager_refresh_several_times"));
336
    ProjectInfo pi = ProjectInfo(project);
337 338

    ProjectPart::Ptr part(new ProjectPart);
339
    part->languageVersion = ProjectPart::CXX14;
340 341 342 343
    part->qtVersion = ProjectPart::Qt5;
    part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader));
    part->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader));
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
344
    pi.appendProjectPart(part);
345
    pi.finish();
346 347 348
    mm->updateProjectInfo(pi);

    CPlusPlus::Snapshot snapshot;
349
    QSet<QString> refreshedFiles;
350 351
    CPlusPlus::Document::Ptr document;

352
    QByteArray defines = "#define FIRST_DEFINE";
353
    for (int i = 0; i < 2; ++i) {
354
        pi = ProjectInfo(project);
355 356 357
        ProjectPart::Ptr part(new ProjectPart);
        // Simulate project configuration change by having different defines each time.
        defines += "\n#define ANOTHER_DEFINE";
358
        part->projectDefines = defines;
359
        part->languageVersion = ProjectPart::CXX14;
360 361 362 363 364
        part->qtVersion = ProjectPart::Qt5;
        part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader));
        part->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader));
        part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
        pi.appendProjectPart(part);
365
        pi.finish();
366

367
        refreshedFiles = helper.updateProjectInfo(pi);
368
        QCOMPARE(refreshedFiles.size(), 3);
369

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        QVERIFY(refreshedFiles.contains(testHeader1));
        QVERIFY(refreshedFiles.contains(testHeader2));
        QVERIFY(refreshedFiles.contains(testCpp));

        snapshot = mm->snapshot();
        QVERIFY(snapshot.contains(testHeader1));
        QVERIFY(snapshot.contains(testHeader2));
        QVERIFY(snapshot.contains(testCpp));

        // No diagnostic messages expected
        document = snapshot.document(testHeader1);
        QVERIFY(document->diagnosticMessages().isEmpty());

        document = snapshot.document(testHeader2);
        QVERIFY(document->diagnosticMessages().isEmpty());

        document = snapshot.document(testCpp);
        QVERIFY(document->diagnosticMessages().isEmpty());
    }
}
390

391 392 393 394 395 396 397
/// QTCREATORBUG-9581
/// Check: If nothing has changes, nothing should be reindexed.
void CppToolsPlugin::test_modelmanager_refresh_test_for_changes()
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

398 399
    const MyTestDataDir testDataDir(_("testdata_refresh"));
    const QString testCpp(testDataDir.file(_("source.cpp")));
400

401
    Project *project = helper.createProject(_("test_modelmanager_refresh_2"));
402
    ProjectInfo pi = ProjectInfo(project);
403 404

    ProjectPart::Ptr part(new ProjectPart);
405
    part->languageVersion = ProjectPart::CXX14;
406 407 408
    part->qtVersion = ProjectPart::Qt5;
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
    pi.appendProjectPart(part);
409
    pi.finish();
410 411

    // Reindexing triggers a reparsing thread
412
    helper.resetRefreshedSourceFiles();
413 414
    QFuture<void> firstFuture = mm->updateProjectInfo(pi);
    QVERIFY(firstFuture.isStarted() || firstFuture.isRunning());
415
    firstFuture.waitForFinished();
416
    const QSet<QString> refreshedFiles = helper.waitForRefreshedSourceFiles();
417 418 419 420 421 422 423 424
    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testCpp));

    // No reindexing since nothing has changed
    QFuture<void> subsequentFuture = mm->updateProjectInfo(pi);
    QVERIFY(subsequentFuture.isCanceled() && subsequentFuture.isFinished());
}

425 426 427 428 429 430 431
/// Check: (1) Added project files are recognized and parsed.
/// Check: (2) Removed project files are recognized and purged from the snapshot.
void CppToolsPlugin::test_modelmanager_refresh_added_and_purge_removed()
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

432
    const MyTestDataDir testDataDir(_("testdata_refresh"));
433

434 435 436
    const QString testHeader1(testDataDir.file(_("header.h")));
    const QString testHeader2(testDataDir.file(_("defines.h")));
    const QString testCpp(testDataDir.file(_("source.cpp")));
437

438
    Project *project = helper.createProject(_("test_modelmanager_refresh_3"));
439
    ProjectInfo pi = ProjectInfo(project);
440 441

    ProjectPart::Ptr part(new ProjectPart);
442
    part->languageVersion = ProjectPart::CXX14;
443 444 445 446
    part->qtVersion = ProjectPart::Qt5;
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
    part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader));
    pi.appendProjectPart(part);
447
    pi.finish();
448 449

    CPlusPlus::Snapshot snapshot;
450
    QSet<QString> refreshedFiles;
451

452
    refreshedFiles = helper.updateProjectInfo(pi);
453 454 455 456 457 458 459 460 461 462

    QCOMPARE(refreshedFiles.size(), 2);
    QVERIFY(refreshedFiles.contains(testHeader1));
    QVERIFY(refreshedFiles.contains(testCpp));

    snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader1));
    QVERIFY(snapshot.contains(testCpp));

    // Now add testHeader2 and remove testHeader1
463
    pi = ProjectInfo(project);
464
    ProjectPart::Ptr newPart(new ProjectPart);
465
    newPart->languageVersion = ProjectPart::CXX14;
466 467 468 469
    newPart->qtVersion = ProjectPart::Qt5;
    newPart->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
    newPart->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader));
    pi.appendProjectPart(newPart);
470
    pi.finish();
471

472
    refreshedFiles = helper.updateProjectInfo(pi);
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

    // Only the added project file was reparsed
    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testHeader2));

    snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader2));
    QVERIFY(snapshot.contains(testCpp));
    // The removed project file is not anymore in the snapshot
    QVERIFY(!snapshot.contains(testHeader1));
}

/// Check: Timestamp modified files are reparsed if project files are added or removed
///        while the project configuration stays the same
void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change()
{
    QFETCH(QString, fileToChange);
490 491 492 493 494 495 496 497
    QFETCH(QStringList, initialProjectFiles);
    QFETCH(QStringList, finalProjectFiles);

    Tests::TemporaryCopiedDir temporaryDir(
                MyTestDataDir(QLatin1String("testdata_refresh2")).path());
    fileToChange = temporaryDir.absolutePath(fileToChange.toUtf8());
    initialProjectFiles = toAbsolutePaths(initialProjectFiles, temporaryDir);
    finalProjectFiles = toAbsolutePaths(finalProjectFiles, temporaryDir);
498 499 500 501

    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

502
    Project *project = helper.createProject(_("test_modelmanager_refresh_timeStampModified"));
503
    ProjectInfo pi = ProjectInfo(project);
504 505

    ProjectPart::Ptr part(new ProjectPart);
506
    part->languageVersion = ProjectPart::CXX14;
507
    part->qtVersion = ProjectPart::Qt5;
508 509
    foreach (const QString &file, initialProjectFiles)
        part->files.append(ProjectFile(file, ProjectFile::CXXSource));
510
    pi = ProjectInfo(project);
511
    pi.appendProjectPart(part);
512
    pi.finish();
513 514 515

    Document::Ptr document;
    CPlusPlus::Snapshot snapshot;
516
    QSet<QString> refreshedFiles;
517

518
    refreshedFiles = helper.updateProjectInfo(pi);
519 520 521

    QCOMPARE(refreshedFiles.size(), initialProjectFiles.size());
    snapshot = mm->snapshot();
522 523 524
    foreach (const QString &file, initialProjectFiles) {
        QVERIFY(refreshedFiles.contains(file));
        QVERIFY(snapshot.contains(file));
525 526 527 528 529 530 531 532 533 534 535 536 537
    }

    document = snapshot.document(fileToChange);
    const QDateTime lastModifiedBefore = document->lastModified();
    QCOMPARE(document->globalSymbolCount(), 1U);
    QCOMPARE(document->globalSymbolAt(0)->name()->identifier()->chars(), "someGlobal");

    // Modify the file
    QTest::qSleep(1000); // Make sure the timestamp is different
    FileChangerAndRestorer fileChangerAndRestorer(fileToChange);
    QByteArray originalContents;
    QVERIFY(fileChangerAndRestorer.readContents(&originalContents));
    const QByteArray newFileContentes = originalContents + "\nint addedOtherGlobal;";
538
    QVERIFY(fileChangerAndRestorer.writeContents(newFileContentes));
539 540 541

    // Add or remove source file. The configuration stays the same.
    part->files.clear();
542 543
    foreach (const QString &file, finalProjectFiles)
        part->files.append(ProjectFile(file, ProjectFile::CXXSource));
544
    pi = ProjectInfo(project);
545
    pi.appendProjectPart(part);
546
    pi.finish();
547

548
    refreshedFiles = helper.updateProjectInfo(pi);
549 550 551

    QCOMPARE(refreshedFiles.size(), finalProjectFiles.size());
    snapshot = mm->snapshot();
552 553 554
    foreach (const QString &file, finalProjectFiles) {
        QVERIFY(refreshedFiles.contains(file));
        QVERIFY(snapshot.contains(file));
555 556 557 558 559 560 561 562 563 564 565 566
    }
    document = snapshot.document(fileToChange);
    const QDateTime lastModifiedAfter = document->lastModified();
    QVERIFY(lastModifiedAfter > lastModifiedBefore);
    QCOMPARE(document->globalSymbolCount(), 2U);
    QCOMPARE(document->globalSymbolAt(0)->name()->identifier()->chars(), "someGlobal");
    QCOMPARE(document->globalSymbolAt(1)->name()->identifier()->chars(), "addedOtherGlobal");
}

void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change_data()
{
    QTest::addColumn<QString>("fileToChange");
567 568
    QTest::addColumn<QStringList>("initialProjectFiles");
    QTest::addColumn<QStringList>("finalProjectFiles");
569

570 571
    const QString testCpp = QLatin1String("source.cpp");
    const QString testCpp2 = QLatin1String("source2.cpp");
572 573

    const QString fileToChange = testCpp;
574 575
    const QStringList projectFiles1 = QStringList() << testCpp;
    const QStringList projectFiles2 = QStringList() << testCpp << testCpp2;
576 577 578 579 580 581 582 583

    // Add a file
    QTest::newRow("case: add project file") << fileToChange << projectFiles1 << projectFiles2;

    // Remove a file
    QTest::newRow("case: remove project file") << fileToChange << projectFiles2 << projectFiles1;
}

584 585
/// Check: If a second project is opened, the code model is still aware of
///        files of the first project.
586 587
void CppToolsPlugin::test_modelmanager_snapshot_after_two_projects()
{
588
    QSet<QString> refreshedFiles;
589 590 591 592 593 594
    ModelManagerTestHelper helper;
    ProjectCreator project1(&helper);
    ProjectCreator project2(&helper);
    CppModelManager *mm = CppModelManager::instance();

    // Project 1
595 596 597 598 599
    project1.create(_("test_modelmanager_snapshot_after_two_projects.1"),
                    _("testdata_project1"),
                    QStringList() << _("foo.h")
                                  << _("foo.cpp")
                                  << _("main.cpp"));
600

601
    refreshedFiles = helper.updateProjectInfo(project1.projectInfo);
602
    QCOMPARE(refreshedFiles, project1.projectFiles.toSet());
603 604 605 606 607 608
    const int snapshotSizeAfterProject1 = mm->snapshot().size();

    foreach (const QString &file, project1.projectFiles)
        QVERIFY(mm->snapshot().contains(file));

    // Project 2
609 610 611 612 613
    project2.create(_("test_modelmanager_snapshot_after_two_projects.2"),
                    _("testdata_project2"),
                    QStringList() << _("bar.h")
                                  << _("bar.cpp")
                                  << _("main.cpp"));
614

615
    refreshedFiles = helper.updateProjectInfo(project2.projectInfo);
616
    QCOMPARE(refreshedFiles, project2.projectFiles.toSet());
617 618 619 620 621 622 623 624 625 626

    const int snapshotSizeAfterProject2 = mm->snapshot().size();
    QVERIFY(snapshotSizeAfterProject2 > snapshotSizeAfterProject1);
    QVERIFY(snapshotSizeAfterProject2 >= snapshotSizeAfterProject1 + project2.projectFiles.size());

    foreach (const QString &file, project1.projectFiles)
        QVERIFY(mm->snapshot().contains(file));
    foreach (const QString &file, project2.projectFiles)
        QVERIFY(mm->snapshot().contains(file));
}
627

628 629
/// Check: (1) For a project with a *.ui file an AbstractEditorSupport object
///            is added for the ui_* file.
630
/// Check: (2) The CppSourceProcessor can successfully resolve the ui_* file
631
///            though it might not be actually generated in the build dir.
632 633
///

634 635
void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
{
636
    VerifyCleanCppModelManager verify;
637

638 639 640
    TemporaryCopiedDir temporaryDir(MyTestDataDir(QLatin1String("testdata_guiproject1")).path());
    QVERIFY(temporaryDir.isValid());
    const QString projectFile = temporaryDir.absolutePath("testdata_guiproject1.pro");
641

642
    ProjectOpenerAndCloser projects;
643 644
    ProjectInfo projectInfo = projects.open(projectFile, /*configureAsExampleProject=*/ true);
    QVERIFY(projectInfo.isValid());
645 646 647

    // Check working copy.
    // An AbstractEditorSupport object should have been added for the ui_* file.
648
    CppModelManager *mm = CppModelManager::instance();
649
    WorkingCopy workingCopy = mm->workingCopy();
650 651 652 653

    QCOMPARE(workingCopy.size(), 2); // mm->configurationFileName() and "ui_*.h"

    QStringList fileNamesInWorkinCopy;
654
    QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
655 656
    while (it.hasNext()) {
        it.next();
657
        fileNamesInWorkinCopy << Utils::FileName::fromString(it.key().toString()).fileName();
658 659
    }
    fileNamesInWorkinCopy.sort();
660
    const QString expectedUiHeaderFileName = _("ui_mainwindow.h");
661 662 663
    QCOMPARE(fileNamesInWorkinCopy.at(0), mm->configurationFileName());
    QCOMPARE(fileNamesInWorkinCopy.at(1), expectedUiHeaderFileName);

664 665
    // Check CppSourceProcessor / includes.
    // The CppSourceProcessor is expected to find the ui_* file in the working copy.
666
    const QString fileIncludingTheUiFile = temporaryDir.absolutePath("mainwindow.cpp");
667 668 669 670 671 672 673 674
    while (!mm->snapshot().document(fileIncludingTheUiFile))
        QCoreApplication::processEvents();

    const CPlusPlus::Snapshot snapshot = mm->snapshot();
    const Document::Ptr document = snapshot.document(fileIncludingTheUiFile);
    QVERIFY(document);
    const QStringList includedFiles = document->includedFiles();
    QCOMPARE(includedFiles.size(), 2);
675 676
    QCOMPARE(Utils::FileName::fromString(includedFiles.at(0)).fileName(), _("mainwindow.h"));
    QCOMPARE(Utils::FileName::fromString(includedFiles.at(1)).fileName(), _("ui_mainwindow.h"));
677
}
678 679 680 681 682

/// QTCREATORBUG-9828: Locator shows symbols of closed files
/// Check: The garbage collector should be run if the last CppEditor is closed.
void CppToolsPlugin::test_modelmanager_gc_if_last_cppeditor_closed()
{
683 684
    ModelManagerTestHelper helper;

685 686
    MyTestDataDir testDataDirectory(_("testdata_guiproject1"));
    const QString file = testDataDirectory.file(_("main.cpp"));
687 688

    CppModelManager *mm = CppModelManager::instance();
689
    helper.resetRefreshedSourceFiles();
690 691

    // Open a file in the editor
hjk's avatar
hjk committed
692
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
693
    Core::IEditor *editor = Core::EditorManager::openEditor(file);
694
    QVERIFY(editor);
hjk's avatar
hjk committed
695
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
696 697 698
    QVERIFY(mm->isCppEditor(editor));
    QVERIFY(mm->workingCopy().contains(file));

699 700
    // Wait until the file is refreshed
    helper.waitForRefreshedSourceFiles();
701 702

    // Close file/editor
703
    Core::EditorManager::closeDocument(editor->document(), /*askAboutModifiedEditors=*/ false);
704
    helper.waitForFinishedGc();
705 706 707 708 709

    // Check: File is removed from the snapshpt
    QVERIFY(!mm->workingCopy().contains(file));
    QVERIFY(!mm->snapshot().contains(file));
}
710 711 712 713 714 715

/// Check: Files that are open in the editor are not garbage collected.
void CppToolsPlugin::test_modelmanager_dont_gc_opened_files()
{
    ModelManagerTestHelper helper;

716 717
    MyTestDataDir testDataDirectory(_("testdata_guiproject1"));
    const QString file = testDataDirectory.file(_("main.cpp"));
718 719

    CppModelManager *mm = CppModelManager::instance();
720
    helper.resetRefreshedSourceFiles();
721 722

    // Open a file in the editor
hjk's avatar
hjk committed
723
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
724
    Core::IEditor *editor = Core::EditorManager::openEditor(file);
725
    QVERIFY(editor);
hjk's avatar
hjk committed
726
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
727 728
    QVERIFY(mm->isCppEditor(editor));

729 730
    // Wait until the file is refreshed and check whether it is in the working copy
    helper.waitForRefreshedSourceFiles();
731

732 733 734 735 736 737 738 739 740 741
    QVERIFY(mm->workingCopy().contains(file));

    // Run the garbage collector
    mm->GC();

    // Check: File is still there
    QVERIFY(mm->workingCopy().contains(file));
    QVERIFY(mm->snapshot().contains(file));

    // Close editor
742
    Core::EditorManager::closeDocument(editor->document());
743 744 745
    helper.waitForFinishedGc();
    QVERIFY(mm->snapshot().isEmpty());
}
746 747 748 749 750 751 752

namespace {
struct EditorCloser {
    Core::IEditor *editor;
    EditorCloser(Core::IEditor *editor): editor(editor) {}
    ~EditorCloser()
    {
753
        using namespace CppTools;
754
        if (editor)
755
            QVERIFY(Tests::TestCase::closeEditorWithoutGarbageCollectorInvocation(editor));
756 757
    }
};
758 759 760 761 762 763 764 765

QString nameOfFirstDeclaration(const Document::Ptr &doc)
{
    if (doc && doc->globalNamespace()) {
        if (CPlusPlus::Symbol *s = doc->globalSymbolAt(0)) {
            if (CPlusPlus::Declaration *decl = s->asDeclaration()) {
                if (const CPlusPlus::Name *name = decl->name()) {
                    if (const CPlusPlus::Identifier *identifier = name->identifier())
766
                        return QString::fromUtf8(identifier->chars(), identifier->size());
767 768 769 770 771 772
                }
            }
        }
    }
    return QString();
}
773 774 775 776 777 778
}

void CppToolsPlugin::test_modelmanager_defines_per_project()
{
    ModelManagerTestHelper helper;

779 780 781 782
    MyTestDataDir testDataDirectory(_("testdata_defines"));
    const QString main1File = testDataDirectory.file(_("main1.cpp"));
    const QString main2File = testDataDirectory.file(_("main2.cpp"));
    const QString header = testDataDirectory.file(_("header.h"));
783 784 785

    CppModelManager *mm = CppModelManager::instance();

786
    Project *project = helper.createProject(_("test_modelmanager_defines_per_project"));
787

788
    typedef ProjectPartHeaderPath HeaderPath;
789

790
    ProjectPart::Ptr part1(new ProjectPart);
791
    part1->projectFile = QLatin1String("project1.projectfile");
792 793
    part1->files.append(ProjectFile(main1File, ProjectFile::CXXSource));
    part1->files.append(ProjectFile(header, ProjectFile::CXXHeader));
794
    part1->languageVersion = ProjectPart::CXX11;
795
    part1->qtVersion = ProjectPart::NoQt;
796
    part1->projectDefines = QByteArray("#define SUB1\n");
797
    part1->headerPaths = { HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath) };
798 799

    ProjectPart::Ptr part2(new ProjectPart);
800
    part2->projectFile = QLatin1String("project1.projectfile");
801 802
    part2->files.append(ProjectFile(main2File, ProjectFile::CXXSource));
    part2->files.append(ProjectFile(header, ProjectFile::CXXHeader));
803
    part2->languageVersion = ProjectPart::CXX11;
804
    part2->qtVersion = ProjectPart::NoQt;
805
    part2->projectDefines = QByteArray("#define SUB2\n");
806
    part2->headerPaths = { HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath) };
807

808
    ProjectInfo pi = ProjectInfo(project);
809 810
    pi.appendProjectPart(part1);
    pi.appendProjectPart(part2);
811
    pi.finish();
812

813
    helper.updateProjectInfo(pi);
814 815 816
    QCOMPARE(mm->snapshot().size(), 4);

    // Open a file in the editor
hjk's avatar
hjk committed
817
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
818

819 820 821 822 823 824 825 826 827 828 829 830 831
    struct Data {
        QString firstDeclarationName;
        QString fileName;
    } d[] = {
        { _("one"), main1File },
        { _("two"), main2File }
    };
    const int size = sizeof(d) / sizeof(d[0]);
    for (int i = 0; i < size; ++i) {
        const QString firstDeclarationName = d[i].firstDeclarationName;
        const QString fileName = d[i].fileName;

        Core::IEditor *editor = Core::EditorManager::openEditor(fileName);
832 833
        EditorCloser closer(editor);
        QVERIFY(editor);
hjk's avatar
hjk committed
834
        QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
835 836
        QVERIFY(mm->isCppEditor(editor));

837
        Document::Ptr doc = mm->document(fileName);
838
        QCOMPARE(nameOfFirstDeclaration(doc), firstDeclarationName);
839 840
    }
}
841

842
void CppToolsPlugin::test_modelmanager_precompiled_headers()
843 844 845
{
    ModelManagerTestHelper helper;

846 847 848 849 850 851
    MyTestDataDir testDataDirectory(_("testdata_defines"));
    const QString main1File = testDataDirectory.file(_("main1.cpp"));
    const QString main2File = testDataDirectory.file(_("main2.cpp"));
    const QString header = testDataDirectory.file(_("header.h"));
    const QString pch1File = testDataDirectory.file(_("pch1.h"));
    const QString pch2File = testDataDirectory.file(_("pch2.h"));
852 853 854

    CppModelManager *mm = CppModelManager::instance();

855
    Project *project = helper.createProject(_("test_modelmanager_defines_per_project_pch"));
856

857
    typedef ProjectPartHeaderPath HeaderPath;
858

859
    ProjectPart::Ptr part1(new ProjectPart);
860
    part1->projectFile = QLatin1String("project1.projectfile");
861 862
    part1->files.append(ProjectFile(main1File, ProjectFile::CXXSource));
    part1->files.append(ProjectFile(header, ProjectFile::CXXHeader));
Erik Verbruggen's avatar