summaryrefslogtreecommitdiff
path: root/src/plugins/clangcodemodel/test/clangcodecompletion_test.cpp
blob: 368d209e154965205de72d271c3be971b971ad22 (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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
/****************************************************************************
**
** 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 "clangcodecompletion_test.h"

#include "clangautomationutils.h"
#include "../clangbackendipcintegration.h"
#include "../clangcompletionassistinterface.h"
#include "../clangmodelmanagersupport.h"

#include <clangcodemodel/clangeditordocumentprocessor.h>

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icore.h>
#include <cpptools/cpptoolsreuse.h>
#include <cpptools/cpptoolstestcase.h>
#include <cpptools/modelmanagertesthelper.h>
#include <cpptools/projectinfo.h>
#include <texteditor/codeassist/assistproposalitem.h>
#include <texteditor/codeassist/genericproposalmodel.h>
#include <texteditor/textdocument.h>
#include <texteditor/texteditor.h>

#include <clangbackendipc/clangcodemodelservermessages.h>

#include <utils/changeset.h>
#include <utils/qtcassert.h>

#include <QDebug>
#include <QtTest>

using namespace ClangBackEnd;
using namespace ClangCodeModel;
using namespace ClangCodeModel::Internal;

namespace {

QString _(const char text[])
{ return QString::fromUtf8(text); }

QString qrcPath(const QByteArray relativeFilePath)
{ return QLatin1String(":/unittests/ClangCodeModel/") + QString::fromUtf8(relativeFilePath); }

QString fileName(const QString &filePath)
{ return QFileInfo(filePath).fileName(); }

CppTools::Tests::TemporaryDir *globalTemporaryDir()
{
    static CppTools::Tests::TemporaryDir dir;
    QTC_CHECK(dir.isValid());
    return &dir;
}

struct LogOutput
{
    LogOutput(const QString &text) : text(text.toUtf8()) {}
    LogOutput(const char text[]) : text(text) {}
    QByteArray text;
};

void printRawLines(QTextStream &out, const QList<QByteArray> &lines)
{
    foreach (const QByteArray &line, lines) {
        QByteArray rawLine = line;
        rawLine.prepend("\"");
        rawLine.append("\\n\"\n");
        out << rawLine;
    }
}

void printDifference(const LogOutput &actual, const LogOutput &expected)
{
    QTextStream out(stderr);

    const QList<QByteArray> actualLines = actual.text.split('\n');
    const QList<QByteArray> expectedLines = expected.text.split('\n');

    out << "-- ACTUAL:\n";
    printRawLines(out, actualLines);
    out << "-- EXPECTED:\n";
    printRawLines(out, expectedLines);

    if (actualLines.size() != expectedLines.size()) {
        out << "-- DIFFERENCE IN LINE COUNT:\n"
            << "    actual lines:" << actualLines.size() << '\n'
            << "  expected lines:" << expectedLines.size() << '\n';
    }

    out << "-- FIRST LINE THAT DIFFERS:\n";
    auto actualLineIt = actualLines.cbegin();
    auto expectedLineIt = expectedLines.cbegin();
    int line = 1;
    forever {
        if (actualLineIt == actualLines.cend() && expectedLineIt != expectedLines.cend()) {
            out << "      line: " << line << '\n';
            out << "    actual: <none>\n";
            out << "  expected: \"" << *expectedLineIt << "\"\n";
        } else if (actualLineIt != actualLines.cend() && expectedLineIt == expectedLines.cend()) {
            out << "      line: " << line << '\n';
            out << "    actual: \"" << *actualLineIt << "\"\n";
            out << "  expected: <none>\n";
        } else {
            if (*actualLineIt != *expectedLineIt) {
                out << "      line: " << line << '\n';
                out << "    actual: \"" << *actualLineIt << "\"\n";
                out << "  expected: \"" << *expectedLineIt << "\"\n";
                return;
            }
        }

        ++line;
        ++actualLineIt;
        ++expectedLineIt;
    }
}

bool compare(const LogOutput &actual, const LogOutput &expected)
{
    const bool isEqual = actual.text == expected.text;
    if (!isEqual)
        printDifference(actual, expected);
    return isEqual;
}

QByteArray readFile(const QString &filePath)
{
    QFile file(filePath);
    QTC_ASSERT(file.open(QFile::ReadOnly | QFile::Text), return QByteArray());
    return file.readAll();
}

bool writeFile(const QString &filePath, const QByteArray &contents)
{
    QFile file(filePath);
    if (!file.open(QFile::WriteOnly | QFile::Text))
        return false;
    if (file.write(contents) != contents.size())
        return false;
    return true;
}

void insertTextAtTopOfEditor(TextEditor::BaseTextEditor *editor, const QByteArray &text)
{
    QTC_ASSERT(editor, return);
    ::Utils::ChangeSet cs;
    cs.insert(0, QString::fromUtf8(text));
    QTextCursor textCursor = editor->textCursor();
    cs.apply(&textCursor);
}

class ChangeDocumentReloadSetting
{
public:
    ChangeDocumentReloadSetting(Core::IDocument::ReloadSetting reloadSetting)
        : m_previousValue(Core::EditorManager::reloadSetting())
    {
        Core::EditorManager::setReloadSetting(reloadSetting);
    }

    ~ChangeDocumentReloadSetting()
    {
        Core::EditorManager::setReloadSetting(m_previousValue);
    }

private:
   Core::IDocument::ReloadSetting m_previousValue;
};

class ChangeIpcSender
{
public:
    ChangeIpcSender(IpcSenderInterface *ipcSender)
    {
        auto &ipc = ModelManagerSupportClang::instance()->ipcCommunicator();
        m_previousSender = ipc.setIpcSender(ipcSender);
    }

    ~ChangeIpcSender()
    {
        auto &ipc = ModelManagerSupportClang::instance()->ipcCommunicator();
        ipc.setIpcSender(m_previousSender);
    }

private:
    IpcSenderInterface *m_previousSender;
};

QString toString(const FileContainer &fileContainer)
{
    QString out;
    QTextStream ts(&out);
    ts << "  Path: " << fileName(fileContainer.filePath().toString())
       << " ProjectPart: " << fileName(fileContainer.projectPartId().toString()) << "\n";
    return out;
}

QString toString(const QVector<FileContainer> &fileContainers)
{
    QString out;
    QTextStream ts(&out);
    foreach (const FileContainer &fileContainer, fileContainers)
        ts << toString(fileContainer);
    return out;
}

QString toString(const ProjectPartContainer &projectPartContainer)
{
    QString out;
    QTextStream ts(&out);
    ts << "  ProjectPartContainer"
       << " id: " << fileName(projectPartContainer.projectPartId().toString());
    return out;
}

QString toString(const QVector<ProjectPartContainer> &projectPartContainers)
{
    QString out;
    QTextStream ts(&out);
    foreach (const ProjectPartContainer &projectPartContainer, projectPartContainers)
        ts << toString(projectPartContainer);
    return out;
}

QString toString(const EndMessage &)
{
    return QLatin1String("EndMessage\n");
}

QString toString(const RegisterTranslationUnitForEditorMessage &message)
{
    QString out;
    QTextStream ts(&out);

    ts << "RegisterTranslationUnitForEditorMessage\n"
       << toString(message.fileContainers());
    return out;
}

QString toString(const UpdateTranslationUnitsForEditorMessage &message)
{
    QString out;
    QTextStream ts(&out);

    ts << "UpdateTranslationUnitForEditorMessage\n"
       << toString(message.fileContainers());
    return out;
}

QString toString(const UnregisterTranslationUnitsForEditorMessage &)
{
    return QLatin1String("UnregisterTranslationUnitsForEditorMessage\n");
}

QString toString(const RegisterProjectPartsForEditorMessage &message)
{
    QString out;
    QTextStream ts(&out);

    ts << "RegisterProjectPartsForEditorMessage\n"
       << toString(message.projectContainers()) << "\n";
    return out;
}

QString toString(const UnregisterProjectPartsForEditorMessage &message)
{
    QString out;
    QTextStream ts(&out);

    ts << "UnregisterProjectPartsForEditorMessage\n"
       << message.projectPartIds().join(Utf8String::fromUtf8(",")).toByteArray() << "\n";
    return out;
}

QString toString(const RegisterUnsavedFilesForEditorMessage &message)
{
    QString out;
    QTextStream ts(&out);

    ts << "RegisterUnsavedFilesForEditorMessage\n"
       << toString(message.fileContainers());
    return out;
}

QString toString(const UnregisterUnsavedFilesForEditorMessage &)
{
    return QLatin1String("UnregisterUnsavedFilesForEditorMessage\n");
}

QString toString(const CompleteCodeMessage &)
{
    return QLatin1String("CompleteCodeMessage\n");
}

QString toString(const RequestDocumentAnnotationsMessage &)
{
    return QStringLiteral("RequestDocumentAnnotationsMessage\n");
}

QString toString(const RequestReferencesMessage &)
{
    return QStringLiteral("RequestReferencesMessage\n");
}

QString toString(const UpdateVisibleTranslationUnitsMessage &)
{
    return QStringLiteral("UpdateVisibleTranslationUnitsMessage\n");
}

class IpcSenderSpy : public IpcSenderInterface
{
public:
    void end() override
    { senderLog.append(toString(EndMessage())); }

    void registerTranslationUnitsForEditor(const RegisterTranslationUnitForEditorMessage &message) override
    { senderLog.append(toString(message)); }

    void updateTranslationUnitsForEditor(const UpdateTranslationUnitsForEditorMessage &message) override
    { senderLog.append(toString(message)); }

    void unregisterTranslationUnitsForEditor(const UnregisterTranslationUnitsForEditorMessage &message) override
    { senderLog.append(toString(message)); }

    void registerProjectPartsForEditor(const RegisterProjectPartsForEditorMessage &message) override
    { senderLog.append(toString(message)); }

    void unregisterProjectPartsForEditor(const UnregisterProjectPartsForEditorMessage &message) override
    { senderLog.append(toString(message)); }

    void registerUnsavedFilesForEditor(const RegisterUnsavedFilesForEditorMessage &message) override
    { senderLog.append(toString(message)); }

    void unregisterUnsavedFilesForEditor(const UnregisterUnsavedFilesForEditorMessage &message) override
    { senderLog.append(toString(message)); }

    void completeCode(const CompleteCodeMessage &message) override
    { senderLog.append(toString(message)); }

    void requestDocumentAnnotations(const RequestDocumentAnnotationsMessage &message) override
    { senderLog.append(toString(message)); }

    void requestReferences(const RequestReferencesMessage &message) override
    { senderLog.append(toString(message)); }

    void updateVisibleTranslationUnits(const UpdateVisibleTranslationUnitsMessage &message) override
    { senderLog.append(toString(message)); }

public:
    QString senderLog;
};

class TestDocument
{
public:
    TestDocument(const QByteArray &fileName, CppTools::Tests::TemporaryDir *temporaryDir = 0)
        : cursorPosition(-1)
    {
        QTC_ASSERT(!fileName.isEmpty(), return);
        const QResource resource(qrcPath(fileName));
        QTC_ASSERT(resource.isValid(), return);
        const QByteArray contents = QByteArray(reinterpret_cast<const char*>(resource.data()),
                                               resource.size());
        cursorPosition = findCursorMarkerPosition(contents);
        if (!contents.isEmpty()) {
            if (!temporaryDir) {
                m_temporaryDir.reset(new CppTools::Tests::TemporaryDir);
                temporaryDir = m_temporaryDir.data();
            }

            filePath = temporaryDir->createFile(fileName, contents);
        }
    }

    static TestDocument fromExistingFile(const QString &filePath)
    {
        TestDocument testDocument;
        QTC_ASSERT(!filePath.isEmpty(), return testDocument);
        testDocument.filePath = filePath;
        testDocument.cursorPosition = findCursorMarkerPosition(readFile(filePath));
        return testDocument;
    }

    static int findCursorMarkerPosition(const QByteArray &contents)
    {
        return contents.indexOf(" /* COMPLETE HERE */");
    }

    bool isCreated() const { return !filePath.isEmpty(); }
    bool hasValidCursorPosition() const { return cursorPosition >= 0; }
    bool isCreatedAndHasValidCursorPosition() const
    { return isCreated() && hasValidCursorPosition(); }

    QString filePath;
    int cursorPosition;

