fileandtokenactions_test.cpp 20.6 KB
Newer Older
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
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include <cplusplus/CppDocument.h>
#include <cplusplus/TranslationUnit.h>

#include <coreplugin/editormanager/editormanager.h>
#include <cppeditor/cppeditor.h>
35
#include <cppeditor/cppeditorplugin.h>
36
#include <cppeditor/cppquickfixassistant.h>
37
#include <cppeditor/cppquickfixes.h>
38
#include <cppeditor/cppquickfix.h>
39
#include <cppeditor/cppquickfix_test_utils.h>
40
#include <cpptools/cppmodelmanagerinterface.h>
41
#include <cpptools/cpptoolsplugin.h>
42
43
44
45
46
47
48
49
50
51
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>
#include <texteditor/basetextdocument.h>

#include <QDebug>
#include <QtAlgorithms>
#include <QTextDocument>
#include <QtTest>

52
53
54
55
56
#if  QT_VERSION >= 0x050000
#define MSKIP_SINGLE(x) QSKIP(x)
#else
#define MSKIP_SINGLE(x) QSKIP(x, SkipSingle)
#endif
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

/*!
    Tests for executing "test actions" for
        (1) each file of each loaded project (file actions) or
            e.g. "Switch Header/Source"
        (2) each word/token of each file of each loaded project (token actions)
            e.g. "Trigger and perform all Quick Fixes"

    Purpose:
        Detect corner cases for which Qt Creator crashes or outputs QTC_ASSERTS.
        Correct behavior is *not* tested.

    Prerequisites:
        These tests depend on the projects that are loaded on startup of Qt Creator.
        Make sure to load the test projects via command line or the session manager.
        The test projects must be properly configured for a Kit.
 */

using namespace Core;
using namespace CPlusPlus;
using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace CppTools;
using namespace TextEditor;

namespace {

class TestActionsTestCase
{
public:
    class AbstractAction
    {
    public:
        /// Every Action is expected to undo its changes.
        virtual void run(CPPEditorWidget *editorWidget) = 0;
        virtual ~AbstractAction() {}
    };
    typedef QSharedPointer<AbstractAction> ActionPointer;
    typedef QList<ActionPointer> Actions;

public:
    /// Run the given fileActions for each file and the given tokenActions for each token.
    /// The cursor is positioned on the very first character of each token.
    void run(const Actions &tokenActions = Actions(),
             const Actions &fileActions = Actions());

    /// Simulate pressing ESC, which will close popups, search results pane, etc...
    /// This works only if the Qt Creator window is active.
    static void escape();

    /// Undoing changes
108
    static void undoChangesInDocument(BaseTextDocument *editorDocument);
109
110
111
112
113
114
115
116
117
118
119
120
    static void undoChangesInAllEditorWidgets();

    /// Execute actions for the current cursor position of editorWidget.
    static void executeActionsOnEditorWidget(CPPEditorWidget *editorWidget, Actions actions);

private:
    /// Move word camel case wise from current cursor position until given token (not included)
    /// and execute the tokenActions for each new position.
    static void moveWordCamelCaseToToken(TranslationUnit *translationUnit, Token token,
                                         CPPEditor *editor, const Actions &tokenActions);

    static void undoAllChangesAndCloseAllEditors();
121
122
123
124
125
126
127

    /// This function expects:
    /// (1) Only Qt4 projects are loaded (qmake in PATH should point to Qt4/bin).
    /// (2) No *.pro.user file exists for the projects.
    static void configureAllProjects(const QList<QPointer<ProjectExplorer::Project> > &projects);

