public async Task FromImport_ModuleAffectsPackage(string appCodeImport)
        {
            var appCode1 = appCodeImport + Environment.NewLine + "sub_package.";
            var appCode2 = appCodeImport + Environment.NewLine + "sub_package.module.";

            var appPath = TestData.GetTestSpecificPath("app.py");
            var root    = Path.GetDirectoryName(appPath);

            await CreateServicesAsync(root, PythonVersions.LatestAvailable3X);

            var rdt = Services.GetService <IRunningDocumentTable>();

            var modulePath = Path.Combine(root, "package", "sub_package", "module.py");

            rdt.OpenDocument(new Uri(modulePath), "X = 42");
            var doc      = rdt.OpenDocument(new Uri(appPath), appCode1);
            var analysis = await doc.GetAnalysisAsync(-1);

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var comps = cs.GetCompletions(analysis, new SourceLocation(2, 13));

            comps.Should().OnlyHaveLabels("module");

            doc.Update(new[] {
                new DocumentChange {
                    InsertedText = appCode2,
                    ReplacedSpan = new SourceSpan(1, 1, 2, 13)
                }
            });

            analysis = await doc.GetAnalysisAsync(-1);

            comps = cs.GetCompletions(analysis, new SourceLocation(2, 21));
            comps.Should().HaveLabels("X");
        }
Ejemplo n.º 2
0
        public async Task ForwardRef()
        {
            const string code     = @"
class D(object):
    def oar(self, x):
        abc = C()
        abc.fob(2)
        a = abc.fob(2.0)
        a.oar(('a', 'b', 'c', 'd'))

class C(object):
    def fob(self, x):
        D().oar('abc')
        D().oar(['a', 'b', 'c'])
        return D()
    def baz(self): pass
";
            var          analysis = await GetAnalysisAsync(code);

            var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);

            var completionInD    = cs.GetCompletions(analysis, new SourceLocation(3, 5));
            var completionInOar  = cs.GetCompletions(analysis, new SourceLocation(5, 9));
            var completionForAbc = cs.GetCompletions(analysis, new SourceLocation(5, 13));

            completionInD.Should().HaveLabels("C", "D", "oar")
            .And.NotContainLabels("a", "abc", "self", "x", "fob", "baz");

            completionInOar.Should().HaveLabels("C", "D", "a", "oar", "abc", "self", "x")
            .And.NotContainLabels("fob", "baz");

            completionForAbc.Should().HaveLabels("baz", "fob");
        }
        public async Task RelativeImportsFromParent()
        {
            const string module2Code = @"from ...package import module1
module1.";

            var appPath = TestData.GetTestSpecificPath("app.py");
            var root    = Path.GetDirectoryName(appPath);

            await CreateServicesAsync(root, PythonVersions.LatestAvailable3X);

            var rdt      = Services.GetService <IRunningDocumentTable>();
            var analyzer = Services.GetService <IPythonAnalyzer>();

            var module1Path = Path.Combine(root, "package", "module1.py");
            var module2Path = Path.Combine(root, "package", "sub_package", "module2.py");

            rdt.OpenDocument(new Uri(module1Path), "X = 42");
            var module2 = rdt.OpenDocument(new Uri(module2Path), module2Code);

            await analyzer.WaitForCompleteAnalysisAsync();

            var analysis = await module2.GetAnalysisAsync(-1);

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var comps = cs.GetCompletions(analysis, new SourceLocation(2, 9));

            comps.Should().HaveLabels("X");
        }
        public async Task SysModuleChain_SingleOpen()
        {
            const string content = @"import module1.mod as mod
mod.";
            await TestData.CreateTestSpecificFileAsync("module1.py", @"import module2 as mod");

            await TestData.CreateTestSpecificFileAsync("module2.py", @"import sys
sys.modules['module1.mod'] = None
VALUE = 42");

            var root = TestData.GetTestSpecificRootUri().AbsolutePath;

            await CreateServicesAsync(root, PythonVersions.LatestAvailable3X);

            var rdt = Services.GetService <IRunningDocumentTable>();

            var doc = rdt.OpenDocument(TestData.GetDefaultModuleUri(), content);
            await doc.GetAstAsync();

            await Services.GetService <IPythonAnalyzer>().WaitForCompleteAnalysisAsync();

            var analysis = await doc.GetAnalysisAsync(-1);

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var comps = cs.GetCompletions(analysis, new SourceLocation(2, 5));

            comps.Should().HaveLabels("VALUE");
        }
Ejemplo n.º 5
0
        public async Task FromPartialName()
        {
            var initPyPath  = TestData.GetTestSpecificUri("package", "__init__.py");
            var module1Path = TestData.GetTestSpecificUri("package", "module1.py");
            var module2Path = TestData.GetTestSpecificUri("package", "sub_package", "module2.py");

            var root = TestData.GetTestSpecificRootUri().AbsolutePath;

            await CreateServicesAsync(root, PythonVersions.LatestAvailable3X);

            var rdt = Services.GetService <IRunningDocumentTable>();

            var module  = rdt.OpenDocument(initPyPath, "answer = 42");
            var module1 = rdt.OpenDocument(module1Path, "from pa");
            var module2 = rdt.OpenDocument(module2Path, "from package.su");

            module1.Interpreter.ModuleResolution.GetOrLoadModule("package");

            await module.GetAnalysisAsync(-1);

            var analysis1 = await module1.GetAnalysisAsync(-1);

            var analysis2 = await module2.GetAnalysisAsync(-1);

            var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);

            var result = cs.GetCompletions(analysis1, new SourceLocation(1, 8));

            result.Should().HaveLabels("package").And.NotContainLabels("module2", "sub_package", "answer");
            result = cs.GetCompletions(analysis2, new SourceLocation(1, 16));
            result.Should().HaveLabels("module1", "sub_package", "answer");
        }