private:
    TestDocument() : cursorPosition(-1) {}
    QSharedPointer<CppTools::Tests::TemporaryDir> m_temporaryDir;
};

class OpenEditorAtCursorPosition
{
public:
    OpenEditorAtCursorPosition(const TestDocument &testDocument);
    ~OpenEditorAtCursorPosition(); // Close editor

    bool succeeded() const { return m_editor && m_backendIsNotified; }
    bool waitUntilBackendIsNotified(int timeout = 10000);
    bool waitUntilProjectPartChanged(const QString &newProjectPartId, int timeout = 10000);
    bool waitUntil(const std::function<bool()> &condition, int timeout);
    TextEditor::BaseTextEditor *editor() const { return m_editor; }

private:
    TextEditor::BaseTextEditor *m_editor;
    bool m_backendIsNotified = false;
};

OpenEditorAtCursorPosition::OpenEditorAtCursorPosition(const TestDocument &testDocument)
{
    Core::IEditor *coreEditor = Core::EditorManager::openEditor(testDocument.filePath);
    m_editor = qobject_cast<TextEditor::BaseTextEditor *>(coreEditor);
    QTC_CHECK(m_editor);
    if (m_editor && testDocument.hasValidCursorPosition())
        m_editor->setCursorPosition(testDocument.cursorPosition);
    m_backendIsNotified = waitUntilBackendIsNotified();
    QTC_CHECK(m_backendIsNotified);
}