    static bool allProjectsConfigured;
128
129
};

130
131
bool TestActionsTestCase::allProjectsConfigured = false;

132
133
134
135
136
137
138
139
140
typedef TestActionsTestCase::Actions Actions;
typedef TestActionsTestCase::ActionPointer ActionPointer;

void TestActionsTestCase::run(const Actions &tokenActions, const Actions &fileActions)
{
    CppModelManagerInterface *mm = CppModelManagerInterface::instance();

    // Collect files to process
    QStringList filesToOpen;
141
    QList<QPointer<ProjectExplorer::Project> > projects;
142
143
    const QList<CppModelManagerInterface::ProjectInfo> projectInfos = mm->projectInfos();
    if (projectInfos.isEmpty())
144
        MSKIP_SINGLE("No project(s) loaded. Test operates only on loaded projects.");
145
146

    foreach (const CppModelManagerInterface::ProjectInfo &info, projectInfos) {
147
148
149
        QPointer<ProjectExplorer::Project> project = info.project();
        if (!projects.contains(project))
            projects << project;
150
151
152
153
154
155
        qDebug() << "Project" << info.project()->displayName() << "- files to process:"
                 << info.sourceFiles().size();
        foreach (const QString &sourceFile, info.sourceFiles())
            filesToOpen << sourceFile;
    }

156
157
158
159
160
161
    // Configure all projects on first execution of this function (= very first test)
    if (!TestActionsTestCase::allProjectsConfigured) {
        configureAllProjects(projects);
        TestActionsTestCase::allProjectsConfigured = true;
    }

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    qSort(filesToOpen);

    // Process all files from the projects
    foreach (const QString filePath, filesToOpen) {
        // Skip e.g. "<configuration>"
        const QFileInfo fileInfo(filePath);
        if (!fileInfo.exists())
            continue;

        qDebug() << " --" << filePath;

        // Clean up
        undoAllChangesAndCloseAllEditors();

        // Open editor
177
        QCOMPARE(EditorManager::documentModel()->openedDocuments().size(), 0);
Kai Koehne's avatar
Kai Koehne committed
178
        CPPEditor *editor = dynamic_cast<CPPEditor *>(EditorManager::openEditor(filePath));
179
        QVERIFY(editor);
180
        QCOMPARE(EditorManager::documentModel()->openedDocuments().size(), 1);
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
        QVERIFY(mm->isCppEditor(editor));
        QVERIFY(mm->workingCopy().contains(filePath));

        // Rehighlight
        CPPEditorWidget *editorWidget = dynamic_cast<CPPEditorWidget *>(editor->editorWidget());
        QVERIFY(editorWidget);
        editorWidget->semanticRehighlight(true);
        while (editorWidget->semanticInfo().doc.isNull())
            QApplication::processEvents();

        // Run all file actions
        executeActionsOnEditorWidget(editorWidget, fileActions);

        if (tokenActions.empty())
            continue;

        Snapshot snapshot = mm->snapshot();
        Document::Ptr document = snapshot.preprocessedDocument(
199
            editorWidget->document()->toPlainText().toUtf8(), filePath);
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
        QVERIFY(document);
        document->parse();
        TranslationUnit *translationUnit = document->translationUnit();
        QVERIFY(translationUnit);
        QVERIFY(translationUnit->tokenCount() >= 2); // First invalid token included

        // Move word camel case wise from the top until the first user visible token
        editor->gotoLine(1);
        const Token token = translationUnit->tokenAt(1);
        moveWordCamelCaseToToken(translationUnit, token, editor, tokenActions);

        // Move token wise through the document
        // translationUnit->tokenAt(0) is the invalid token, so start with 1.
        for (unsigned i = 1, ei = translationUnit->tokenCount(); i < ei; ++i) {
            const Token token = translationUnit->tokenAt(i);
            if (token.kind() == T_EOF_SYMBOL)
                continue;

            if (token.expanded()) {
                // Move word camel case wise until first not expanded token
                unsigned j = i + 1;
                for (; translationUnit->tokenAt(j).expanded() && j < ei; ++j) ;
                if (j == ei) {
                    if (j == i + 1)
                        break;
                    else // All tokens are expanded until end
                        j = j - 1;
                }
                const Token token = translationUnit->tokenAt(j);
                moveWordCamelCaseToToken(translationUnit, token, editor, tokenActions);
                i = j - 1; // Continue with next not expanded token
            } else {
                // Position the cursor on the token
                unsigned line, column;
                translationUnit->getPosition(token.offset, &line, &column);
                editor->gotoLine(line, column - 1);
                QApplication::processEvents();

                // Run all token actions
                executeActionsOnEditorWidget(editorWidget, tokenActions);
            }
        } // for tokens
    } // for files

    // Clean up
    undoAllChangesAndCloseAllEditors();
}

void TestActionsTestCase::escape()
{
    if (QWidget *w = QApplication::focusWidget())
        QTest::keyClick(w, Qt::Key_Escape);
}

254
void TestActionsTestCase::undoChangesInDocument(BaseTextDocument *editorDocument)
255
{
256
    QTextDocument * const document = editorDocument->document();
257
258
    QVERIFY(document);
    while (document->isUndoAvailable())
259
        document->undo();
260
261
262
263
}

void TestActionsTestCase::undoChangesInAllEditorWidgets()
{
264
265
266
    foreach (IDocument *document, EditorManager::documentModel()->openedDocuments()) {
        BaseTextDocument *baseTextDocument = qobject_cast<BaseTextDocument *>(document);
        undoChangesInDocument(baseTextDocument);
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
    }
}

void TestActionsTestCase::executeActionsOnEditorWidget(CPPEditorWidget *editorWidget,
                                                        TestActionsTestCase::Actions actions)
{
    foreach (const ActionPointer &action, actions)
        action->run(editorWidget);
    QApplication::processEvents();
}

void TestActionsTestCase::moveWordCamelCaseToToken(TranslationUnit *translationUnit, Token token,
                                                    CPPEditor *editor, const Actions &tokenActions)
{
    QVERIFY(translationUnit);
    QVERIFY(editor);
    CPPEditorWidget *editorWidget = dynamic_cast<CPPEditorWidget *>(editor->editorWidget());
    QVERIFY(editorWidget);

    unsigned line, column;
    translationUnit->getPosition(token.offset, &line, &column);

    while (editor->currentLine() < (int) line
           || (editor->currentLine() == (int) line
               && editor->currentColumn() < (int) column)) {
        editorWidget->gotoNextWordCamelCase();
        QApplication::processEvents();

        // Run all token actions
        executeActionsOnEditorWidget(editorWidget, tokenActions);
    }
}

void TestActionsTestCase::undoAllChangesAndCloseAllEditors()
{
    undoChangesInAllEditorWidgets();
303
    EditorManager::closeAllEditors(/*askAboutModifiedEditors =*/ false);
304
    QApplication::processEvents();
305
    QCOMPARE(EditorManager::documentModel()->openedDocuments().size(), 0);
306
307
}

308
309
310
311
312
313
314
315
316
void TestActionsTestCase::configureAllProjects(const QList<QPointer<ProjectExplorer::Project> >
                                               &projects)
{
    foreach (const QPointer<ProjectExplorer::Project> &project, projects) {
        qDebug() << "*** Configuring project" << project->displayName();
        project->configureAsExampleProject(QStringList());
    }
}

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
class NoOpTokenAction : public TestActionsTestCase::AbstractAction
{
public:
    /// Do nothing on each token
    void run(CPPEditorWidget *) {}
};

class FollowSymbolUnderCursorTokenAction : public TestActionsTestCase::AbstractAction
{
public:
    /// Follow symbol under cursor
    /// Warning: May block if file does not exists (e.g. a not generated ui_* file).
    void run(CPPEditorWidget *editorWidget);
};

void FollowSymbolUnderCursorTokenAction::run(CPPEditorWidget *editorWidget)
{
    // Follow link
335
    IEditor *editorBefore = EditorManager::currentEditor();
336
337
338
339
340
341
342
    const int originalLine = editorBefore->currentLine();
    const int originalColumn = editorBefore->currentColumn();
    editorWidget->openLinkUnderCursor();
    TestActionsTestCase::escape();
    QApplication::processEvents();

    // Go back
343
    IEditor *editorAfter = EditorManager::currentEditor();
344
    if (editorAfter != editorBefore)
345
        EditorManager::goBackInNavigationHistory();
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
    else
        editorBefore->gotoLine(originalLine, originalColumn);
    QApplication::processEvents();
}

class SwitchDeclarationDefinitionTokenAction : public TestActionsTestCase::AbstractAction
{
public:
    /// Switch Declaration/Definition on each token
    void run(CPPEditorWidget *);
};

void SwitchDeclarationDefinitionTokenAction::run(CPPEditorWidget *)
{
    // Switch Declaration/Definition
361
    IEditor *editorBefore = EditorManager::currentEditor();
362
363
    const int originalLine = editorBefore->currentLine();
    const int originalColumn = editorBefore->currentColumn();
364
    CppEditor::Internal::CppEditorPlugin::instance()->switchDeclarationDefinition();
365
366
367
    QApplication::processEvents();

    // Go back
368
    IEditor *editorAfter = EditorManager::currentEditor();
369
    if (editorAfter != editorBefore)
370
        EditorManager::goBackInNavigationHistory();
371
372
373
374
375
376
377
378
379
380
381
382
383
384
    else
        editorBefore->gotoLine(originalLine, originalColumn);
    QApplication::processEvents();
}

class FindUsagesTokenAction : public TestActionsTestCase::AbstractAction
{
public:
    /// Find Usages on each token
    void run(CPPEditorWidget *);
};

void FindUsagesTokenAction::run(CPPEditorWidget *)
{
385
    CppEditor::Internal::CppEditorPlugin::instance()->findUsages();
386
387
388
389
390
391
392
393
394
395
396
397
    QApplication::processEvents();
}

class RenameSymbolUnderCursorTokenAction : public TestActionsTestCase::AbstractAction
{
public:
    /// Rename Symbol Under Cursor on each token (Renaming is not applied)
    void run(CPPEditorWidget *);
};

void RenameSymbolUnderCursorTokenAction::run(CPPEditorWidget *)
{
398
    CppEditor::Internal::CppEditorPlugin::instance()->renameSymbolUnderCursor();
399
400
401
402
403
404
405
406
407
408
409
410
    QApplication::processEvents();
}

class OpenTypeHierarchyTokenAction : public TestActionsTestCase::AbstractAction
{
public:
    /// Open Type Hierarchy on each token
    void run(CPPEditorWidget *);
};

void OpenTypeHierarchyTokenAction::run(CPPEditorWidget *)
{
411
    CppEditor::Internal::CppEditorPlugin::instance()->openTypeHierarchy();
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
    QApplication::processEvents();
}

class InvokeCompletionTokenAction : public TestActionsTestCase::AbstractAction
{
public:
    /// Invoke completion menu on each token.
    /// Warning: May create tool tip artefacts if focus is lost.
    void run(CPPEditorWidget *editorWidget);
};

void InvokeCompletionTokenAction::run(CPPEditorWidget *editorWidget)
{
    // Invoke assistant and wait until it is finished
    QEventLoop loop;
    QObject::connect(editorWidget, SIGNAL(assistFinished()), &loop, SLOT(quit()));
    editorWidget->invokeAssist(Completion);
    loop.exec();

    // Close the completion popup widget
    QApplication::processEvents();
    editorWidget->abortAssist();
    // An alternative way to close the completion pop up is to give the editor widget the focus.
    // This works only if the Qt Creator window is always the active window.
    //    editorWidget->setFocus();
    QApplication::processEvents();

439
440
    BaseTextDocument *doc = qobject_cast<BaseTextDocument *>(editorWidget->editorDocument());
    TestActionsTestCase::undoChangesInDocument(doc);
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
}

class RunAllQuickFixesTokenAction : public TestActionsTestCase::AbstractAction
{
public:
    /// Trigger all Quick Fixes and apply the matching ones
    void run(CPPEditorWidget *editorWidget);
};

// TODO: Some QuickFixes operate on selections.
void RunAllQuickFixesTokenAction::run(CPPEditorWidget *editorWidget)
{
    // Calling editorWidget->invokeAssist(QuickFix) would be not enough
    // since we also want to execute the ones that match.

    const QList<CppQuickFixFactory *> quickFixFactories
        = ExtensionSystem::PluginManager::getObjects<CppQuickFixFactory>();
    QVERIFY(!quickFixFactories.isEmpty());

    CppQuickFixInterface qfi(new CppQuickFixAssistInterface(editorWidget, ExplicitlyInvoked));
    // This guard is important since the Quick Fixes expect to get a non-empty path().
    if (qfi->path().isEmpty())
        return;

    foreach (CppQuickFixFactory *quickFixFactory, quickFixFactories) {
        TextEditor::QuickFixOperations operations;
467
468
469
470
471
472
473
474
475
476
477
478
479
        // Some Quick Fixes pop up a dialog and are therefore inappropriate for this test.
        // Where possible, use a guiless version of the factory.
        if (qobject_cast<InsertVirtualMethods *>(quickFixFactory)) {
            QScopedPointer<CppQuickFixFactory> factoryProducingGuiLessOperations;
            factoryProducingGuiLessOperations.reset(
                new InsertVirtualMethods(
                    new InsertVirtualMethodsDialogTest(
                        InsertVirtualMethodsDialog::ModeOutsideClass, true)));
            factoryProducingGuiLessOperations->match(qfi, operations);
        } else {
            quickFixFactory->match(qfi, operations);
        }

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
        foreach (QuickFixOperation::Ptr operation, operations) {
            qDebug() << "    -- Performing Quick Fix" << operation->description();
            operation->perform();
            TestActionsTestCase::escape();
            TestActionsTestCase::undoChangesInAllEditorWidgets();
            QApplication::processEvents();
        }
    }
}

class SwitchHeaderSourceFileAction : public TestActionsTestCase::AbstractAction
{
public:
    void run(CPPEditorWidget *);
};

void SwitchHeaderSourceFileAction::run(CPPEditorWidget *)
{
    // Switch Header/Source
499
    IEditor *editorBefore = EditorManager::currentEditor();
500
501
502
503
    CppTools::Internal::CppToolsPlugin::instance()->switchHeaderSource();
    QApplication::processEvents();

    // Go back
504
    IEditor *editorAfter = EditorManager::currentEditor();
505
    if (editorAfter != editorBefore)
506
        EditorManager::goBackInNavigationHistory();
507
508
509
510
511
    QApplication::processEvents();
}

} // anonymous namespace