Ejemplo n.º 6
0
        public async Task InitPyVsModuleNameImport_FromRelativeImport()
        {
            const string appCode = @"
from .sub_package import module
from .sub_package.module import submodule
module.
submodule.";

            var appPath      = TestData.GetTestSpecificPath("package", "app.py");
            var modulePath   = TestData.GetTestSpecificPath("package", "sub_package", "module.py");
            var initPyPath   = TestData.GetTestSpecificPath("package", "sub_package", "module", "__init__.py");
            var submoduleUri = TestData.GetTestSpecificUri("package", "sub_package", "module", "submodule.py");

            await CreateServicesAsync(PythonVersions.LatestAvailable3X);

            var rdt = Services.GetService <IRunningDocumentTable>();

            rdt.OpenDocument(new Uri(initPyPath), "Y = 6 * 9");
            rdt.OpenDocument(new Uri(modulePath), "X = 42");
            rdt.OpenDocument(submoduleUri, "Z = 0");

            var doc      = rdt.OpenDocument(new Uri(appPath), appCode);
            var analysis = await doc.GetAnalysisAsync(-1);

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion, Services);
            var comps = cs.GetCompletions(analysis, new SourceLocation(4, 8));

            comps.Should().HaveLabels("Y").And.NotContainLabels("X");

            comps = cs.GetCompletions(analysis, new SourceLocation(5, 11));
            comps.Should().HaveLabels("Z");
        }
Ejemplo n.º 7
0
        public async Task ImportInPackage()
        {
            var module1Path = TestData.GetTestSpecificUri("package", "module1.py");
            var module2Path = TestData.GetTestSpecificUri("package", "module2.py");
            var module3Path = TestData.GetTestSpecificUri("package", "sub_package", "module3.py");

            var root = TestData.GetTestSpecificRootUri().AbsolutePath;

            await CreateServicesAsync(root, PythonVersions.LatestAvailable3X);

            var rdt = Services.GetService <IRunningDocumentTable>();

            var module1 = rdt.OpenDocument(module1Path, "import package.");
            var module2 = rdt.OpenDocument(module2Path, "import package.sub_package.");
            var module3 = rdt.OpenDocument(module3Path, "import package.");

            var analysis1 = await module1.GetAnalysisAsync(-1);

            var analysis2 = await module2.GetAnalysisAsync(-1);

            var analysis3 = await module3.GetAnalysisAsync(-1);

            var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);

            var result = cs.GetCompletions(analysis1, new SourceLocation(1, 16));

            result.Should().OnlyHaveLabels("module2", "sub_package");
            result = cs.GetCompletions(analysis2, new SourceLocation(1, 16));
            result.Should().OnlyHaveLabels("module1", "sub_package");
            result = cs.GetCompletions(analysis2, new SourceLocation(1, 28));
            result.Should().OnlyHaveLabels("module3");
            result = cs.GetCompletions(analysis3, new SourceLocation(1, 16));
            result.Should().OnlyHaveLabels("module1", "module2", "sub_package");
        }