OpenEditorAtCursorPosition::~OpenEditorAtCursorPosition()
{
    if (m_editor)
        Core::EditorManager::closeEditor(m_editor, /* askAboutModifiedEditors= */ false);
}



bool OpenEditorAtCursorPosition::waitUntilBackendIsNotified(int timeout)
{
    const QString filePath = m_editor->document()->filePath().toString();

    auto condition = [filePath] () {
        const auto *processor = ClangEditorDocumentProcessor::get(filePath);
        return processor && processor->projectPart();
    };

    return waitUntil(condition, timeout);
}

bool OpenEditorAtCursorPosition::waitUntilProjectPartChanged(const QString &newProjectPartId,
                                                             int timeout)
{
    const QString filePath = m_editor->document()->filePath().toString();

    auto condition = [newProjectPartId, filePath] () {
        const auto *processor = ClangEditorDocumentProcessor::get(filePath);
        return processor
            && processor->projectPart()
            && processor->projectPart()->id() == newProjectPartId;
    };

    return waitUntil(condition, timeout);
}

bool OpenEditorAtCursorPosition::waitUntil(const std::function<bool ()> &condition, int timeout)
{
    QTime time;
    time.start();

    forever {
        if (time.elapsed() > timeout)
            return false;

        if (condition())
            return true;

        QCoreApplication::processEvents();
        QThread::msleep(20);
    }

    return false;
}