512
void CppEditorPlugin::test_openEachFile()
513
514
515
516
517
{
    TestActionsTestCase test;
    test.run();
}

518
void CppEditorPlugin::test_switchHeaderSourceOnEachFile()
519
520
521
522
523
524
525
526
{
    Actions fileActions;
    fileActions << ActionPointer(new SwitchHeaderSourceFileAction);

    TestActionsTestCase test;
    test.run(Actions(), fileActions);
}

527
void CppEditorPlugin::test_moveTokenWiseThroughEveryFile()
528
529
530
531
532
533
534
535
536
{
    Actions tokenActions;
    tokenActions << ActionPointer(new NoOpTokenAction());

    TestActionsTestCase test;
    test.run(tokenActions);
}

/// May block if file does not exists (e.g. a not generated ui_* file).
537
void CppEditorPlugin::test_moveTokenWiseThroughEveryFileAndFollowSymbol()
538
539
540
541
542
543
544
545
{
    Actions tokenActions;
    tokenActions << ActionPointer(new FollowSymbolUnderCursorTokenAction());

    TestActionsTestCase test;
    test.run(tokenActions);
}

546
void CppEditorPlugin::test_moveTokenWiseThroughEveryFileAndSwitchDeclarationDefinition()
547
548
549
550
551
552
553
554
{
    Actions tokenActions;
    tokenActions << ActionPointer(new SwitchDeclarationDefinitionTokenAction());

    TestActionsTestCase test;
    test.run(tokenActions);
}