Ejemplo n.º 8
0
        public async Task SysModuleChain()
        {
            const string content1 = @"import module2.mod as mod
mod.";
            const string content2 = @"import module3 as mod";
            const string content3 = @"import sys
sys.modules['module2.mod'] = None
VALUE = 42";

            var uri1 = await TestData.CreateTestSpecificFileAsync("module1.py", content1);

            var uri2 = await TestData.CreateTestSpecificFileAsync("module2.py", content2);

            var uri3 = await TestData.CreateTestSpecificFileAsync("module3.py", content3);

            await CreateServicesAsync(PythonVersions.LatestAvailable3X);

            var rdt      = Services.GetService <IRunningDocumentTable>();
            var analyzer = Services.GetService <IPythonAnalyzer>();

            var doc1 = rdt.OpenDocument(uri1, content1);

            rdt.OpenDocument(uri2, content2);
            rdt.OpenDocument(uri3, content3);
            await analyzer.WaitForCompleteAnalysisAsync();

            var analysis = await doc1.GetAnalysisAsync(-1);

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion, Services);
            var comps = cs.GetCompletions(analysis, new SourceLocation(2, 5));

            comps.Should().HaveLabels("VALUE");
        }
Ejemplo n.º 9
0
        public async Task SecondRootIsPartOfFirstRoot()
        {
            var folder1 = TestData.GetTestSpecificPath("folder");
            var folder2 = TestData.GetTestSpecificPath("folder2");
            var folder3 = TestData.GetTestSpecificPath("src");

            var module1Uri = TestData.GetTestSpecificUri("folder", "module1.py");
            var module2Uri = TestData.GetTestSpecificUri("folder2", "module2.py");
            var appUri     = TestData.GetTestSpecificUri("src", "app.py");

            const string module1Content = @"X = 42";
            const string module2Content = @"Y = 6*9";
            const string appContent     = @"import module1
import module2
module1.
module2.";

            await CreateServicesAsync(PythonVersions.LatestAvailable2X, new[] { folder1, folder2, folder3 });

            var rdt      = Services.GetService <IRunningDocumentTable>();
            var analyzer = Services.GetService <IPythonAnalyzer>();

            rdt.OpenDocument(module1Uri, module1Content);
            rdt.OpenDocument(module2Uri, module2Content);
            var app      = rdt.OpenDocument(appUri, appContent);
            var analysis = await app.GetAnalysisAsync(-1);

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion, Services);
            var comps = cs.GetCompletions(analysis, new SourceLocation(3, 9));

            comps.Should().HaveLabels("X");

            comps = cs.GetCompletions(analysis, new SourceLocation(4, 9));
            comps.Should().HaveLabels("Y");
        }
Ejemplo n.º 10
0
 public Task Execute()
 {
     if (Output.EventError != EventError.Success)
     {
         if (EventCenter.EnabledLog(LogType.Debug))
         {
             EventCenter.Log(LogType.Debug, $"{Input.Token} {EventDispatchProxy.Type.Name} proxy execute {Input.EventPath} error {(string)Output.Data[0]}");
         }
         ENException exception = new ENException((string)Output.Data[0]);
         exception.EventError = Output.EventError;
         CompletionSource.Error(exception);
     }
     else
     {
         if (EventCenter.EnabledLog(LogType.Debug))
         {
             EventCenter.Log(LogType.Debug, $"{Input.Token} {EventDispatchProxy.Type.Name} proxy execute {Input.EventPath} successed!");
         }
         if (Output.Data != null && Output.Data.Length > 0)
         {
             CompletionSource.Success(Output.Data[0]);
         }
         else
         {
             CompletionSource.Success(new object());
         }
     }
     return(Task.CompletedTask);
 }