CppTools::ProjectPart::Ptr createProjectPart(const QStringList &files,
                                             const QString &defines)
{
    using namespace CppTools;

    ProjectPart::Ptr projectPart(new ProjectPart);
    projectPart->projectFile = QLatin1String("myproject.project");
    foreach (const QString &file, files)
        projectPart->files.append(ProjectFile(file, ProjectFile::classify(file)));
    projectPart->qtVersion = ProjectPart::NoQt;
    projectPart->projectDefines = defines.toUtf8();

    return projectPart;
}

CppTools::ProjectInfo createProjectInfo(ProjectExplorer::Project *project,
                                        const QStringList &files,
                                        const QString &defines)
{
    using namespace CppTools;
    QTC_ASSERT(project, return ProjectInfo());

    const CppTools::ProjectPart::Ptr projectPart = createProjectPart(files, defines);
    ProjectInfo projectInfo = ProjectInfo(project);
    projectInfo.appendProjectPart(projectPart);
    return projectInfo;
}

class ProjectLoader
{
public:
    ProjectLoader(const QStringList &projectFiles,
                  const QString &projectDefines,
                  bool testOnlyForCleanedProjects = false)
        : m_project(0)
        , m_projectFiles(projectFiles)
        , m_projectDefines(projectDefines)
        , m_helper(0, testOnlyForCleanedProjects)
    {
    }

    bool load()
    {
        m_project = m_helper.createProject(QLatin1String("testProject"));
        const CppTools::ProjectInfo projectInfo = createProjectInfo(m_project,
                                                                    m_projectFiles,
                                                                    m_projectDefines);
        const QSet<QString> filesIndexedAfterLoading = m_helper.updateProjectInfo(projectInfo);
        return m_projectFiles.size() == filesIndexedAfterLoading.size();
    }

    bool updateProject(const QString &updatedProjectDefines)
    {
        QTC_ASSERT(m_project, return false);
        const CppTools::ProjectInfo updatedProjectInfo = createProjectInfo(m_project,
                                                                           m_projectFiles,
                                                                           updatedProjectDefines);
        return updateProjectInfo(updatedProjectInfo);

    }

private:
    bool updateProjectInfo(const CppTools::ProjectInfo &projectInfo)
    {
        const QSet<QString> filesIndexedAfterLoading = m_helper.updateProjectInfo(projectInfo);
        return m_projectFiles.size() == filesIndexedAfterLoading.size();
    }

    ProjectExplorer::Project *m_project;
    QStringList m_projectFiles;
    QString m_projectDefines;
    CppTools::Tests::ModelManagerTestHelper m_helper;
};

class ProjectLessCompletionTest
{
public:
    ProjectLessCompletionTest(const QByteArray &testFileName,
                              const QString &textToInsert = QString(),
                              const QStringList &includePaths = QStringList())
    {
        CppTools::Tests::TestCase garbageCollectionGlobalSnapshot;
        QVERIFY(garbageCollectionGlobalSnapshot.succeededSoFar());

        const TestDocument testDocument(testFileName, globalTemporaryDir());
        QVERIFY(testDocument.isCreatedAndHasValidCursorPosition());
        OpenEditorAtCursorPosition openEditor(testDocument);
        QVERIFY(openEditor.succeeded());

        if (!textToInsert.isEmpty())
            openEditor.editor()->insert(textToInsert);

        proposal = completionResults(openEditor.editor(), includePaths, 15000);
    }

    ProposalModel proposal;
};

int indexOfItemWithText(ProposalModel model, const QByteArray &text)
{
    if (!model)
        return -1;

    for (int i = 0, size = model->size(); i < size; ++i) {
        const QString itemText = model->text(i);
        if (itemText == QString::fromUtf8(text))
            return i;
    }

    return -1;
}

bool hasItem(ProposalModel model, const QByteArray &text)
{
    return indexOfItemWithText(model, text) != -1;
}

bool hasItem(ProposalModel model, const QByteArray &text, const QByteArray &detail)
{
    const int index = indexOfItemWithText(model, text);
    if (index != -1 && index < model->size()) {
        TextEditor::IAssistProposalModel *imodel = model.data();
        const auto genericModel = static_cast<TextEditor::GenericProposalModel *>(imodel);
        const auto itemDetail = genericModel->detail(index);
        return itemDetail == QString::fromUtf8(detail);
    }

    return false;
}

bool hasSnippet(ProposalModel model, const QByteArray &text)
{
    if (!model)
        return false;

    // Snippets seem to end with a whitespace
    const QString snippetText = QString::fromUtf8(text) + QLatin1Char(' ');

    auto *genericModel = static_cast<TextEditor::GenericProposalModel *>(model.data());
    for (int i = 0, size = genericModel->size(); i < size; ++i) {
        TextEditor::AssistProposalItemInterface *item = genericModel->proposalItem(i);
        QTC_ASSERT(item, continue);
        if (item->text() == snippetText)
            return item->isSnippet();
    }

    return false;
}

