pycompletiontest.cpp 30.6 KB
Newer Older
1 2 3 4 5
/*****************************************************************************
 *   Copyright 2012 Sven Brauch <svenbrauch@googlemail.com>                  *
 *                                                                           *
 *   This program is free software: you can redistribute it and/or modify    *
 *   it under the terms of the GNU General Public License as published by    *
6
 *   the Free Software Foundation, either version 2 of the License, or       *
7 8 9 10 11 12 13 14 15 16 17 18
 *   (at your option) any later version.                                     *
 *                                                                           *
 *   This program is distributed in the hope that it will be useful,         *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
 *   GNU General Public License for more details.                            *
 *                                                                           *
 *   You should have received a copy of the GNU General Public License       *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>    *
 *****************************************************************************/

#include "pycompletiontest.h"
19

20
#include <language/backgroundparser/backgroundparser.h>
21
#include <language/codecompletion/codecompletiontesthelper.h>
Sven Brauch's avatar
Sven Brauch committed
22
#include <language/duchain/declaration.h>
23 24
#include <language/codegen/coderepresentation.h>
#include <language/duchain/duchain.h>
25 26
#include <interfaces/ilanguagecontroller.h>

27 28
#include <tests/testcore.h>
#include <tests/autotestshell.h>
29

Kevin Funk's avatar
Kevin Funk committed
30
#include <ktexteditor_version.h>
31 32
#include <KTextEditor/Editor>
#include <KService>
Sven Brauch's avatar
Sven Brauch committed
33

34
#include "codecompletion/context.h"
35
#include "codecompletion/helpers.h"
Kevin Funk's avatar
Kevin Funk committed
36
#include "codecompletiondebug.h"
37

38
#include <QDebug>
39
#include <QStandardPaths>
Yuri Chornoivan's avatar
Yuri Chornoivan committed
40
#include <QTest>
41

42 43
using namespace KDevelop;

Sven Brauch's avatar
Sven Brauch committed
44 45
QTEST_MAIN(Python::PyCompletionTest)

46 47
Q_DECLARE_METATYPE(QList<Python::RangeInString>)

48
static int testId = 0;
49
static QString basepath = "/tmp/__kdevpythoncompletiontest.dir/";
50 51