Ejemplo n.º 11
0
        public async Task GenericAndRegularBases()
        {
            const string code     = @"
from typing import TypeVar, Generic

_T = TypeVar('_T')

class Box(Generic[_T], list):
    def __init__(self, v: _T):
        self.v = v

    def get(self) -> _T:
        return self.v

boxedint = Box(1234)
x = boxedint.

boxedstr = Box('str')
y = boxedstr.
";
            var          analysis = await GetAnalysisAsync(code, PythonVersions.LatestAvailable3X);

            var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);

            var result = cs.GetCompletions(analysis, new SourceLocation(14, 14));

            result.Should().HaveLabels("append", "index");
            result.Should().NotContainLabels("bit_length");

            result = cs.GetCompletions(analysis, new SourceLocation(17, 14));
            result.Should().HaveLabels("append", "index");
            result.Should().NotContainLabels("capitalize");
        }
Ejemplo n.º 12
0
        public async Task InFunctionDefinition_3X()
        {
            var analysis = await GetAnalysisAsync("@dec" + Environment.NewLine + "async   def  f(): pass", PythonVersions.LatestAvailable3X);

            var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);

            var result = cs.GetCompletions(analysis, new SourceLocation(1, 1));

            result.Should().HaveLabels("any");

            result = cs.GetCompletions(analysis, new SourceLocation(1, 2));
            result.Should().HaveLabels("abs").And.NotContainLabels("def");

            result = cs.GetCompletions(analysis, new SourceLocation(2, 1));
            result.Should().HaveLabels("def");

            result = cs.GetCompletions(analysis, new SourceLocation(2, 12));
            result.Should().HaveLabels("def");

            result = cs.GetCompletions(analysis, new SourceLocation(2, 13));
            result.Should().HaveNoCompletion();

            result = cs.GetCompletions(analysis, new SourceLocation(2, 14));
            result.Should().HaveNoCompletion();
        }
Ejemplo n.º 13
0
        public async Task FromDotInImplicitPackage()
        {
            var module1 = TestData.GetTestSpecificUri("package", "module1.py");
            var module2 = TestData.GetTestSpecificUri("package", "module2.py");
            var module3 = TestData.GetTestSpecificUri("package", "sub_package", "module3.py");

            var root = TestData.GetTestSpecificRootUri().AbsolutePath;

            await CreateServicesAsync(root, PythonVersions.LatestAvailable3X);

            var rdt = Services.GetService <IRunningDocumentTable>();

            var module = rdt.OpenDocument(module1, "from .");

            rdt.OpenDocument(module2, string.Empty);
            rdt.OpenDocument(module3, string.Empty);

            var analysis = await module.GetAnalysisAsync(-1);

            var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);

            var result = cs.GetCompletions(analysis, new SourceLocation(1, 7));

            result.Should().OnlyHaveLabels("module2", "sub_package");
        }
Ejemplo n.º 14
0
            public override void Handle(RHost host, Message response)
            {
                response.ExpectArguments(1, 3);
                var firstArg = response[0] as JValue;

                if (firstArg != null && firstArg.Value == null)
                {
                    CompletionSource.TrySetCanceled();
                    return;
                }

                response.ExpectArguments(3);
                var parseStatus = response.GetEnum <RParseStatus>(0, "parseStatus", parseStatusNames);
                var error       = response.GetString(1, "error", allowNull: true);

                REvaluationResult result;

                if (Kind.HasFlag(REvaluationKind.NoResult))
                {
                    result = new REvaluationResult(error, parseStatus);
                }
                else if (Kind.HasFlag(REvaluationKind.RawResult))
                {
                    result = new REvaluationResult(response.Blob, error, parseStatus);
                }
                else
                {
                    result = new REvaluationResult(response[2], error, parseStatus);
                }

                CompletionSource.TrySetResult(result);
            }