class MonitorGeneratedUiFile : public QObject
{
    Q_OBJECT

public:
    MonitorGeneratedUiFile();
    bool waitUntilGenerated(int timeout = 10000) const;

private:
    void onUiFileGenerated() { m_isGenerated = true; }

    bool m_isGenerated = false;
};

MonitorGeneratedUiFile::MonitorGeneratedUiFile()
{
    connect(CppTools::CppModelManager::instance(),
            &CppTools::CppModelManager::abstractEditorSupportContentsUpdated,
            this, &MonitorGeneratedUiFile::onUiFileGenerated);
}

bool MonitorGeneratedUiFile::waitUntilGenerated(int timeout) const
{
    if (m_isGenerated)
        return true;

    QTime time;
    time.start();

    forever {
        if (m_isGenerated)
            return true;

        if (time.elapsed() > timeout)
            return false;

        QCoreApplication::processEvents();
        QThread::msleep(20);
    }

    return false;
}

class WriteFileAndWaitForReloadedDocument : public QObject
{
public:
    WriteFileAndWaitForReloadedDocument(const QString &filePath,
                                        const QByteArray &fileContents,
                                        Core::IDocument *document)
        : m_filePath(filePath)
        , m_fileContents(fileContents)
    {
        QTC_CHECK(document);
        connect(document, &Core::IDocument::reloadFinished,
                this, &WriteFileAndWaitForReloadedDocument::onReloadFinished);
    }

    void onReloadFinished()
    {
        m_onReloadFinished = true;
    }

    bool wait() const
    {
        QTC_ASSERT(writeFile(m_filePath, m_fileContents), return false);

        QTime totalTime;
        totalTime.start();

        QTime writeFileAgainTime;
        writeFileAgainTime.start();

        forever {
            if (m_onReloadFinished)
                return true;

            if (totalTime.elapsed() > 10000)
                return false;

            if (writeFileAgainTime.elapsed() > 3000) {
                // The timestamp did not change, try again now.
                QTC_ASSERT(writeFile(m_filePath, m_fileContents), return false);
                writeFileAgainTime.restart();
            }

            QCoreApplication::processEvents();
            QThread::msleep(20);
        }
    }

private:
    bool m_onReloadFinished = false;
    QString m_filePath;
    QByteArray m_fileContents;
};

} // anonymous namespace