555
void CppEditorPlugin::test_moveTokenWiseThroughEveryFileAndFindUsages()
556
557
558
559
560
561
562
563
{
    Actions tokenActions;
    tokenActions << ActionPointer(new FindUsagesTokenAction());

    TestActionsTestCase test;
    test.run(tokenActions);
}

564
void CppEditorPlugin::test_moveTokenWiseThroughEveryFileAndRenameUsages()
565
566
567
568
569
570
571
572
{
    Actions tokenActions;
    tokenActions << ActionPointer(new RenameSymbolUnderCursorTokenAction());

    TestActionsTestCase test;
    test.run(tokenActions);
}

573
void CppEditorPlugin::test_moveTokenWiseThroughEveryFileAndOpenTypeHierarchy()
574
575
576
577
578
579
580
581
{
    Actions tokenActions;
    tokenActions << ActionPointer(new OpenTypeHierarchyTokenAction());

    TestActionsTestCase test;
    test.run(tokenActions);
}

582
void CppEditorPlugin::test_moveTokenWiseThroughEveryFileAndInvokeCompletion()
583
584
585
586
587
588
589
590
{
    Actions tokenActions;
    tokenActions << ActionPointer(new InvokeCompletionTokenAction());

    TestActionsTestCase test;
    test.run(tokenActions);
}

591
void CppEditorPlugin::test_moveTokenWiseThroughEveryFileAndTriggerQuickFixes()
592
593
594
595
596
597
598
{
    Actions tokenActions;
    tokenActions << ActionPointer(new RunAllQuickFixesTokenAction());

    TestActionsTestCase test;
    test.run(tokenActions);
}