Ejemplo n.º 15
0
        public async Task AzureFunctions()
        {
            const string code     = @"
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    name = req.params.
";
            var          analysis = await GetAnalysisAsync(code, PythonVersions.LatestAvailable3X);

            var v = analysis.GlobalScope.Variables["func"];

            v.Should().NotBeNull();
            if (v.Value.GetPythonType <IPythonModule>().ModuleType == ModuleType.Unresolved)
            {
                var ver = analysis.Document.Interpreter.Configuration.Version;
                Assert.Inconclusive(
                    $"'azure.functions' package is not installed for Python {ver}, see https://github.com/Microsoft/python-language-server/issues/462");
            }

            var cs     = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var result = cs.GetCompletions(analysis, new SourceLocation(5, 23));

            result.Should().HaveLabels("get");
            result.Completions.First(x => x.label == "get").Should().HaveDocumentation("dict.get*");
        }
Ejemplo n.º 16
0
 protected override void OnDisappearing()
 {
     if (!valueSelected)
     {
         CompletionSource.TrySetCanceled();
     }
     base.OnDisappearing();
 }
Ejemplo n.º 17
0
 private bool ShouldTriggerRequireIntellisense()
 {
     return(CompletionSource.ShouldTriggerRequireIntellisense(
                _textView.Caret.Position.BufferPosition,
                _classifier,
                false
                ));
 }
Ejemplo n.º 18
0
        public async Task NoCompletionBadImportExpression()
        {
            var analysis = await GetAnalysisAsync("import os,.");

            var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);

            cs.GetCompletions(analysis, new SourceLocation(1, 12)); // Should not crash.
        }
Ejemplo n.º 19
0
        public async Task LoopImports_Variables1()
        {
            const string module1Code = @"
class A1: 
    def M1(self): return 0; pass

from module2 import y3
x = y3.M3()
";
            const string module2Code = @"
from module1 import A1
y1 = A1()
from module3 import A3
y3 = A3()
";
            const string module3Code = @"
class A3:
    def M3(self): return '0'; pass

from module2 import y1
z = y1.M1()
";

            const string appCode    = @"
from module1 import x
from module3 import z

x.
z.";
            var          module1Uri = TestData.GetTestSpecificUri("module1.py");
            var          module2Uri = TestData.GetTestSpecificUri("module2.py");
            var          module3Uri = TestData.GetTestSpecificUri("module3.py");
            var          appUri     = TestData.GetTestSpecificUri("app.py");

            var root = Path.GetDirectoryName(appUri.AbsolutePath);

            await CreateServicesAsync(root, PythonVersions.LatestAvailable3X);

            var rdt      = Services.GetService <IRunningDocumentTable>();
            var analyzer = Services.GetService <IPythonAnalyzer>();

            rdt.OpenDocument(module3Uri, module3Code);
            rdt.OpenDocument(module2Uri, module2Code);
            rdt.OpenDocument(module1Uri, module1Code);

            var app = rdt.OpenDocument(appUri, appCode);
            await analyzer.WaitForCompleteAnalysisAsync();

            var analysis = await app.GetAnalysisAsync(-1);

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion, Services);
            var comps = cs.GetCompletions(analysis, new SourceLocation(5, 3));

            comps.Should().HaveLabels("capitalize");

            comps = cs.GetCompletions(analysis, new SourceLocation(6, 3));
            comps.Should().HaveLabels("bit_length");
        }
Ejemplo n.º 20
0
        public async Task NoCompletionInFStringConstant(string openFString)
        {
            var analysis = await GetAnalysisAsync(openFString);

            var cs     = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var result = cs.GetCompletions(analysis, new SourceLocation(1, 5));

            result.Should().HaveNoCompletion();
        }
Ejemplo n.º 21
0
        public async Task NoCompletionInString(bool is2x)
        {
            var analysis = await GetAnalysisAsync("\"str.\"", is2x?PythonVersions.LatestAvailable2X : PythonVersions.LatestAvailable3X);

            var cs     = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var result = cs.GetCompletions(analysis, new SourceLocation(1, 6));

            result.Should().HaveNoCompletion();
        }