namespace ClangCodeModel {
namespace Internal {
namespace Tests {

void ClangCodeCompletionTest::testCompleteDoxygenKeywords()
{
    ProjectLessCompletionTest t("doxygenKeywordsCompletion.cpp");

    QVERIFY(hasItem(t.proposal, "brief"));
    QVERIFY(hasItem(t.proposal, "param"));
    QVERIFY(hasItem(t.proposal, "return"));
    QVERIFY(!hasSnippet(t.proposal, "class"));
}

void ClangCodeCompletionTest::testCompletePreprocessorKeywords()
{
    ProjectLessCompletionTest t("preprocessorKeywordsCompletion.cpp");

    QVERIFY(hasItem(t.proposal, "ifdef"));
    QVERIFY(hasItem(t.proposal, "endif"));
    QVERIFY(!hasSnippet(t.proposal, "class"));
}

void ClangCodeCompletionTest::testCompleteIncludeDirective()
{
    CppTools::Tests::TemporaryCopiedDir testDir(qrcPath("exampleIncludeDir"));
    ProjectLessCompletionTest t("includeDirectiveCompletion.cpp",
                                QString(),
                                QStringList(testDir.path()));

    QVERIFY(hasItem(t.proposal, "file.h"));
    QVERIFY(hasItem(t.proposal, "otherFile.h"));
    QVERIFY(hasItem(t.proposal, "mylib/"));
    QVERIFY(!hasSnippet(t.proposal, "class"));
}

void ClangCodeCompletionTest::testCompleteGlobals()
{
    ProjectLessCompletionTest t("globalCompletion.cpp");

    QVERIFY(hasItem(t.proposal, "globalVariable", "int globalVariable"));
    QVERIFY(hasItem(t.proposal, "globalFunction", "void globalFunction ()"));
    QVERIFY(hasItem(t.proposal, "GlobalClass", "GlobalClass"));
    QVERIFY(hasItem(t.proposal, "class", "class"));    // Keyword
    QVERIFY(hasSnippet(t.proposal, "class")); // Snippet
}

void ClangCodeCompletionTest::testCompleteMembers()
{
    ProjectLessCompletionTest t("memberCompletion.cpp");

    QVERIFY(hasItem(t.proposal, "member"));
    QVERIFY(!hasItem(t.proposal, "globalVariable"));
    QVERIFY(!hasItem(t.proposal, "class"));    // Keyword
    QVERIFY(!hasSnippet(t.proposal, "class")); // Snippet
}

void ClangCodeCompletionTest::testCompleteFunctions()
{
    ProjectLessCompletionTest t("functionCompletion.cpp");

    QVERIFY(hasItem(t.proposal, "void f()"));
    QVERIFY(hasItem(t.proposal, "void f(int a)"));
    QVERIFY(hasItem(t.proposal, "void f(const QString &amp;s)"));
    QVERIFY(hasItem(t.proposal, "void f(char c<i>, int optional</i>)")); // TODO: No default argument?
    QVERIFY(hasItem(t.proposal, "void f(char c<i>, int optional1, int optional2</i>)")); // TODO: No default argument?
    QVERIFY(hasItem(t.proposal, "void f(const TType&lt;QString&gt; *t)"));
    QVERIFY(hasItem(t.proposal, "TType&lt;QString&gt; f(bool)"));
}

void ClangCodeCompletionTest::testCompleteConstructor()
{
    ProjectLessCompletionTest t("constructorCompletion.cpp");

    QVERIFY(!hasItem(t.proposal, "globalVariable"));
    QVERIFY(!hasItem(t.proposal, "class"));
    QVERIFY(hasItem(t.proposal, "Foo(int)"));
    QVERIFY(hasItem(t.proposal, "Foo(int, double)"));
}

// Explicitly Inserting The Dot
// ----------------------------
// Inserting the dot for is important since it will send the editor
// content to the backend and thus generate an unsaved file on the backend
// side. The unsaved file enables us to do the dot to arrow correction.

void ClangCodeCompletionTest::testCompleteWithDotToArrowCorrection()
{
    ProjectLessCompletionTest t("dotToArrowCorrection.cpp",
                                QStringLiteral(".")); // See above "Explicitly Inserting The Dot"

    QVERIFY(hasItem(t.proposal, "member"));
}

void ClangCodeCompletionTest::testDontCompleteWithDotToArrowCorrectionForFloats()
{
    ProjectLessCompletionTest t("noDotToArrowCorrectionForFloats.cpp",
                                QStringLiteral(".")); // See above "Explicitly Inserting The Dot"

    QCOMPARE(t.proposal->size(), 0);
}

void ClangCodeCompletionTest::testCompleteProjectDependingCode()
{
    const TestDocument testDocument("completionWithProject.cpp");
    QVERIFY(testDocument.isCreatedAndHasValidCursorPosition());

    ProjectLoader projectLoader(QStringList(testDocument.filePath),
                                _("#define PROJECT_CONFIGURATION_1\n"));
    QVERIFY(projectLoader.load());

    OpenEditorAtCursorPosition openEditor(testDocument);
    QVERIFY(openEditor.succeeded());

    ProposalModel proposal = completionResults(openEditor.editor());
    QVERIFY(hasItem(proposal, "projectConfiguration1"));
}

void ClangCodeCompletionTest::testCompleteProjectDependingCodeAfterChangingProject()
{
    const TestDocument testDocument("completionWithProject.cpp");
    QVERIFY(testDocument.isCreatedAndHasValidCursorPosition());

    OpenEditorAtCursorPosition openEditor(testDocument);
    QVERIFY(openEditor.succeeded());

    // Check completion without project
    ProposalModel proposal = completionResults(openEditor.editor());
    QVERIFY(hasItem(proposal, "noProjectConfigurationDetected"));

    {
        // Check completion with project configuration 1
        ProjectLoader projectLoader(QStringList(testDocument.filePath),
                                    _("#define PROJECT_CONFIGURATION_1\n"),
                                    /* testOnlyForCleanedProjects= */ true);
        QVERIFY(projectLoader.load());
        openEditor.waitUntilProjectPartChanged(QLatin1String("myproject.project"));

        proposal = completionResults(openEditor.editor());

        QVERIFY(hasItem(proposal, "projectConfiguration1"));
        QVERIFY(!hasItem(proposal, "projectConfiguration2"));

        // Check completion with project configuration 2
        QVERIFY(projectLoader.updateProject(_("#define PROJECT_CONFIGURATION_2\n")));
        proposal = completionResults(openEditor.editor());

        QVERIFY(!hasItem(proposal, "projectConfiguration1"));
        QVERIFY(hasItem(proposal, "projectConfiguration2"));
    } // Project closed

    // Check again completion without project
    openEditor.waitUntilProjectPartChanged(QLatin1String(""));
    proposal = completionResults(openEditor.editor());
    QVERIFY(hasItem(proposal, "noProjectConfigurationDetected"));
}

void ClangCodeCompletionTest::testCompleteProjectDependingCodeInGeneratedUiFile()
{
    CppTools::Tests::TemporaryCopiedDir testDir(qrcPath("qt-widgets-app"));
    QVERIFY(testDir.isValid());

    MonitorGeneratedUiFile monitorGeneratedUiFile;

    // Open project
    const QString projectFilePath = testDir.absolutePath("qt-widgets-app.pro");
    CppTools::Tests::ProjectOpenerAndCloser projectManager;
    const CppTools::ProjectInfo projectInfo = projectManager.open(projectFilePath, true);
    QVERIFY(projectInfo.isValid());
    QVERIFY(monitorGeneratedUiFile.waitUntilGenerated());

    // Open file with ui object
    const QString completionFile = testDir.absolutePath("mainwindow.cpp");
    const TestDocument testDocument = TestDocument::fromExistingFile(completionFile);
    QVERIFY(testDocument.isCreatedAndHasValidCursorPosition());
    OpenEditorAtCursorPosition openSource(testDocument);
    QVERIFY(openSource.succeeded());

    // ...and check comletions
    ProposalModel proposal = completionResults(openSource.editor());
    QVERIFY(hasItem(proposal, "menuBar"));
    QVERIFY(hasItem(proposal, "statusBar"));
    QVERIFY(hasItem(proposal, "centralWidget"));
    QVERIFY(hasItem(proposal, "setupUi"));
}

void ClangCodeCompletionTest::testCompleteAfterModifyingIncludedHeaderInOtherEditor()
{
    QSKIP("We don't reparse anymore before a code completion so we get wrong completion results.");

    CppTools::Tests::TemporaryDir temporaryDir;
    const TestDocument sourceDocument("mysource.cpp", &temporaryDir);
    QVERIFY(sourceDocument.isCreatedAndHasValidCursorPosition());
    const TestDocument headerDocument("myheader.h", &temporaryDir);
    QVERIFY(headerDocument.isCreated());

    // Test that declarations from header file are visible in source file
    OpenEditorAtCursorPosition openSource(sourceDocument);
    QVERIFY(openSource.succeeded());
    ProposalModel proposal = completionResults(openSource.editor());
    QVERIFY(hasItem(proposal, "globalFromHeader"));

    // Open header and insert a new declaration
    OpenEditorAtCursorPosition openHeader(headerDocument);
    QVERIFY(openHeader.succeeded());
    insertTextAtTopOfEditor(openHeader.editor(), "int globalFromHeaderUnsaved;\n");

    // Switch back to source file and check if modified header is reflected in completions.
    Core::EditorManager::activateEditor(openSource.editor());
    QCoreApplication::processEvents(); // connections are queued
    proposal = completionResults(openSource.editor());
    QVERIFY(hasItem(proposal, "globalFromHeader"));
    QVERIFY(hasItem(proposal, "globalFromHeaderUnsaved"));
}

void ClangCodeCompletionTest::testCompleteAfterModifyingIncludedHeaderByRefactoringActions()
{
    QSKIP("We don't reparse anymore before a code completion so we get wrong completion results.");

    CppTools::Tests::TemporaryDir temporaryDir;
    const TestDocument sourceDocument("mysource.cpp", &temporaryDir);
    QVERIFY(sourceDocument.isCreatedAndHasValidCursorPosition());
    const TestDocument headerDocument("myheader.h", &temporaryDir);
    QVERIFY(headerDocument.isCreated());

    // Open header
    OpenEditorAtCursorPosition openHeader(headerDocument);
    QVERIFY(openHeader.succeeded());

    // Open source and test that declaration from header file is visible in source file
    OpenEditorAtCursorPosition openSource(sourceDocument);
    QVERIFY(openSource.succeeded());
    ProposalModel proposal = completionResults(openSource.editor());
    QVERIFY(hasItem(proposal, "globalFromHeader"));

    // Modify header document without switching to its editor.
    // This simulates e.g. changes from refactoring actions.
    ::Utils::ChangeSet cs;
    cs.insert(0, QLatin1String("int globalFromHeaderUnsaved;\n"));
    QTextCursor textCursor = openHeader.editor()->textCursor();
    cs.apply(&textCursor);

    // Check whether modified header is reflected in the completions.
    proposal = completionResults(openSource.editor());
    QVERIFY(hasItem(proposal, "globalFromHeader"));
    QVERIFY(hasItem(proposal, "globalFromHeaderUnsaved"));
}

void ClangCodeCompletionTest::testCompleteAfterChangingIncludedAndOpenHeaderExternally()
{
    QSKIP("The file system watcher is doing it in backend process but we wait not long enough");

    ChangeDocumentReloadSetting reloadSettingsChanger(Core::IDocument::ReloadUnmodified);

    CppTools::Tests::TemporaryDir temporaryDir;
    const TestDocument sourceDocument("mysource.cpp", &temporaryDir);
    QVERIFY(sourceDocument.isCreatedAndHasValidCursorPosition());
    const TestDocument headerDocument("myheader.h", &temporaryDir);
    QVERIFY(headerDocument.isCreated());

    // Open header
    OpenEditorAtCursorPosition openHeader(headerDocument);
    QVERIFY(openHeader.succeeded());

    // Open source and test completions
    OpenEditorAtCursorPosition openSource(sourceDocument);
    QVERIFY(openSource.succeeded());
    ProposalModel proposal = completionResults(openSource.editor());
    QVERIFY(hasItem(proposal, "globalFromHeader"));

    // Simulate external modification and wait for reload
    WriteFileAndWaitForReloadedDocument waitForReloadedDocument(
                headerDocument.filePath,
                "int globalFromHeaderReloaded;\n",
                openHeader.editor()->document());
    QVERIFY(waitForReloadedDocument.wait());

    // Retrigger completion and check if its updated
    proposal = completionResults(openSource.editor());
    QVERIFY(hasItem(proposal, "globalFromHeaderReloaded"));
}

void ClangCodeCompletionTest::testCompleteAfterChangingIncludedAndNotOpenHeaderExternally()
{
    QSKIP("The file system watcher is doing it in backend process but we wait not long enough");

    CppTools::Tests::TemporaryDir temporaryDir;
    const TestDocument sourceDocument("mysource.cpp", &temporaryDir);
    QVERIFY(sourceDocument.isCreatedAndHasValidCursorPosition());
    const TestDocument headerDocument("myheader.h", &temporaryDir);
    QVERIFY(headerDocument.isCreated());

    // Open source and test completions
    OpenEditorAtCursorPosition openSource(sourceDocument);
    QVERIFY(openSource.succeeded());
    ProposalModel proposal = completionResults(openSource.editor());
    QVERIFY(hasItem(proposal, "globalFromHeader"));

    // Simulate external modification, e.g version control checkout
    QVERIFY(writeFile(headerDocument.filePath, "int globalFromHeaderReloaded;\n"));

    // Retrigger completion and check if its updated
    proposal = completionResults(openSource.editor());
    QVERIFY(hasItem(proposal, "globalFromHeaderReloaded"));
}

void ClangCodeCompletionTest::testUpdateBackendAfterRestart()
{
    QSKIP("Must be rewritten with a more robust approach instead of sender log!");
    IpcSenderSpy spy;
    ChangeIpcSender changeIpcSender(&spy);

    CppTools::Tests::TemporaryCopiedDir testDir(qrcPath("qt-widgets-app"));
    QVERIFY(testDir.isValid());

    // Open file not part of any project...
    const TestDocument headerDocument("myheader.h", &testDir);
    QVERIFY(headerDocument.isCreated());
    OpenEditorAtCursorPosition openHeader(headerDocument);
    QVERIFY(openHeader.succeeded());
    // ... and modify it, so we have an unsaved file.
    insertTextAtTopOfEditor(openHeader.editor(), "int someGlobal;\n");
    // Open project ...
    MonitorGeneratedUiFile monitorGeneratedUiFile;
    const QString projectFilePath = testDir.absolutePath("qt-widgets-app.pro");
    CppTools::Tests::ProjectOpenerAndCloser projectManager;
    const CppTools::ProjectInfo projectInfo = projectManager.open(projectFilePath, true);
    QVERIFY(projectInfo.isValid());
    QVERIFY(monitorGeneratedUiFile.waitUntilGenerated());
    // ...and a file of the project
    const QString completionFile = testDir.absolutePath("mainwindow.cpp");
    const TestDocument testDocument = TestDocument::fromExistingFile(completionFile);
    QVERIFY(testDocument.isCreatedAndHasValidCursorPosition());
    OpenEditorAtCursorPosition openSource(testDocument);
    QVERIFY(openSource.succeeded());

    // Check messages that would have been sent
    QVERIFY(compare(LogOutput(spy.senderLog),
                    LogOutput(
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: myheader.h ProjectPart: \n"
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: myheader.h ProjectPart: \n"
                        "RequestDiagnosticsMessage\n"
                        "  ProjectPartContainer id: qt-widgets-app.pro qt-widgets-app\n"
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: myheader.h ProjectPart: \n"
                        "RequestDiagnosticsMessage\n"
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: myheader.h ProjectPart: \n"
                        "RequestDiagnosticsMessage\n"
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: ui_mainwindow.h ProjectPart: \n"
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: myheader.h ProjectPart: \n"
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: mainwindow.cpp ProjectPart: qt-widgets-app.pro qt-widgets-app\n"
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: mainwindow.cpp ProjectPart: qt-widgets-app.pro qt-widgets-app\n"
                        "RequestDiagnosticsMessage\n"

                    )));
    spy.senderLog.clear();

    // Kill backend process...
    auto &ipcCommunicator = ModelManagerSupportClang::instance()->ipcCommunicator();
    ipcCommunicator.killBackendProcess();
    QSignalSpy waitForReinitializedBackend(&ipcCommunicator,
                                           SIGNAL(backendReinitialized()));
    QVERIFY(waitForReinitializedBackend.wait());

    // ...and check if code model backend would have been provided with current data
    QVERIFY(compare(LogOutput(spy.senderLog),
                    LogOutput(
                        "RegisterProjectPartsForEditorMessage\n"
                        "  ProjectPartContainer id: \n"
                        "RegisterProjectPartsForEditorMessage\n"
                        "  ProjectPartContainer id: qt-widgets-app.pro qt-widgets-app\n"
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: myheader.h ProjectPart: \n"
                        "RegisterTranslationUnitForEditorMessage\n"
                        "  Path: ui_mainwindow.h ProjectPart: \n"
                    )));
}

} // namespace Tests
} // namespace Internal
} // namespace ClangCodeModel

#include "clangcodecompletion_test.moc"