Esempio n. 1
0
        public void YieldFromExpressionCompletion()
        {
            const string code = @"
def f():
    yield 1
    return 1

def g():
    f().
    yield from f().
    (yield from f()).
";

            using (var view = new PythonEditor(code, PythonLanguageVersion.V35)) {
                AssertUtil.CheckCollection(view.GetCompletionsAfter("f()."),
                                           new[] { "next", "send", "throw" },
                                           new[] { "real", "imag" }
                                           );
                AssertUtil.CheckCollection(view.GetCompletionsAfter("yield from f()."),
                                           new[] { "next", "send", "throw" },
                                           new[] { "real", "imag" }
                                           );
                AssertUtil.CheckCollection(view.GetCompletionsAfter("(yield from f())."),
                                           new[] { "real", "imag" },
                                           new[] { "next", "send", "throw" }
                                           );
            }
        }
Esempio n. 2
0
        public void AwaitExpressionCompletion()
        {
            const string code = @"
async def f():
    return 1

async def g():
    f().
    await f().
    (await f()).";

            using (var view = new PythonEditor(code, PythonLanguageVersion.V35)) {
                AssertUtil.CheckCollection(view.GetCompletionsAfter("f()."),
                                           new[] { "next", "send", "throw" },
                                           new[] { "real", "imag" }
                                           );
                AssertUtil.CheckCollection(view.GetCompletionsAfter("await f()."),
                                           new[] { "next", "send", "throw" },
                                           new[] { "real", "imag" }
                                           );
                AssertUtil.CheckCollection(view.GetCompletionsAfter("(await f())."),
                                           new[] { "real", "imag" },
                                           new[] { "next", "send", "throw" }
                                           );
            }
        }
        public static async Task AssertReferences(Server s, TextDocumentIdentifier document, SourceLocation position, IEnumerable <string> contains, IEnumerable <string> excludes, string expr = null, bool returnDefinition = false)
        {
            var refs = (await s.FindReferences(new ReferencesParams {
                textDocument = document,
                position = position,
                _expr = expr,
                context = new ReferenceContext {
                    includeDeclaration = true,
                    _includeDefinitionRanges = returnDefinition,
                    _includeValues = true
                }
            }));

            IEnumerable <string> set;

            if (returnDefinition)
            {
                set = refs.Select(r => $"{r._kind ?? ReferenceKind.Reference};{r._definitionRange}");
            }
            else
            {
                set = refs.Select(r => $"{r._kind ?? ReferenceKind.Reference};{r.range}");
            }

            AssertUtil.CheckCollection(
                set,
                contains,
                excludes
                );
        }
Esempio n. 4
0
        public void KeywordCompletions()
        {
            var code = "def f():\r\n     \r\n    x = abc, oar, \r\n    pass\r\n#2\r\n";

            using (var view = new PythonEditor(code, version: PythonLanguageVersion.V35)) {
                IEnumerable <string> completionList;
                completionList = view.GetCompletions(code.IndexOfEnd("#2\r\n"));

                // not in a function
                AssertUtil.CheckCollection(completionList,
                                           new[] { "assert", "and", "async" },
                                           new[] { "await", "return", "yield" }
                                           );

                completionList = view.GetCompletions(code.IndexOf("    \r\n") - 2);
                AssertUtil.CheckCollection(completionList,
                                           new[] { "assert", "and", "async", "yield", "return" },
                                           Array.Empty <string>()
                                           );

                completionList = view.GetCompletions(code.IndexOfEnd("oar,"));
                AssertUtil.CheckCollection(completionList,
                                           new[] { "and" },
                                           new[] { "def" }
                                           );
            }
        }
        public void PathEqualityCache()
        {
            var cmp = new PathEqualityComparer();

            var path1 = "C:\\normalized\\path\\";
            var path2 = "c:/normalized/here/../path";

            Assert.AreEqual(0, cmp._compareKeyCache.Count);
            cmp.GetHashCode(path1);
            Assert.AreEqual(1, cmp._compareKeyCache[path1].Accessed);

            cmp.GetHashCode(path2);
            Assert.AreEqual(1, cmp._compareKeyCache[path1].Accessed);
            Assert.AreEqual(2, cmp._compareKeyCache[path2].Accessed);

            cmp.GetHashCode(path1);
            Assert.AreEqual(3, cmp._compareKeyCache[path1].Accessed);
            Assert.AreEqual(2, cmp._compareKeyCache[path2].Accessed);

            foreach (var path_i in Enumerable.Range(0, 100).Select(i => $"C:\\path\\{i}\\here"))
            {
                cmp.GetHashCode(path_i);
                cmp.GetHashCode(path1);
            }

            AssertUtil.CheckCollection(
                cmp._compareKeyCache.Keys,
                new[] { path1 },
                new[] { path2 }
                );
        }