Ejemplo n.º 22
0
        public async Task NoCompletionInComment()
        {
            var analysis = await GetAnalysisAsync("x = 1 #str. more text");

            var cs     = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var result = cs.GetCompletions(analysis, new SourceLocation(1, 12));

            result.Should().HaveNoCompletion();
        }
        public async Task TypingModule()
        {
            var analysis = await GetAnalysisAsync(@"from typing import ");

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var comps = cs.GetCompletions(analysis, new SourceLocation(1, 20));

            comps.Should().HaveLabels("TypeVar", "List", "Dict", "Union");
        }
Ejemplo n.º 24
0
            public async Task <IssuedToken> GetTokenAsync(VssTraceActivity traceActivity)
            {
                IssuedToken token = null;

                try
                {
                    VssHttpEventSource.Log.IssuedTokenAcquiring(traceActivity, this.Provider);
                    if (this.Provider.InvokeRequired)
                    {
                        // Post to the UI thread using the scheduler. This may return a new task object which needs
                        // to be awaited, since once we get to the UI thread there may be nothing to do if someone else
                        // preempts us.

                        // The cancellation token source is used to handle race conditions between scheduling and
                        // waiting for the UI task to begin execution. The callback is responsible for disposing of
                        // the token source, since the thought here is that the callback will run eventually as the
                        // typical reason for not starting execution within the timeout is due to a deadlock with
                        // the scheduler being used.
                        var timerTask          = new TaskCompletionSource <Object>();
                        var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3));
                        timeoutTokenSource.Token.Register(() => timerTask.SetResult(null), false);

                        var uiTask = Task.Factory.StartNew((state) => PostCallback(state, timeoutTokenSource),
                                                           this,
                                                           this.CancellationToken,
                                                           TaskCreationOptions.None,
                                                           this.Provider.Credential.Scheduler).Unwrap();

                        var completedTask = await Task.WhenAny(timerTask.Task, uiTask).ConfigureAwait(false);

                        if (completedTask == uiTask)
                        {
                            token = uiTask.Result;
                        }
                    }
                    else
                    {
                        token = await this.Provider.OnGetTokenAsync(this.FailedToken, this.CancellationToken).ConfigureAwait(false);
                    }

                    CompletionSource.TrySetResult(token);
                    return(token);
                }
                catch (Exception exception)
                {
                    // Mark our completion source as failed so other waiters will get notified in all cases
                    CompletionSource.TrySetException(exception);
                    throw;
                }
                finally
                {
                    this.Provider.CurrentToken = token ?? this.FailedToken;
                    VssHttpEventSource.Log.IssuedTokenAcquired(traceActivity, this.Provider, token);
                }
            }
        public async Task AllComplex(string allCode)
        {
            var module1Code = @"
class A:
    def foo(self):
        pass
    pass

class B:
    def bar(self):
        pass
    pass

class C:
    def baz(self):
        pass
    pass
" + allCode;

            var appCode = @"
from module1 import *

A().
B().
C().
";

            var module1Uri = TestData.GetTestSpecificUri("module1.py");
            var appUri     = TestData.GetTestSpecificUri("app.py");

            var root = Path.GetDirectoryName(appUri.AbsolutePath);

            await CreateServicesAsync(root, PythonVersions.LatestAvailable3X);

            var rdt      = Services.GetService <IRunningDocumentTable>();
            var analyzer = Services.GetService <IPythonAnalyzer>();

            rdt.OpenDocument(module1Uri, module1Code);

            var app = rdt.OpenDocument(appUri, appCode);
            await analyzer.WaitForCompleteAnalysisAsync();

            var analysis = await app.GetAnalysisAsync(-1);

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var comps = cs.GetCompletions(analysis, new SourceLocation(4, 5));

            comps.Should().HaveLabels("foo");

            comps = cs.GetCompletions(analysis, new SourceLocation(5, 5));
            comps.Should().HaveLabels("bar");

            comps = cs.GetCompletions(analysis, new SourceLocation(6, 5));
            comps.Should().NotContainLabels("baz");
        }
        public async Task UserSearchPathsInsideWorkspace()
        {
            var          folder1          = TestData.GetTestSpecificPath("folder1");
            var          folder2          = TestData.GetTestSpecificPath("folder2");
            var          packageInFolder1 = Path.Combine(folder1, "package");
            var          packageInFolder2 = Path.Combine(folder2, "package");
            var          module1Path      = Path.Combine(packageInFolder1, "module1.py");
            var          module2Path      = Path.Combine(packageInFolder2, "module2.py");
            const string module1Content   = @"class A():
    @staticmethod
    def method1():
        pass";
            const string module2Content   = @"class B():
    @staticmethod
    def method2():
        pass";
            const string mainContent      = @"from package import module1 as mod1, module2 as mod2
mod1.
mod2.
mod1.A.
mod2.B.";
            var          root             = Path.GetDirectoryName(folder1);

            await CreateServicesAsync(root, PythonVersions.LatestAvailable3X);

            var rdt         = Services.GetService <IRunningDocumentTable>();
            var analyzer    = Services.GetService <IPythonAnalyzer>();
            var interpreter = Services.GetService <IPythonInterpreter>();

            interpreter.ModuleResolution.SetUserSearchPaths(new[] { folder1, folder2 });

            rdt.OpenDocument(new Uri(module1Path), module1Content);
            rdt.OpenDocument(new Uri(module2Path), module2Content);

            var mainPath = Path.Combine(root, "main.py");
            var doc      = rdt.OpenDocument(new Uri(mainPath), mainContent);
            await analyzer.WaitForCompleteAnalysisAsync();

            var analysis = await doc.GetAnalysisAsync(-1);

            var cs    = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var comps = cs.GetCompletions(analysis, new SourceLocation(2, 6));

            comps.Should().HaveLabels("A").And.NotContainLabels("B");

            comps = cs.GetCompletions(analysis, new SourceLocation(3, 6));
            comps.Should().HaveLabels("B").And.NotContainLabels("A");

            comps = cs.GetCompletions(analysis, new SourceLocation(4, 8));
            comps.Should().HaveLabels("method1");

            comps = cs.GetCompletions(analysis, new SourceLocation(5, 8));
            comps.Should().HaveLabels("method2");
        }