namespace Python {
52

53 54 55 56 57 58
QStandardItemModel& fakeModel() {
  static QStandardItemModel model;
  model.setColumnCount(10);
  model.setRowCount(10);
  return model;
}
59 60

QString filenameForTestId(const int id) {
61
    return basepath + "test_" + QString::number(id) + ".py";
62 63 64 65 66 67 68
}

QString nextFilename() {
    testId += 1;
    return filenameForTestId(testId);
}

Sven Brauch's avatar
Sven Brauch committed
69 70
PyCompletionTest::PyCompletionTest(QObject* parent) : QObject(parent)
{
71
    initShell();
Sven Brauch's avatar
Sven Brauch committed
72 73
}

74 75 76 77
void makefile(QString filename, QString contents) {
    QFile fileptr;
    fileptr.setFileName(basepath + filename);
    fileptr.open(QIODevice::WriteOnly);
78
    fileptr.write(contents.toUtf8());
79
    fileptr.close();
80
    auto url = QUrl::fromLocalFile(QDir::cleanPath(basepath + filename));
81
    qCDebug(KDEV_PYTHON_CODECOMPLETION) <<  "updating duchain for " << url.url() << basepath;
82
    const IndexedString urlstring(url);
Sven Brauch's avatar
Sven Brauch committed
83
    DUChain::self()->updateContextForUrl(urlstring, KDevelop::TopDUContext::ForceUpdate);
84
    ICore::self()->languageController()->backgroundParser()->parseDocuments();
Sven Brauch's avatar
Sven Brauch committed
85
    DUChain::self()->waitForUpdate(urlstring, KDevelop::TopDUContext::AllDeclarationsContextsAndUses);
86 87
}

88 89 90 91 92
void PyCompletionTest::initShell()
{
    AutoTestShell::init();
    TestCore* core = new TestCore();
    core->initialize(KDevelop::Core::NoUi);
Sven Brauch's avatar
Sven Brauch committed
93 94
    QDir d;
    d.mkpath(basepath);
Miquel Sabaté's avatar
Miquel Sabaté committed
95

96 97 98
    auto doc_url = QDir::cleanPath(QStandardPaths::locate(QStandardPaths::GenericDataLocation,
                                                          "kdevpythonsupport/documentation_files/builtindocumentation.py"));

99
    DUChain::self()->updateContextForUrl(IndexedString(doc_url), KDevelop::TopDUContext::AllDeclarationsContextsAndUses);
100
    ICore::self()->languageController()->backgroundParser()->parseDocuments();
101
    DUChain::self()->waitForUpdate(IndexedString(doc_url), KDevelop::TopDUContext::AllDeclarationsContextsAndUses);
Miquel Sabaté's avatar
Miquel Sabaté committed
102

103 104
    DUChain::self()->disablePersistentStorage();
    KDevelop::CodeRepresentation::setDiskChangesForbidden(true);
Miquel Sabaté's avatar
Miquel Sabaté committed
105

106
    // now, create a nice little completion hierarchy
Sven Brauch's avatar
Sven Brauch committed
107 108
    d.mkpath(basepath + "submoduledir");
    d.mkpath(basepath + "submoduledir/anothersubdir");
109 110 111 112 113 114
    makefile("toplevelmodule.py", "some_var = 3\ndef some_function(): pass\nclass some_class():\n def method(): pass");
    makefile("submoduledir/__init__.py", "var_in_sub_init = 5");
    makefile("submoduledir/subfile.py", "var_in_subfile = 5\nclass some_subfile_class():\n def method2(): pass");
    makefile("submoduledir/anothersubdir/__init__.py", "var_in_subsub_init = 5");
    makefile("submoduledir/anothersubdir/subsubfile.py", "var_in_subsubfile = 5\nclass another_subfile_class():"
                                                      "\n def method3(): pass");
115 116
}

117 118
void PyCompletionTest::testIdentifierMatching()
{
119 120
    QCOMPARE(camelCaseToUnderscore("FooBarBaz").toUtf8().data(), "foo_bar_baz");
    QCOMPARE(camelCaseToUnderscore("fooBarbaz").toUtf8().data(),  "foo_barbaz");
121 122 123 124 125 126 127 128 129 130 131 132 133

    QCOMPARE(identifierMatchQuality("foobar", "foobar"),  3);
    QCOMPARE(identifierMatchQuality("foobar", "bar"),  2);
    QCOMPARE(identifierMatchQuality("bar", "foobar"),  2);
    QCOMPARE(identifierMatchQuality("foobarbaz", "bar"),  2);
    QCOMPARE(identifierMatchQuality("bar", "foobarbaz"),  2);
    QCOMPARE(identifierMatchQuality("FoobarBaz", "FoobarBang"), 1);
    QCOMPARE(identifierMatchQuality("Foobar_Baz", "Foobar_Bang"), 1);
    QCOMPARE(identifierMatchQuality("xydsf", "qkigfb"), 0);
    QCOMPARE(identifierMatchQuality("ac_ac", "ac_ae"), 0);
    QCOMPARE(identifierMatchQuality("AcAb", "AbDe"), 0);
}

134 135 136 137 138 139
void PyCompletionTest::testExpressionParserMisc()
{
    // in completion, strings are filtered out and never contain " or ' chars.
    ExpressionParser p("foobar(3, \"some_string\", func(), funcfunc(3, 5), \t");
    bool ok;
    int expressionsSkipped = 0;
140
    p.skipUntilStatus(ExpressionParser::EventualCallFound, &ok, &expressionsSkipped);
141 142 143
    QVERIFY(ok);
    QCOMPARE(expressionsSkipped, 4); // number of params
    QCOMPARE(p.getRemainingCode(), QString("foobar"));
Sven Brauch's avatar
Sven Brauch committed
144 145 146 147
    ExpressionParser::Status s;
    QString calledFunction = p.popExpression(&s);
    QVERIFY(s == ExpressionParser::ExpressionFound);
    QCOMPARE(calledFunction, QString("foobar"));
Miquel Sabaté's avatar
Miquel Sabaté committed
148

Sven Brauch's avatar
Sven Brauch committed
149
    ExpressionParser q("hello(world, foo.bar[3].foobar(3, \"some_string\", func(), funcfunc(3, 5), \t");
150
    q.skipUntilStatus(ExpressionParser::EventualCallFound, &ok, &expressionsSkipped);
151 152
    QVERIFY(ok);
    QCOMPARE(expressionsSkipped, 4);
Sven Brauch's avatar
Sven Brauch committed
153 154 155 156
    QCOMPARE(q.getRemainingCode(), QString("hello(world, foo.bar[3].foobar"));
    calledFunction = q.popExpression(&s);
    QCOMPARE(s, ExpressionParser::ExpressionFound);
    QCOMPARE(calledFunction, QString("foo.bar[3].foobar"));
157 158
}

159 160 161 162 163
void PyCompletionTest::testExpressionParser()
{
    QFETCH(QString, data);
    QFETCH(int, expectedStatus);
    QFETCH(QString, expectedExpression);
Miquel Sabaté's avatar
Miquel Sabaté committed
164

165 166 167 168 169 170 171 172 173 174 175 176
    ExpressionParser p(data);
    ExpressionParser::Status status;
    QString result = p.popExpression(&status);
    QCOMPARE((int) status, expectedStatus);
    QCOMPARE(result, expectedExpression);
}

void PyCompletionTest::testExpressionParser_data()
{
    QTest::addColumn<QString>("data");
    QTest::addColumn<int>("expectedStatus");
    QTest::addColumn<QString>("expectedExpression");
Miquel Sabaté's avatar
Miquel Sabaté committed
177

178 179 180 181
    QTest::newRow("attrExpression") << "foo.bar.baz" << (int) ExpressionParser::ExpressionFound << "foo.bar.baz";
    QTest::newRow("attrExpressionAccess") << "foo.bar.baz." << (int) ExpressionParser::MemberAccessFound << "";
    QTest::newRow("attrExpressionCall") << "foo.bar(3, 5, 7, hell0(3)).baz" << (int) ExpressionParser::ExpressionFound << "foo.bar(3, 5, 7, hell0(3)).baz";
    QTest::newRow("nextArg") << "foo(3, 5, \t" << (int) ExpressionParser::CommaFound << "";
182
    QTest::newRow("call") << "fo0barR( \t  " << (int) ExpressionParser::EventualCallFound << "";
183
    QTest::newRow("initializer") << "my_list = [" << (int) ExpressionParser::InitializerFound << "";
184
    QTest::newRow("fancy_initializer") << "my_list = [1, 2, 3, 4, []" << (int) ExpressionParser::ExpressionFound << "[]";
185
    QTest::newRow("def") << "def " << (int) ExpressionParser::DefFound << "";
186 187
}

188
const QList<CompletionTreeItem*> PyCompletionTest::invokeCompletionOn(const QString& initCode, const QString& invokeCode)
189
{
190 191 192 193 194 195 196 197
    CompletionParameters data = prepareCompletion(initCode, invokeCode);
    return runCompletion(data);
}

const CompletionParameters PyCompletionTest::prepareCompletion(const QString& initCode, const QString& invokeCode)
{
    CompletionParameters completion_data;

198 199 200
    QString filename = nextFilename();
    QFile fileptr(filename);
    fileptr.open(QIODevice::WriteOnly);
201
    fileptr.write(initCode.toUtf8().replace("%INVOKE", ""));
202
    fileptr.close();
Miquel Sabaté's avatar
Miquel Sabaté committed
203

204
    DUChain::self()->updateContextForUrl(IndexedString(filename), KDevelop::TopDUContext::ForceUpdate);
205
    ICore::self()->languageController()->backgroundParser()->parseDocuments();
206 207
    ReferencedTopDUContext topContext = DUChain::self()->waitForUpdate(IndexedString(filename),
                                                                       KDevelop::TopDUContext::AllDeclarationsAndContexts);
Miquel Sabaté's avatar
Miquel Sabaté committed
208

209
    Q_ASSERT(topContext);
Miquel Sabaté's avatar
Miquel Sabaté committed
210

211 212 213
    Q_ASSERT(initCode.indexOf("%INVOKE") != -1);
    QString copy = initCode;
    QString allCode = copy.replace("%INVOKE", invokeCode);
Miquel Sabaté's avatar
Miquel Sabaté committed
214

215
    QStringList lines = allCode.split('\n');
216
    completion_data.cursorAt = CursorInRevision::invalid();
217
    for ( int i = 0; i < lines.length(); i++ ) {
218 219
        int j = lines.at(i).indexOf("%CURSOR");
        if ( j != -1 ) {
220
            completion_data.cursorAt = CursorInRevision(i, j);
221 222
            break;
        }
223
    }
224
    Q_ASSERT(completion_data.cursorAt.isValid());
225
    // codeCompletionContext only gets passed the text until the place where completion is invoked
226 227
    completion_data.snip = allCode.mid(0, allCode.indexOf("%CURSOR"));
    completion_data.remaining = allCode.mid(allCode.indexOf("%CURSOR") + 7);
Miquel Sabaté's avatar
Miquel Sabaté committed
228

Sven Brauch's avatar
Sven Brauch committed
229
    DUChainReadLocker lock;
230 231
    completion_data.contextAtCursor = DUContextPointer(topContext->findContextAt(completion_data.cursorAt, true));
    Q_ASSERT(completion_data.contextAtCursor);
Miquel Sabaté's avatar
Miquel Sabaté committed
232

233 234 235 236 237
    return completion_data;
}

const QList<CompletionTreeItem*> PyCompletionTest::runCompletion(const CompletionParameters parameters)
{
238
    PythonCodeCompletionContext* context = new PythonCodeCompletionContext(parameters.contextAtCursor, parameters.snip, parameters.remaining, parameters.cursorAt, 0, nullptr);
Sven Brauch's avatar
Sven Brauch committed
239
    bool abort = false;
240
    QList<CompletionTreeItem*> items;
241
    foreach ( CompletionTreeItemPointer ptr, context->completionItems(abort, true) ) {
242 243 244 245 246
        items << ptr.data();
        // those are leaked, but it's only a few kb while the tests are running. who cares.
        m_ptrs << ptr;
    }
    return items;
Sven Brauch's avatar
Sven Brauch committed
247 248
}

249
bool PyCompletionTest::containsItemForDeclarationNamed(const QList<CompletionTreeItem*> items, QString itemName)
Sven Brauch's avatar
Sven Brauch committed
250
{
251
    foreach ( const CompletionTreeItem* ptr, items ) {
Sven Brauch's avatar
Sven Brauch committed
252 253 254 255 256 257 258 259 260
        if ( ptr->declaration() ) {
            if ( ptr->declaration()->identifier().toString() == itemName ) {
                return true;
            }
        }
    }
    return false;
}

261
bool PyCompletionTest::containsItemStartingWith(const QList<CompletionTreeItem*> items, const QString& itemName)
262 263
{
    QModelIndex idx = fakeModel().index(0, KDevelop::CodeCompletionModel::Name);
264
    foreach ( const CompletionTreeItem* ptr, items ) {
265
        if ( ptr->data(idx, Qt::DisplayRole, nullptr).toString().startsWith(itemName) ) {
266 267 268 269 270 271 272 273
            return true;
        }
    }
    return false;
}

bool PyCompletionTest::itemInCompletionList(const QString& initCode, const QString& invokeCode, QString itemName)
{
274 275
    QList< CompletionTreeItem* > items = invokeCompletionOn(initCode, invokeCode);
    return containsItemStartingWith(items, itemName);
276 277
}

278 279
bool PyCompletionTest::declarationInCompletionList(const QString& initCode, const QString& invokeCode, QString itemName)
{
280 281
    QList< CompletionTreeItem* > items = invokeCompletionOn(initCode, invokeCode);
    return containsItemForDeclarationNamed(items, itemName);
282 283 284 285 286 287 288
}

bool PyCompletionTest::completionListIsEmpty(const QString& initCode, const QString& invokeCode)
{
    return invokeCompletionOn(initCode, invokeCode).isEmpty();
}

289 290 291 292 293
void PyCompletionTest::testImportCompletion()
{
    QFETCH(QString, invokeCode);
    QFETCH(QString, completionCode);
    QFETCH(QString, expectedItem);
294

295 296 297 298 299 300 301 302 303 304 305 306 307
    if ( expectedItem == "EMPTY" ) {
        QVERIFY(completionListIsEmpty(invokeCode, completionCode));
    }
    else {
        QVERIFY(itemInCompletionList(invokeCode, completionCode, expectedItem));
    }
}

void PyCompletionTest::testImportCompletion_data()
{
    QTest::addColumn<QString>("invokeCode");
    QTest::addColumn<QString>("completionCode");
    QTest::addColumn<QString>("expectedItem");
Miquel Sabaté's avatar
Miquel Sabaté committed
308

309
    QTest::newRow("same_directory") << "%INVOKE" << "import %CURSOR" << "toplevelmodule";
310 311
//     QTest::newRow("same_directory_beginText") << "%INVOKE" << "import toplevelmo%CURSOR" << "toplevelmodule";
    QTest::newRow("nocompletion") << "%INVOKE" << "from toplevelmodule %CURSOR" << "EMPTY";
312 313 314 315 316 317 318 319 320 321 322 323 324
    QTest::newRow("subdirectory_full") << "%INVOKE" << "import %CURSOR" << "submoduledir";
    QTest::newRow("subdirectory_file") << "%INVOKE" << "import submoduledir.%CURSOR" << "subfile";
    QTest::newRow("subsubdirectory_file") << "%INVOKE" << "import submoduledir.anothersubdir.%CURSOR" << "subsubfile";
    QTest::newRow("subdirectory_from") << "%INVOKE" << "from submoduledir import %CURSOR" << "subfile";
    QTest::newRow("subdirectory_declfromfile") << "%INVOKE" << "from submoduledir.subfile import %CURSOR" << "var_in_subfile";
    QTest::newRow("declaration_from_init_subdir") << "%INVOKE" << "from submoduledir import %CURSOR" << "var_in_sub_init";
    QTest::newRow("class_from_file") << "%INVOKE" << "from toplevelmodule import %CURSOR" << "some_class";
    // TODO implement this or not? It breaks the possibility to easily document modules like PyQT.
    // maybe enable this behaviour only for doc files?
//     QTest::newRow("class_property_not") << "%INVOKE" << "import toplevelmodule.some_class.%CURSOR" << "EMPTY";
    QTest::newRow("class_from_file_in_subdir") << "%INVOKE" << "from submoduledir.subfile import %CURSOR" << "some_subfile_class";
}

325 326 327 328 329 330 331 332 333 334 335 336 337
void PyCompletionTest::testCompletionAfterQuotes()
{
    QFETCH(QString, invokeCode);
    QFETCH(QString, completionCode);
    invokeCode = "testvar = 3\n" + invokeCode;
    QVERIFY( ! completionListIsEmpty(invokeCode, completionCode) );
}


void PyCompletionTest::testCompletionAfterQuotes_data()
{
    QTest::addColumn<QString>("invokeCode");
    QTest::addColumn<QString>("completionCode");
Miquel Sabaté's avatar
Miquel Sabaté committed
338

339 340 341 342 343 344 345 346 347
    QTest::newRow("nothing") << "\n%INVOKE" << "%CURSOR";
    QTest::newRow("sq_in_string") << "\"foo'bar\"\n%INVOKE" << "%CURSOR";
    QTest::newRow("sq_in_sl_comment") << "#foo'bar\n%INVOKE" << "%CURSOR";
    QTest::newRow("sq_in_ml_string") << "\"\"\"foo'bar\n\n' \n'\"\"\"\n%INVOKE" << "%CURSOR";
    QTest::newRow("dq_in_string") << "'foo\"bar'\n%INVOKE" << "%CURSOR";
    QTest::newRow("dq_in_comment") << "# \" foo\n%INVOKE" << "%CURSOR";
    QTest::newRow("dq_in_ml_string") << "\'\'\'foo \n\"\n\n \'\'\'\n%INVOKE" << "%CURSOR";
}

348 349 350
void PyCompletionTest::testNoImplicitMagicFunctions()
{
    QVERIFY(! itemInCompletionList("class my(): pass\nd = my()\n%INVOKE", "d.%CURSOR", "__get__") );
351
    QEXPECT_FAIL("", "Sorting needs to be fixed first before magic function completion can be re-enabled", Continue);
352 353 354
    QVERIFY(itemInCompletionList("class my():\n def __get__(self): pass\nd = my()\n%INVOKE", "d.%CURSOR", "__get__") );
}

Sven Brauch's avatar
Sven Brauch committed
355 356
void PyCompletionTest::testIntegralTypesImmediate()
{
357 358 359
    QFETCH(QString, invokeCode);
    QFETCH(QString, completionCode);
    QFETCH(QString, expectedDeclaration);
Miquel Sabaté's avatar
Miquel Sabaté committed
360

361 362 363 364 365 366 367 368
    QVERIFY(declarationInCompletionList(invokeCode, completionCode, expectedDeclaration));
}

void PyCompletionTest::testIntegralTypesImmediate_data()
{
    QTest::addColumn<QString>("invokeCode");
    QTest::addColumn<QString>("completionCode");
    QTest::addColumn<QString>("expectedDeclaration");
Miquel Sabaté's avatar
Miquel Sabaté committed
369

370 371 372 373 374 375 376 377 378 379 380 381 382
    QTest::newRow("list_syntax") << "[]%INVOKE" << ".%CURSOR" << "append";
    QTest::newRow("dict_syntax") << "{}%INVOKE" << ".%CURSOR" << "items";
    QTest::newRow("string_syntax") << "\"\"%INVOKE" << ".%CURSOR" << "capitalize";
    QTest::newRow("list_class") << "list()%INVOKE" << ".%CURSOR" << "append";
    QTest::newRow("dict_class") << "dict()%INVOKE" << ".%CURSOR" << "items";
    QTest::newRow("string_class") << "str()%INVOKE" << ".%CURSOR" << "capitalize";
}

void PyCompletionTest::testIntegralExpressionsDifferentContexts()
{
    QFETCH(QString, invokeCode);
    QFETCH(QString, completionCode);
    QFETCH(QString, expectedDeclaration);
Miquel Sabaté's avatar
Miquel Sabaté committed
383

384 385 386 387 388 389 390 391
    QVERIFY(declarationInCompletionList(invokeCode, completionCode, expectedDeclaration));
}

void PyCompletionTest::testIntegralExpressionsDifferentContexts_data()
{
    QTest::addColumn<QString>("invokeCode");
    QTest::addColumn<QString>("completionCode");
    QTest::addColumn<QString>("expectedDeclaration");
Miquel Sabaté's avatar
Miquel Sabaté committed
392

393 394 395 396 397 398
    QTest::newRow("function_call") << "foo([]%INVOKE)" << ".%CURSOR" << "append";
    QTest::newRow("function_call_multi") << "foo(bar(baz(bang([]%INVOKE))))" << ".%CURSOR" << "append";
    QTest::newRow("empty_list") << "[[]%INVOKE]" << ".%CURSOR" << "append";
    QTest::newRow("list") << "[1, 2, 3, 4, 5, []%INVOKE]" << ".%CURSOR" << "append";
    QTest::newRow("list_with_fancy_string") << "[\"FooFObar\\\", 3)\", []%INVOKE]" << ".%CURSOR" << "append";
    QTest::newRow("empty_dict") << "{[]%INVOKE}" << ".%CURSOR" << "append";
399
    QTest::newRow("print_stmt") << "%INVOKE" << "print([].%CURSOR" << "append";
400 401
}

402 403 404
void PyCompletionTest::testIgnoreCommentSignsInStringLiterals()
{
    QVERIFY( ! completionListIsEmpty("'#'%INVOKE", ".%CURSOR") );
405 406
    QVERIFY( ! completionListIsEmpty("def addEntry(self,array):\n"
                                     "  \"\"\"\"some comment\"\"\"\n  %INVOKE", "%CURSOR") );
407 408
}

409 410 411 412
void PyCompletionTest::testNoCompletionInCommentsOrStrings()
{
    QFETCH(QString, invokeCode);
    QFETCH(QString, completionCode);
Miquel Sabaté's avatar
Miquel Sabaté committed
413

Sven Brauch's avatar
Sven Brauch committed
414
    QVERIFY(! declarationInCompletionList(invokeCode, completionCode, "append"));
415 416 417 418 419 420
}

void PyCompletionTest::testNoCompletionInCommentsOrStrings_data()
{
    QTest::addColumn<QString>("invokeCode");
    QTest::addColumn<QString>("completionCode");
Miquel Sabaté's avatar
Miquel Sabaté committed
421

422
    QTest::newRow("single_comment") << "# []%INVOKE" << ".%CURSOR";
423
    QTest::newRow("single_comment_local") << "local=3\n# %INVOKE" << "%CURSOR";
424 425 426 427 428 429
    QTest::newRow("stringDQ") << "\"[]%INVOKE\"" << ".%CURSOR";
    QTest::newRow("stringSQ") << "\'[]%INVOKE\'" << ".%CURSOR";
    QTest::newRow("multilineDQ") << "\"\"\"[]%INVOKE\"\"\"" << ".%CURSOR";
    QTest::newRow("multilineSQ") << "\'\'\'[]%INVOKE\'\'\'" << ".%CURSOR";
    QTest::newRow("multilineDQ_newlines") << "\"\"\"\n\n[]%INVOKE\n\n\n\"\"\"" << ".%CURSOR";
    QTest::newRow("multilineSQ_newlines") << "\'\'\'\n\n[]%INVOKE\n\n\n\'\'\'" << ".%CURSOR";
430 431
}

432 433 434 435 436 437 438 439 440 441 442
void PyCompletionTest::testImplementMethodCompletion()
{
    QFETCH(QString, invokeCode);
    QFETCH(QString, completionCode);
    QVERIFY(itemInCompletionList(invokeCode, completionCode, "__init__"));
}

void PyCompletionTest::testImplementMethodCompletion_data()
{
    QTest::addColumn<QString>("invokeCode");
    QTest::addColumn<QString>("completionCode");
Miquel Sabaté's avatar
Miquel Sabaté committed
443

444 445
    QTest::newRow("simple_begin") << "class myclass():\n %INVOKE\n pass" << "def %CURSOR";
    QTest::newRow("another_method_before") << "class myclass():\n def some_method(param):pass\n %INVOKE" << "def %CURSOR";
446 447
    QTest::newRow("another_method_before_multiline") << "class myclass():\n def some_method(param):\n  pass\n  pass \n  pass"
                                                        "\n %INVOKE" << "def %CURSOR";
448 449 450
    QTest::newRow("contextskip") << "class myclass():\n def some_method(param):\n  pass\n \n \n \n %INVOKE" << "def %CURSOR";
    QTest::newRow("contextskip2") << "class myclass():\n def some_method(param): pass\n"
                                     " def some_method2(param):\n  pass\n  pass\n %INVOKE" << "\n \n \n def %CURSOR";
451 452
}

453 454 455 456 457
void PyCompletionTest::testAutoBrackets()
{
    QList< CompletionTreeItem* > items = invokeCompletionOn("class Foo:\n @property\n def myprop(self): pass\n"
                                                            "a=Foo()\n%INVOKE", "a.%CURSOR");
    QVERIFY(containsItemForDeclarationNamed(items, "myprop"));
458
    CompletionTreeItem* item = nullptr;
459 460 461 462 463 464 465 466 467 468 469 470
    foreach ( CompletionTreeItem* ptr, items ) {
        if ( ptr->declaration() ) {
            if ( ptr->declaration()->identifier().toString() == "myprop" ) {
                item = ptr;
                break;
            }
        }
    }
    QVERIFY(item);
    KService::Ptr documentService = KService::serviceByDesktopPath("katepart.desktop");
    QVERIFY(documentService);
    KTextEditor::Document* document = documentService->createInstance<KTextEditor::Document>(this);
Sven Brauch's avatar
Sven Brauch committed
471
    auto view = document->createView(nullptr);
472
    QVERIFY(document);
Sven Brauch's avatar
Sven Brauch committed
473
    item->execute(view, KTextEditor::Range(0, 0, 0, 0));
474 475 476
    QCOMPARE(document->text(), QLatin1String("myprop"));
}

477 478
void PyCompletionTest::testExceptionCompletion()
{
479
    QList< CompletionTreeItem* > items = invokeCompletionOn("localvar = 3\nraise %INVOKE", "%CURSOR");
480 481
    QVERIFY(containsItemForDeclarationNamed(items, "Exception"));
    QVERIFY(! containsItemForDeclarationNamed(items, "localvar"));
Miquel Sabaté's avatar
Miquel Sabaté committed
482

483 484 485 486
    items = invokeCompletionOn("localvar = 3\n%INVOKE", "try: pass\nexcept %CURSOR");
    QVERIFY(containsItemForDeclarationNamed(items, "Exception"));
    QVERIFY(! containsItemForDeclarationNamed(items, "localvar"));
}
487

488 489 490
void PyCompletionTest::testGeneratorCompletion()
{
    QVERIFY(itemInCompletionList("%INVOKE", "foobar = [item for %CURSOR", "item in"));
491 492
    QVERIFY(itemInCompletionList("%INVOKE", "foobar = [key, value for %CURSOR", "key, value in"));
    QVERIFY(itemInCompletionList("%INVOKE", "foobar = [str(key + value) for %CURSOR", "key, value in"));
493 494 495 496 497 498 499 500 501
    QVERIFY(itemInCompletionList("%INVOKE\ndec_l8r=3", "foobar = [dec_l8r for %CURSOR", "dec_l8r in"));
}

void PyCompletionTest::testInheritanceCompletion()
{
    QList< CompletionTreeItem* > items = invokeCompletionOn("class parentClass: pass\n%INVOKE", "class childClass(%CURSOR");
    QVERIFY(containsItemForDeclarationNamed(items, "parentClass"));
    items = invokeCompletionOn("class parentClass: pass\nclass childClass(%INVOKE): pass", "%CURSOR");
    QVERIFY(containsItemForDeclarationNamed(items, "parentClass"));
Sven Brauch's avatar
Sven Brauch committed
502
    items = invokeCompletionOn("class parentClass:\n class blubb: pass\nclass childClass(%INVOKE): pass", "parentClass.%CURSOR");
503 504
    QVERIFY(! containsItemForDeclarationNamed(items, "parentClass"));
    QVERIFY(containsItemForDeclarationNamed(items, "blubb"));
505 506
}

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
void PyCompletionTest::testAddImportCompletion()
{
    QFETCH(QString, completionCode);
    QFETCH(QString, invokeCode);
    QFETCH(int, expectedItems);

    QCOMPARE(invokeCompletionOn(completionCode, invokeCode).size(), expectedItems);
}

void PyCompletionTest::testAddImportCompletion_data()
{
    QTest::addColumn<QString>("completionCode");
    QTest::addColumn<QString>("invokeCode");
    QTest::addColumn<int>("expectedItems");

    QTest::newRow("has_entry_when_necessary") << "toplevelmodule%INVOKE" << ".%CURSOR" << 1;
    QTest::newRow("has_no_when_not_necessary") << "toplevelmodule = 3;\ntoplevelmodule%INVOKE" << ".%CURSOR" << 0;
}

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
void PyCompletionTest::testFunctionDeclarationCompletion()
{
    QFETCH(QString, completionCode);
    QFETCH(QString, invokeCode);
    QFETCH(KTextEditor::Range, executeRange);
    QFETCH(QString, expectedReplacement);

    QString documentCode = completionCode;
    documentCode.replace("%INVOKE", invokeCode).replace("%CURSOR", "");

    QString expectedCode = completionCode;
    expectedCode.replace("%INVOKE", expectedReplacement);

    const QList<CompletionTreeItem *> completionItems = invokeCompletionOn(completionCode, invokeCode);

    QVERIFY( ! completionItems.isEmpty() );

    KService::Ptr documentService = KService::serviceByDesktopPath("katepart.desktop");
    QVERIFY(documentService);
    KTextEditor::Document* document = documentService->createInstance<KTextEditor::Document>(this);
    QVERIFY(document);
    document->setText(documentCode);
Miquel Sabaté's avatar
Miquel Sabaté committed
548

Sven Brauch's avatar
Sven Brauch committed
549
    auto view = document->createView(nullptr);
550

Sven Brauch's avatar
Sven Brauch committed
551
    completionItems.first()->execute(view, executeRange);
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
    QCOMPARE(document->text(), expectedCode);
}

void PyCompletionTest::testFunctionDeclarationCompletion_data()
{
    QTest::addColumn<QString>("completionCode");
    QTest::addColumn<QString>("invokeCode");
    QTest::addColumn<KTextEditor::Range>("executeRange");
    QTest::addColumn<QString>("expectedReplacement");

    QTest::newRow("func_decl_no_parens") << "def foo():\n  pass\n%INVOKE" << "foo%CURSOR" << KTextEditor::Range(2, 0, 2, 3)
                                         << "foo()";

    QTest::newRow("func_decl_existing_parens") << "def foo():\n  return 0\nbar = %INVOKE" << "foo%CURSOR()" << KTextEditor::Range(2, 6, 2, 9)
                                           << "foo()";

    QTest::newRow("decorator_no_parens") << "def mydecorator():\n  pass\nclass Foo:\n  %INVOKE\n  def bar():\n    pass" << "@mydecorator%CURSOR" << KTextEditor::Range(3, 3, 3, 15)
                                         << "@mydecorator";

    QTest::newRow("class_name_no_constructor_parens") << "class Foo:\n  pass\nbar = %INVOKE" << "Foo%CURSOR" << KTextEditor::Range(2, 6, 2, 9)
                                                      << "Foo()";

574
    QTest::newRow("class_name_explicit_constructor_parens") << "class Foo:\n  def __init__(self):\n    pass\nbar = %INVOKE" << "Fo%CURSOR"
575 576 577 578
                                                        << KTextEditor::Range(3, 6, 3, 9)
                                                        << "Foo()";
}

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
void PyCompletionTest::testCompletionScopes()
{
    QFETCH(QString, invokeCode);
    QFETCH(QString, completionCode);
    QFETCH(QString, expectedDeclaration);
    QVERIFY(declarationInCompletionList(invokeCode, completionCode, expectedDeclaration));
}

void PyCompletionTest::testCompletionScopes_data()
{
    QTest::addColumn<QString>("invokeCode");
    QTest::addColumn<QString>("completionCode");
    QTest::addColumn<QString>("expectedDeclaration");
    QTest::newRow("class_scope_end_inside") << "class A:\n test1=1\nclass B:\n test2=1\nf = A()\nclass T:\n f = B()\n f%INVOKE" << ".%CURSOR" << "test2";
    QTest::newRow("class_scope_end_outside") << "class A:\n test1=1\nclass B:\n test2=1\nf = A()\nclass T:\n f = B()\nf%INVOKE" << ".%CURSOR" << "test1";
}

596 597 598 599
void PyCompletionTest::testStringFormattingCompletion()
{
    QFETCH(QString, completionCode);
    QFETCH(QString, invokeCode);
600 601
    QFETCH(QString, expectedItem);
    QFETCH(bool, expectedPresent);
602

603
    QCOMPARE(itemInCompletionList(completionCode, invokeCode, expectedItem), expectedPresent);
604 605 606 607 608 609
}

void PyCompletionTest::testStringFormattingCompletion_data()
{
    QTest::addColumn<QString>("completionCode");
    QTest::addColumn<QString>("invokeCode");
610 611 612 613 614 615 616 617 618 619 620
    QTest::addColumn<QString>("expectedItem");
    QTest::addColumn<bool>("expectedPresent");

    QTest::newRow("sq_string") << "'foo %INVOKE'" << "%CURSOR" << "{0}" << true;
    QTest::newRow("dq_string") << "\"foo %INVOKE bar\"" << "%CURSOR" << "{0}" << true;
    QTest::newRow("sq_ml_string") << "'''foo\n\n%INVOKE\nbar'''" << "%CURSOR" << "{0}" << true;
    QTest::newRow("dq_ml_string") << "\"\"\"foo\nbar %INVOKE baz\"\"\"" << "%CURSOR" << "{0}" << true;
    QTest::newRow("auto_id") << "\"foo {0} bar {1} baz %INVOKE\"" << "%CURSOR" << "{2}" << true;

    QTest::newRow("format_suggestions_conversion") << "\"foo {0} bar %INVOKE\"" << "{1}%CURSOR" << "{1!r}" << true;
    QTest::newRow("format_suggestions_spec") << "\"foo {0} bar {1}%INVOKE baz\"" << "{2}%CURSOR" << "{2:%}" << true;
621

622 623 624 625 626
    QTest::newRow("incompatible_suggestions_conversion") << "\"foo %INVOKE bar\"" << "{0:%}%CURSOR" << "{0!s:%}" << false;
    QTest::newRow("incompatible_suggestions_spec") << "\"foo %INVOKE bar\"" << "{0!s}%CURSOR" << "{0!s:%}" << false;

    QTest::newRow("alignment_for_strings") << "\"foo %INVOKE bar\"" << "{0!s}%CURSOR" << "{0!s:^${width}}" << true;
    QTest::newRow("conversion_for_aliged_strings") << "\"foo %INVOKE bar\"" << "{0!s}%CURSOR" << "{0!s:^${width}}" << true;
627 628 629

}

630 631 632 633 634 635 636
void PyCompletionTest::testStringFormatter()
{
    QFETCH(QString, string);
    QFETCH(int, expectedId);
    QFETCH(QList<RangeInString>, expectedVariablePositions);

    StringFormatter f(string);
637

638 639
    int id = f.nextIdentifierId();
    QCOMPARE(id, expectedId);
640

641 642 643 644 645 646 647 648 649 650
    for (int i = 0; i < string.size(); i++) {
        bool expectedInsideVariable = false;
        foreach (RangeInString range, expectedVariablePositions) {
            if (i >= range.beginIndex && i <= range.endIndex) {
                expectedInsideVariable = true;
                break;
            }
        }
        QCOMPARE(f.isInsideReplacementVariable(i), expectedInsideVariable);
    }
651 652
}

653 654 655 656 657 658 659 660
void PyCompletionTest::testStringFormatter_data()
{
    QTest::addColumn<QString>("string");
    QTest::addColumn<int>("expectedId");
    QTest::addColumn<QList<RangeInString> >("expectedVariablePositions");

    QTest::newRow("sl_string") << "\"foo {0} bar {1}\"" << 2
                               << (QList<RangeInString>() << RangeInString(5, 8) << RangeInString(13, 16));
661

662 663 664 665 666 667 668 669 670 671
    QTest::newRow("ml_string") << "\"\"\"foo {0} \n\nbar {1} \n{foo} {2}\nbaz\"\"\"" << 3
                               << (QList<RangeInString>() << RangeInString(7, 10) << RangeInString(17, 20)
                                   << RangeInString(22, 27) << RangeInString(28, 31));

    QTest::newRow("containing_quotes") << "'''foo {0}\nbar\n{1}{0} \\' \\\" \\\" {2} {foo} \n\\'\n {3}baz'''" << 4
                                       << (QList<RangeInString>() << RangeInString(7, 10) << RangeInString(15, 18)
                                           << RangeInString(18, 21) << RangeInString(31, 34) << RangeInString(35, 40)
                                           << RangeInString(46, 49));
}

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
QString repeat_distinct(const QString& code, int count) {
    QString result;
    QString line;
    for ( int i = 0; i < count; i++ ) {
        line = code;
        result.append(line.replace(QString("%X"), QString::number(i)));
    }
    return result;
}

void PyCompletionTest::completionBenchTest()
{
    QFETCH(QString, completionCode);
    QFETCH(QString, invokeCode);

    CompletionParameters data = prepareCompletion(completionCode, invokeCode);
    QBENCHMARK {
        runCompletion(data);
    }
}

void PyCompletionTest::completionBenchTest_data()
{
    QTest::addColumn<QString>("completionCode");
    QTest::addColumn<QString>("invokeCode");

    QTest::newRow("variable_completion") << "a0 = 2\n%INVOKE" << "b = a%CURSOR";
    QTest::newRow("no_items") << "%INVOKE" << "def func(%CURSOR";
    QTest::newRow("function") << "%INVOKE" << "foo(%CURSOR";
    QTest::newRow("deep_function") << "foo(bar(baz(bang([]%INVOKE))))" << ".%CURSOR";
    QTest::newRow("class_completion") << "class my(): pass\nd = my()\n%INVOKE" << "d.%CURSOR";

    QString many_globals = repeat_distinct("a%X=%X\n", 1000);

    QTest::newRow("function_many_globals") << many_globals + "%INVOKE" << "foo(%CURSOR";
    QTest::newRow("variable_completion_many_globals") << many_globals + "%INVOKE" << "b = a%CURSOR";
}

710
}