Esempio n. 6
0
        public void ExceptionCompletions()
        {
            using (var vs = new MockVs()) {
                foreach (var ver in new[] { PythonLanguageVersion.V36, PythonLanguageVersion.V27 })
                {
                    foreach (string code in new[] {
                        @"import sys
raise |",
                        @"import sys
raise (|",
                        @"import sys
try:
    pass
except |",
                        @"import sys
try:
    pass
except (|",
                        @"import sys
try:
    pass
except (ValueError, |"
                    })
                    {
                        Console.WriteLine($"{ver}:: {code}");

                        var completionList = GetCompletions(vs, code.IndexOf("|"), code.Replace("|", ""), ver);

                        AssertUtil.CheckCollection(completionList,
                                                   new[] { "Exception", "KeyboardInterrupt", "GeneratorExit", "StopIteration", "SystemExit", "sys", "Warning" },
                                                   new[] { "str", "int" }
                                                   );
                    }

                    foreach (string code in new[] {
                        @"import sys
raise (sys.",
                        @"import sys
try:
    pass
except (sys."
                    })
                    {
                        var completionList = GetCompletions(vs, code.IndexOfEnd("sys."), code, ver);

                        AssertUtil.CheckCollection(
                            completionList,
                            new[] { "modules", "path", "version" },
                            new[] { "Exception", "KeyboardInterrupt", "GeneratorExit", "StopIteration", "SystemExit" }
                            );
                    }
                }
            }
        }
Esempio n. 7
0
        public void ImportPydFromSearchPath()
        {
            var analyzer = new PythonAnalysis("Global|PythonCore|2.7-32");

            analyzer.AddModule("test-module", "from spam import *");
            analyzer.WaitForAnalysis();
            AssertUtil.CheckCollection(analyzer.GetAllNames(), null, new[] { "system", "spam" });

            analyzer.SetSearchPaths(TestData.GetPath("TestData"));
            analyzer.ReanalyzeAll(CancellationTokens.After60s);

            AssertUtil.CheckCollection(analyzer.GetAllNames(), new[] { "system" }, new[] { "spam" });
        }
Esempio n. 8
0
        public void ImportFromSearchPath()
        {
            var analyzer = new PythonAnalysis(PythonLanguageVersion.V35);

            analyzer.AddModule("test-module", "from test_package import *");
            analyzer.WaitForAnalysis();
            AssertUtil.CheckCollection(analyzer.GetAllNames(), null, new[] { "package_method", "package_method_two", "test_package" });

            analyzer.SetSearchPaths(TestData.GetPath("TestData\\AddImport"));
            analyzer.ReanalyzeAll();

            AssertUtil.CheckCollection(analyzer.GetAllNames(), new[] { "package_method", "package_method_two" }, new[] { "test_package" });
        }
        public static async Task AssertSignature(Server s, TextDocumentIdentifier document, SourceLocation position, IEnumerable <string> contains, IEnumerable <string> excludes, string expr = null)
        {
            var sigs = (await s.SignatureHelp(new TextDocumentPositionParams {
                textDocument = document,
                position = position,
                _expr = expr
            })).signatures;

            AssertUtil.CheckCollection(
                sigs.Select(sig => $"{sig.label}({string.Join(",", sig.parameters.Select(p => $"{p.label}:{p._type}={p._defaultValue}"))})"),
                contains,
                excludes
                );
        }
Esempio n. 10
0
 public static async Task AssertCompletion(Server s, TextDocumentIdentifier document, IEnumerable <string> contains, IEnumerable <string> excludes, Position?position = null, CompletionContext?context = null, Func <CompletionItem, string> cmpKey = null, string expr = null)
 {
     cmpKey = cmpKey ?? (c => c.insertText);
     AssertUtil.CheckCollection(
         (await s.Completion(new CompletionParams {
         textDocument = document,
         position = position ?? new Position(),
         context = context,
         _expr = expr
     })).items?.Select(cmpKey),
         contains,
         excludes
         );
 }
Esempio n. 11
0
        public static async Task AssertSignature(Server s, TextDocumentIdentifier document, SourceLocation position, IEnumerable <string> contains, IEnumerable <string> excludes, string expr = null)
        {
            var sigs = (await s.SignatureHelp(new TextDocumentPositionParams {
                textDocument = document,
                position = position,
                _expr = expr
            })).signatures;

            AssertUtil.CheckCollection(
                sigs.Select(sig => sig.label),
                contains,
                excludes
                );
        }
Esempio n. 12
0
        public void ImportPydFromSearchPath()
        {
            PythonTypeDatabase.ExtensionModuleLoader.AlwaysGenerateDb = true;
            try {
                var analyzer = new PythonAnalysis("Global|PythonCore|2.7-32");

                analyzer.AddModule("test-module", "from spam import *");
                analyzer.WaitForAnalysis();
                AssertUtil.CheckCollection(analyzer.GetAllNames(), null, new[] { "system", "spam" });

                analyzer.SetSearchPaths(TestData.GetPath("TestData"));
                analyzer.ReanalyzeAll(CancellationTokens.After60s);

                AssertUtil.CheckCollection(analyzer.GetAllNames(), new[] { "system" }, new[] { "spam" });
            } finally {
                PythonTypeDatabase.ExtensionModuleLoader.AlwaysGenerateDb = false;
            }
        }
Esempio n. 13
0
        private void TestRegexOne(PythonWorkspaceContext workspaceContext, IList <string> includedWorkspaceFilePaths)
        {
            var filteredFilePaths = workspaceContext.EnumerateUserFiles(
                (x) => PythonConstants.TestFileExtensionRegex.IsMatch(PathUtils.GetFileOrDirectoryName(x))
                ).ToList();

            var expectedFiles = new List <string>();

            foreach (var filePath in includedWorkspaceFilePaths)
            {
                var fileName = PathUtils.GetFileOrDirectoryName(filePath).ToLower();

                if ((fileName.EndsWith(".txt") || fileName.EndsWith(".py")))
                {
                    expectedFiles.Add(filePath);
                }
            }

            AssertUtil.CheckCollection(filteredFilePaths, expectedFiles, Enumerable.Empty <string>());
        }
Esempio n. 14
0
        private void TestRegexTwo(PythonWorkspaceContext workspaceContext, IList <string> includedWorkspaceFilePaths)
        {
            var filteredFilePaths = workspaceContext.EnumerateUserFiles(
                (x) => PythonConstants.DefaultTestFileNameRegex.IsMatch(PathUtils.GetFileOrDirectoryName(x))
                ).ToList();

            var expectedFiles = new List <string>();

            foreach (var filePath in includedWorkspaceFilePaths)
            {
                var fileName = PathUtils.GetFileOrDirectoryName(filePath).ToLower();

                if ((fileName.StartsWith("test") && (fileName.EndsWith(".py") || fileName.EndsWith(".txt"))) ||
                    fileName.EndsWith("_test.py") || fileName.EndsWith("_test.txt"))
                {
                    Assert.IsTrue(filteredFilePaths.Remove(filePath));
                }
            }

            AssertUtil.CheckCollection(filteredFilePaths, expectedFiles, Enumerable.Empty <string>());
        }
Esempio n. 15
0
        public async Task LiveShareCallback_Completion()
        {
            var cb = PythonLanguageServiceProviderCallback.CreateTestInstance();

            using (var analyzer = await CreateAnalyzerAsync())
            {
                var t     = analyzer.WaitForNextCompleteAnalysis();
                var entry = await analyzer.AnalyzeFileAsync(TestData.GetPath("TestData", "LiveShare", "module.py"));

                await t;

                cb.SetAnalyzer(entry.DocumentUri, analyzer);

                var res = await cb.RequestAsync(
                    new LS.LspRequest <CompletionParams, CompletionList>(Methods.TextDocumentCompletionName),
                    new CompletionParams
                {
                    TextDocument = new TextDocumentIdentifier {
                        Uri = entry.DocumentUri
                    },
                    Position = new Position {
                        Line = 0, Character = 0
                    },
                    Context = new CompletionContext
                    {
                        TriggerCharacter = "",
                        TriggerKind      = CompletionTriggerKind.Invoked
                    }
                },
                    null,
                    CancellationToken.None
                    );

                AssertUtil.CheckCollection(
                    res.Items.Select(c => c.InsertText),
                    new[] { "MyClass", "my_func", "my_var", "path" },
                    new[] { "os" }
                    );
            }
        }