Ejemplo n.º 27
0
        public async Task MarkupKindValid()
        {
            var analysis = await GetAnalysisAsync("import sys\nsys.\n");

            var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);

            var result = cs.GetCompletions(analysis, new SourceLocation(2, 5));

            result.Completions?.Select(i => i.documentation.kind)
            .Should().NotBeEmpty().And.BeSubsetOf(new[] { MarkupKind.PlainText, MarkupKind.Markdown });
        }
Ejemplo n.º 28
0
        public async Task NoCompletionForCurrentModuleName(bool empty)
        {
            var modulePath = TestData.GetNextModulePath();
            var code       = empty ? string.Empty : $"{Path.GetFileNameWithoutExtension(modulePath)}.";
            var analysis   = await GetAnalysisAsync(code, PythonVersions.LatestAvailable3X, null, modulePath);

            var cs     = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);
            var result = cs.GetCompletions(analysis, new SourceLocation(1, code.Length + 1));

            result.Should().NotContainLabels(analysis.Document.Name);
        }
Ejemplo n.º 29
0
        protected virtual void CancelCompletionSourceIfNecessary()
        {
            var task = CompletionSource?.Task;

            if (task == null || task.IsFaulted || task.IsCompleted || task.IsCanceled)
            {
                return;
            }

            CompletionSource.SetCanceled();
        }
Ejemplo n.º 30
0
        public async Task FromDotInRoot()
        {
            const string code     = "from .";
            var          analysis = await GetAnalysisAsync(code, PythonVersions.LatestAvailable3X);

            var cs = new CompletionSource(new PlainTextDocumentationSource(), ServerSettings.completion);

            var result = cs.GetCompletions(analysis, new SourceLocation(1, 7));

            result.Should().HaveNoCompletion();
        }