Beispiel #1
0
        private static void TestQuickInfo(MockVs vs, string code, int start, int end, params string[] expected)
        {
            using (var view = new PythonEditor(code, vs: vs)) {
                var snapshot = view.CurrentSnapshot;

                for (int i = start; i < end; i++)
                {
                    var analysis = snapshot.AnalyzeExpression(
                        vs.ServiceProvider,
                        snapshot.CreateTrackingSpan(i, i == snapshot.Length ? 0 : 1, SpanTrackingMode.EdgeInclusive),
                        false
                        );

                    List <object> quickInfo = new List <object>();
                    ITrackingSpan span;
                    QuickInfoSource.AugmentQuickInfoWorker(
                        analysis,
                        quickInfo,
                        out span
                        );

                    Assert.AreEqual(expected.Length, quickInfo.Count);
                    for (int j = 0; j < expected.Length; j++)
                    {
                        Assert.AreEqual(expected[j], quickInfo[j]);
                    }
                }
            }
        }
        public void DisableAutoCompletions()
        {
            using (var vs = new MockVs()) {
                var options = vs.GetPyService().AdvancedOptions;
                var oldALM  = options.AutoListMembers;
                var oldALI  = options.AutoListIdentifiers;
                options.AutoListMembers     = false;
                options.AutoListIdentifiers = false;
                vs.OnDispose(() => {
                    options.AutoListMembers     = oldALM;
                    options.AutoListIdentifiers = oldALI;
                });

                var view = CreateViewAndAnalyze(vs);

                foreach (var t in new[] { "a", "a.", "import " })
                {
                    Console.WriteLine("Typed " + t);
                    view.Type(t);

                    view.AssertNoIntellisenseSession();

                    view.Clear();
                }
            }
        }
Beispiel #3
0
 public void FromOSPathImportCompletions3x()
 {
     using (var vs = new MockVs()) {
         var factory = vs.Invoke(() => vs.GetPyService().InterpreterRegistryService.Interpreters.LastOrDefault(p => p.Configuration.Version.Major == 3));
         OSPathImportTest(vs, factory);
     }
 }
Beispiel #4
0
        public static PythonToolsService GetPyService(this MockVs session)
        {
            var service = session.ServiceProvider.GetPythonToolsService();

            Assert.IsNotNull(service, "PythonToolsService is unavailable");
            return(service);
        }
Beispiel #5
0
        private static void OSPathImportTest(MockVs vs, MockCompletionDB db)
        {
            var code = "from ";

            AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), "os", "sys");

            code = "from o";
            var completions = GetCompletions(vs, -1, code, db.Factory);

            AssertUtil.ContainsAtLeast(completions, "os");
            AssertUtil.DoesntContain(completions, "sys");

            code = "from os ";
            AssertUtil.ContainsExactly(GetCompletions(vs, -1, code, db.Factory), "import");

            code = "from os import";
            AssertUtil.ContainsExactly(GetCompletions(vs, -1, code, db.Factory), "import");

            code = "from os import ";
            AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), "path");

            code = "from os.";
            AssertUtil.ContainsExactly(GetCompletions(vs, -1, code, db.Factory), "path");

            code = "from os.path import ";
            AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), "abspath", "relpath");

            var allNames = new HashSet <string>();

            allNames.UnionWith(GetCompletions(vs, -1, "from ntpath import ", db.Factory));
            allNames.UnionWith(GetCompletions(vs, -1, "from posixpath import ", db.Factory));

            code = "from os.path import ";
            AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), allNames);
        }
Beispiel #6
0
 public void FromOSPathImportCompletions3x()
 {
     using (var vs = new MockVs())
         using (var db = MockCompletionDB.Create(PythonLanguageVersion.V33, "os", "ntpath", "posixpath", "os2emxpath")) {
             OSPathImportTest(vs, db);
         }
 }
Beispiel #7
0
        public void GotoDefinition()
        {
            using (var vs = new MockVs()) {
                string code = @"
class C:
    def fff(self): pass

C().fff";

                //var emptyAnalysis = AnalyzeExpression(0, code);
                //AreEqual(emptyAnalysis.Expression, "");

                for (int i = -1; i >= -3; i--)
                {
                    var analysis = AnalyzeExpression(vs, i, code);
                    Assert.AreEqual("C().fff", analysis.Expression);
                }

                var classAnalysis = AnalyzeExpression(vs, -6, code);
                Assert.AreEqual("C()", classAnalysis.Expression);

                var defAnalysis = AnalyzeExpression(vs, code.IndexOf("def fff") + 4, code);
                Assert.AreEqual("fff", defAnalysis.Expression);
            }
        }
Beispiel #8
0
        public void OverridesWithMismatchedAnalysis()
        {
            // Here we create a buffer and analyze. We then add some newlines
            // and a def, expecting completions from A (int). Because the def
            // has moved down into class B, GetCompletions() rolls it back
            // to find out where in the analysis to look - without this, we
            // would get completions for dict rather than int.
            var code = @"
class A(int):
    pass

class B(dict):
    pass

";

            using (var vs = new MockVs()) {
                var editText    = "\r\n\r\n\r\n    def ";
                var editInsert  = code.IndexOf("pass") + 4;
                var completions = EditAndGetCompletions(vs, code, editText, editInsert, "def ");

                AssertUtil.ContainsAtLeast(completions, "bit_length", "conjugate");
                AssertUtil.DoesntContain(completions, "keys");

                editText    = "\r\n\r\n\r\n\r\n\r\n    def ";
                editInsert  = code.IndexOf("pass", editInsert) + 4;
                completions = EditAndGetCompletions(vs, code, editText, editInsert, "def ");

                AssertUtil.ContainsAtLeast(completions, "keys", "__contains__");
                AssertUtil.DoesntContain(completions, "bit_length");
            }
        }
        public void TabCommits()
        {
            using (var vs = new MockVs()) {
                var  opts   = vs.GetPyService().AdvancedOptions;
                bool oldECI = opts.EnterCommitsIntellisense;
                bool oldALM = opts.AutoListMembers;
                bool oldALI = opts.AutoListIdentifiers;
                bool oldHAM = opts.HideAdvancedMembers;
                opts.EnterCommitsIntellisense = false;
                opts.AutoListMembers          = true;
                opts.AutoListIdentifiers      = false;
                opts.HideAdvancedMembers      = false;
                vs.OnDispose(() => {
                    opts.EnterCommitsIntellisense = oldECI;
                    opts.AutoListMembers          = oldALM;
                    opts.AutoListIdentifiers      = oldALI;
                    opts.HideAdvancedMembers      = oldHAM;
                });

                var view = CreateViewAndAnalyze(vs);
                view.Type("min.");

                var session = view.TopSession as ICompletionSession;
                Console.WriteLine(string.Join("\n", session.Completions()));
                view.Type("class\t");

                Assert.AreEqual("min.__class__", view.Text);
            }
        }
Beispiel #10
0
        private static IEnumerable <string> EditAndGetCompletions(
            MockVs vs,
            string code,
            string editText,
            int editInsert,
            string completeAfter,
            PythonLanguageVersion version = PythonLanguageVersion.V27
            )
        {
            using (var view = new PythonEditor(code, version, vs)) {
                view.AdvancedOptions.HideAdvancedMembers = false;

                var snapshot = view.CurrentSnapshot;
                using (var evt = view.AnalysisCompleteEvent) {
                    view.View.MoveCaret(new SnapshotPoint(snapshot, editInsert));
                    view.Type(editText);

                    if (!evt.WaitOne(10000))
                    {
                        Assert.Fail("Failed to wait for new analysis");
                    }
                }

                var newSnapshot = view.CurrentSnapshot;
                Assert.AreNotSame(snapshot, newSnapshot);

                return(view.GetCompletionsAfter(completeAfter));
            }
        }
        public void EnterCommitsCompleteNoNewLine()
        {
            using (var vs = new MockVs()) {
                var  opts   = vs.GetPyService().AdvancedOptions;
                bool oldANL = opts.AddNewLineAtEndOfFullyTypedWord;
                bool oldALM = opts.AutoListMembers;
                bool oldALI = opts.AutoListIdentifiers;
                bool oldHAM = opts.HideAdvancedMembers;
                opts.AddNewLineAtEndOfFullyTypedWord = true;
                opts.AutoListMembers     = true;
                opts.AutoListIdentifiers = false;
                opts.HideAdvancedMembers = false;
                vs.OnDispose(() => {
                    opts.AddNewLineAtEndOfFullyTypedWord = oldANL;
                    opts.AutoListMembers     = oldALM;
                    opts.AutoListIdentifiers = oldALI;
                    opts.HideAdvancedMembers = oldHAM;
                });
                var view = CreateViewAndAnalyze(vs);
                view.Type("min.");

                var session = view.TopSession as ICompletionSession;

                view.Type("__class__\r");

                Assert.AreEqual("min.__class__\r\n", view.Text);
            }
        }
        private void AutoListTest(string code, PythonLanguageVersion version, params int[] triggerAtIndex)
        {
            using (var vs = new MockVs()) {
                var interpreterService = vs.GetPyService()._interpreterOptionsService;
                var oldDefault         = interpreterService.DefaultInterpreter;
                interpreterService.DefaultInterpreter = interpreterService.Interpreters
                                                        .First(i => i.Configuration.Version == version.ToVersion());
                vs.OnDispose(() => interpreterService.DefaultInterpreter = oldDefault);

                var options = vs.GetPyService().AdvancedOptions;
                var oldALI  = options.AutoListIdentifiers;
                var oldALM  = options.AutoListMembers;
                options.AutoListIdentifiers = true;
                options.AutoListMembers     = true;
                vs.OnDispose(() => {
                    options.AutoListIdentifiers = oldALI;
                    options.AutoListMembers     = oldALM;
                });

                var view = CreateViewAndAnalyze(vs);

                int    lastStart = 0;
                string text;
                foreach (var _i in triggerAtIndex)
                {
                    bool expectCompletions = _i >= 0;
                    int  expected          = _i > 0 ? _i : -_i;

                    text = code.Substring(lastStart, expected - lastStart);
                    Console.WriteLine("Typing '{0}' [{1}, {2})", text, lastStart, expected);
                    view.Type(text);

                    view.AssertNoIntellisenseSession();
                    lastStart = expected;

                    if (expectCompletions)
                    {
                        text = code.Substring(expected, 1);
                        Console.WriteLine("Typing '{0}' [{1}, {2}) and expect completions", text, expected, expected + 1);
                        view.Type(text);

                        using (var sh = view.WaitForSession <ICompletionSession>()) {
                            sh.Session.Dismiss();
                        }

                        lastStart = expected + 1;
                    }
                }
                text = code.Substring(lastStart);
                if (!string.IsNullOrEmpty(text))
                {
                    Console.WriteLine("Typing '{0}' [{1}, {2})", text, lastStart, code.Length);
                    view.Type(text);

                    view.AssertNoIntellisenseSession();
                }
            }
        }
Beispiel #13
0
 private static void AnalyzeAndValidateExpression(MockVs vs, int start, int charCount, string code, string expectedExpr)
 {
     // We check charCount + 1 positions to ensure that go to definition
     // works when caret is on the left AND right of identifier (and in between)
     for (int i = 0; i <= charCount; i++)
     {
         var defAnalysis = AnalyzeExpression(vs, start + i, code);
         Assert.AreEqual(expectedExpr, defAnalysis?.Expression);
     }
 }
Beispiel #14
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" }
                            );
                    }
                }
            }
        }
Beispiel #15
0
        private static void TestSignature(MockVs vs, int location, string sourceCode, string expectedExpression, int paramIndex, PythonLanguageVersion version, bool analyze, out SignatureAnalysis sigs)
        {
            if (location < 0)
            {
                location = sourceCode.Length + location;
            }

            sigs = GetSignatureAnalysis(vs, location, sourceCode, version);
            Assert.AreEqual(expectedExpression, sigs.Text, sourceCode);
            Assert.AreEqual(paramIndex, sigs.ParameterIndex, sourceCode);
        }
Beispiel #16
0
        private static SignatureAnalysis GetSignatureAnalysis(MockVs vs, int index, string code, PythonLanguageVersion version = PythonLanguageVersion.V27)
        {
            using (var view = new PythonEditor(code, version, vs)) {
                var snapshot = view.CurrentSnapshot;

                return(snapshot.GetSignatures(
                           vs.ServiceProvider,
                           snapshot.CreateTrackingSpan(index, 1, SpanTrackingMode.EdgeInclusive)
                           ));
            }
        }
Beispiel #17
0
        public void SignatureHelpStarArgs()
        {
            SignatureAnalysis sigResult;

            using (var vs = new MockVs()) {
                TestSignature(vs, -1, @"def f(a, *b, c=None): pass
f(1, 2, 3, 4,", "f", 4, PythonLanguageVersion.V27, true, out sigResult);
                Assert.IsTrue(sigResult.Signatures.Count >= 1, "No signature analysis results");
                Assert.AreEqual("*b", sigResult.Signatures[0].CurrentParameter.Name);
            }
        }
Beispiel #18
0
        public void QuickInfo()
        {
            string code = @"
x = ""ABCDEFGHIJKLMNOPQRSTUVWYXZ""
cls._parse_block(ast.expr)


f(a,
(b, c, d),
e)


def f():
    """"""helpful information
    
    
""""""

while True:
    pass

lambda larg1, larg2: None";


            using (var vs = new MockVs()) {
                // we get the appropriate subexpression
                TestQuickInfo(vs, code, code.IndexOf("cls."), code.IndexOf("cls.") + 4, "cls: <unknown type>");
                TestQuickInfo(vs, code, code.IndexOf("cls.") + 4 + 1, code.IndexOf("cls.") + 4 + 1 + 11, "cls._parse_block: <unknown type>");
                TestQuickInfo(vs, code, code.IndexOf("cls.") + 4 + 1 + 11 + 1, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 4, "ast: <unknown type>");
                TestQuickInfo(vs, code, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 4 + 1, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 4 + 1 + 3, "ast.expr: <unknown type>");
                TestQuickInfo(vs, code, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 4 + 1 + 3 + 1, code.IndexOf("cls.") + 4 + 1 + 11 + 1 + 5 + 3 + 1 + 1, "cls._parse_block(ast.expr): <unknown type>");

                // the whole string shows up in quick info
                TestQuickInfo(vs, code, code.IndexOf("x = ") + 4, code.IndexOf("x = ") + 4 + 28, "\"ABCDEFGHIJKLMNOPQRSTUVWYXZ\": str");

                // trailing new lines don't show up in quick info
                TestQuickInfo(vs, code, code.IndexOf("def f") + 4, code.IndexOf("def f") + 5, "f: def f()\r\nhelpful information");

                // keywords don't show up in quick info
                TestQuickInfo(vs, code, code.IndexOf("while True:"), code.IndexOf("while True:") + 5);

                // 'lambda' keyword doesn't show up in quick info
                TestQuickInfo(vs, code, code.IndexOf("lambda"), code.IndexOf("lambda") + 6);
                // but its arguments do
                TestQuickInfo(vs, code, code.IndexOf("larg1"), code.IndexOf("larg1") + 5, "larg1: <unknown type>");
                TestQuickInfo(vs, code, code.IndexOf("larg2"), code.IndexOf("larg2") + 5, "larg2: <unknown type>");

                // multiline function, hover at the close paren
                TestQuickInfo(vs, code, code.IndexOf("e)") + 1, code.IndexOf("e)") + 2, @"f(a,
(b, c, d),
e): <unknown type>");
            }
        }
Beispiel #19
0
        public void CompletionWithLongDocString()
        {
            using (var vs = new MockVs()) {
                var    docString = GenerateText(100, 72, "    ").ToArray();
                string code      = @"
def func(a):
    '''" + string.Join(Environment.NewLine, docString) + @"'''
    pass

";

                // Because there is an extra line added for the Quick Info we only
                // want the first 29 lines of the docstring. For signature docs,
                // we'll cut to 15 lines.
                var expected1 = string.Join(Environment.NewLine, docString.Take(29)) + Environment.NewLine + "...";
                var expected2 = string.Join(Environment.NewLine, docString.Take(15)).TrimStart() + Environment.NewLine + "...";

                using (var view = new PythonEditor(code)) {
                    TestQuickInfo(view, code.IndexOf("func"), code.IndexOf("func") + 4, "func: def func(a)\r\n" + expected1);

                    SignatureAnalysis sigs;
                    view.Text += "func(";
                    TestSignature(view, -1, "func", 0, out sigs);
                    Assert.AreEqual(1, sigs.Signatures.Count);
                    Assert.AreEqual(1, sigs.Signatures[0].Parameters.Count);
                    Assert.AreEqual(expected2, sigs.Signatures[0].Documentation);
                }

                docString = GenerateText(100, 250, "    ").ToArray();
                code      = @"
def func(a):
    '''" + string.Join(Environment.NewLine, docString) + @"'''
    pass

";

                using (var view = new PythonEditor(code)) {
                    // The long lines cause us to truncate sooner.
                    expected1 = string.Join(Environment.NewLine, docString.Take(15)) + Environment.NewLine + "...";
                    expected2 = string.Join(Environment.NewLine, docString.Take(8)).TrimStart() + Environment.NewLine + "...";

                    TestQuickInfo(view, code.IndexOf("func"), code.IndexOf("func") + 4, "func: def func(a)\r\n" + expected1);

                    SignatureAnalysis sigs;
                    view.Text += "func(";
                    TestSignature(view, -1, "func", 0, out sigs);
                    Assert.AreEqual(1, sigs.Signatures.Count);
                    Assert.AreEqual(1, sigs.Signatures[0].Parameters.Count);
                    Assert.AreEqual(expected2, sigs.Signatures[0].Documentation);
                }
            }
        }
Beispiel #20
0
        public static IVisualStudioInstance ToMockVs(this SolutionFile self)
        {
            MockVs vs = new MockVs();

            vs.Invoke(() =>
            {
                // HACK: The default targets files require a function that we don't provide
                // The tests are mostly still broken, but they get further now. We should probably
                // move them into UI tests, as we can't emulate the MSBuild environment well enough
                // to open projects from here.
                Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.SetGlobalProperty("NugetRestoreTargets", "false");
                ErrorHandler.ThrowOnFailure(vs.Solution.OpenSolutionFile(0, self.Filename));
            });
            return(vs);
        }
Beispiel #21
0
        private static ExpressionAnalysis AnalyzeExpression(MockVs vs, int location, string code, PythonLanguageVersion version = PythonLanguageVersion.V27)
        {
            if (location < 0)
            {
                location += code.Length + 1;
            }

            using (var view = new PythonEditor(code, version, vs)) {
                var snapshot = view.CurrentSnapshot;
                return(vs.InvokeTask(() => view.Analyzer.AnalyzeExpressionAsync(
                                         (AnalysisEntry)view.GetAnalysisEntry(),
                                         new SnapshotPoint(snapshot, location)
                                         )));
            }
        }
        public void EnterDismisses()
        {
            var vs = new MockVs();

            vs.GetPyService().AdvancedOptions.EnterCommitsIntellisense = false;
            vs.GetPyService().AdvancedOptions.AutoListMembers = true;
            var view = CreateViewAndAnalyze(vs);

            view.Type("min.");

            var session = view.TopSession as ICompletionSession;

            view.Type("class\r");

            Assert.AreEqual("min.class\r\n", view.Text);
        }
Beispiel #23
0
        private static ExpressionAnalysis AnalyzeExpression(MockVs vs, int location, string code, PythonLanguageVersion version = PythonLanguageVersion.V27)
        {
            if (location < 0)
            {
                location += code.Length + 1;
            }

            using (var view = new PythonEditor(code, version, vs)) {
                var snapshot = view.CurrentSnapshot;
                return(snapshot.AnalyzeExpression(
                           vs.ServiceProvider,
                           snapshot.CreateTrackingSpan(location, location < snapshot.Length ? 1 : 0, SpanTrackingMode.EdgeInclusive),
                           false
                           ));
            }
        }
Beispiel #24
0
        public void CtrlSpaceAfterKeyword()
        {
            // http://pytools.codeplex.com/workitem/560
            string code = @"
def h():
    return 

print 

";

            using (var vs = new MockVs()) {
                AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("return "), code), "any");
                AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("print "), code), "any");
            }
        }
Beispiel #25
0
        public void CtrlSpaceAfterNumber()
        {
            // http://pytools.codeplex.com/workitem/2323
            string code = @"
2
2.
2..
2.0.
";

            using (var vs = new MockVs()) {
                AssertUtil.ContainsExactly(GetCompletions(vs, code.IndexOfEnd("2"), code));
                AssertUtil.ContainsExactly(GetCompletions(vs, code.IndexOfEnd("2."), code));
                AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("2.."), code), "real", "imag");
                AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("2.0."), code), "real", "imag");
            }
        }
Beispiel #26
0
        public void GotoDefinition()
        {
            using (var vs = new MockVs()) {
                string code = @"
class C:
    def fff(self): pass
i=1+2
C().fff";

                AnalyzeAndValidateExpression(vs, code.IndexOf("fff("), 3, code, "fff");
                AnalyzeAndValidateExpression(vs, code.IndexOf("self)"), 4, code, "self");
                AnalyzeAndValidateExpression(vs, code.IndexOf("C:"), 1, code, "C");
                AnalyzeAndValidateExpression(vs, code.IndexOf("1"), 1, code, "1");
                AnalyzeAndValidateExpression(vs, code.IndexOf("2"), 1, code, "2");
                AnalyzeAndValidateExpression(vs, code.IndexOf("C()."), 1, code, "C");
                AnalyzeAndValidateExpression(vs, code.IndexOf(".fff") + 2, 2, code, "C().fff");
            }
        }
Beispiel #27
0
            public ClassifierHelper(string code, PythonLanguageVersion version)
            {
                _vs = new MockVs();

                var reg       = _vs.ContentTypeRegistry;
                var providers = _vs.ComponentModel.GetExtensions <IClassifierProvider>().ToArray();

                _provider1 = providers.OfType <PythonClassifierProvider>().Single();
                _provider2 = providers.OfType <PythonAnalysisClassifierProvider>().Single();

                var factory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());

                _analyzer = new VsProjectAnalyzer(_vs.ServiceProvider, factory, new[] { factory });

                _view = _vs.CreateTextView(PythonCoreConstants.ContentType, code, v => {
                    v.TextView.TextBuffer.Properties.AddProperty(typeof(VsProjectAnalyzer), _analyzer);
                });
            }
        private static MockVsTextView CreateViewAndAnalyze(MockVs vs = null)
        {
            if (vs == null)
            {
                vs = new MockVs();
                // Ensure these options are set correctly if we're creating the
                // instance. Otherwise, the caller is responsible.
                var opts = vs.GetPyService().AdvancedOptions;
                opts.AutoListMembers     = true;
                opts.AutoListIdentifiers = false;
            }
            var view = vs.CreateTextView(
                PythonCoreConstants.ContentType,
                Path.Combine(Environment.CurrentDirectory, Path.GetRandomFileName(), "foo.py")
                );

            view.View.GetAnalyzer(vs.ServiceProvider).WaitForCompleteAnalysis(x => true);
            return(view);
        }
Beispiel #29
0
        public MockVsTextManager(MockVs vs)
        {
            _vs = vs;
            foreach (var langService in MockVs.CachedInfo.LangServicesByGuid)
            {
                var type = langService.Value.Attribute;

                _langPrefs[langService.Key] = new LANGPREFERENCES2()
                {
                    guidLang                     = langService.Key,
                    fDropdownBar                 = (uint)(type.ShowDropDownOptions ? 1 : 0),
                    fInsertTabs                  = (uint)(type.DefaultToInsertSpaces ? 0 : 1),
                    fShowCompletion              = (uint)(type.ShowCompletion ? 1 : 0),
                    fShowSmartIndent             = (uint)(type.ShowSmartIndent ? 1 : 0),
                    fHideAdvancedAutoListMembers = (uint)(type.HideAdvancedMembersByDefault ? 1 : 0),
                    fAutoListMembers             = 1,
                    fAutoListParams              = 1,
                    IndentStyle                  = type.ShowSmartIndent ? vsIndentStyle.vsIndentStyleSmart : vsIndentStyle.vsIndentStyleDefault
                };
            }
        }
        public void AutoListIdentifierCompletions()
        {
            using (var vs = new MockVs()) {
                var options = vs.GetPyService().AdvancedOptions;
                var oldALI  = options.AutoListIdentifiers;
                options.AutoListIdentifiers = true;
                vs.OnDispose(() => options.AutoListIdentifiers = oldALI);

                var view = CreateViewAndAnalyze(vs);
                view.Type("a = ");

                foreach (var c in "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ")
                {
                    // x<space> should bring up a completion session
                    Console.WriteLine("Typing {0}", c);
                    view.Type(c.ToString());

                    using (var sh = view.WaitForSession <ICompletionSession>()) {
                        sh.Session.Dismiss();
                    }

                    view.Backspace();
                }

                view.AssertNoIntellisenseSession();

                // x<space> should not bring up a completion session
                // Don't check too many items, since asserting that no session
                // starts is slow.
                foreach (var c in "1234567890([{")
                {
                    Console.WriteLine("Typing {0}", c);
                    view.Type(c.ToString());

                    view.AssertNoIntellisenseSession();

                    view.Backspace();
                }
            }
        }
Beispiel #31
0
        private static ExpressionAnalysis AnalyzeExpression(MockVs vs, int location, string code, PythonLanguageVersion version = PythonLanguageVersion.V27) {
            if (location < 0) {
                location += code.Length + 1;
            }

            using (var view = new PythonEditor(code, version, vs)) {
                var snapshot = view.CurrentSnapshot;
                return snapshot.AnalyzeExpression(
                    vs.ServiceProvider,
                    snapshot.CreateTrackingSpan(location, location < snapshot.Length ? 1 : 0, SpanTrackingMode.EdgeInclusive),
                    false
                );
            }
        }
Beispiel #32
0
 private static IEnumerable<string> GetCompletions(MockVs vs, int index, string code, IPythonInterpreterFactory factory) {
     using (var view = new PythonEditor(code, vs: vs, factory: factory)) {
         return view.GetCompletions(index);
     }
 }
Beispiel #33
0
 private static IEnumerable<string> GetCompletions(MockVs vs, int index, string code, PythonLanguageVersion version = PythonLanguageVersion.V27) {
     using (var view = new PythonEditor(code, version, vs)) {
         return view.GetCompletions(index);
     }
 }
Beispiel #34
0
        public void CtrlSpaceAfterKeyword() {
            // http://pytools.codeplex.com/workitem/560
            string code = @"
def h():
    return 

print 

";

            using (var vs = new MockVs()) {
                AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("return "), code), "any");
                AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("print "), code), "any");
            }
        }
Beispiel #35
0
        public void OverridesWithMismatchedAnalysis() {
            // Here we create a buffer and analyze. We then add some newlines
            // and a def, expecting completions from A (int). Because the def
            // has moved down into class B, GetCompletions() rolls it back
            // to find out where in the analysis to look - without this, we
            // would get completions for dict rather than int.
            var code = @"
class A(int):
    pass

class B(dict):
    pass

";

            using (var vs = new MockVs()) {
                var editText = "\r\n\r\n\r\n    def ";
                var editInsert = code.IndexOf("pass") + 4;
                var completions = EditAndGetCompletions(vs, code, editText, editInsert, "def ");

                AssertUtil.ContainsAtLeast(completions, "bit_length", "conjugate");
                AssertUtil.DoesntContain(completions, "keys");

                editText = "\r\n\r\n\r\n\r\n\r\n    def ";
                editInsert = code.IndexOf("pass", editInsert) + 4;
                completions = EditAndGetCompletions(vs, code, editText, editInsert, "def ");

                AssertUtil.ContainsAtLeast(completions, "keys", "__contains__");
                AssertUtil.DoesntContain(completions, "bit_length");
            }
        }
Beispiel #36
0
 public MockTreeNode(MockVs mockVs, HierarchyItem res) {
     _mockVs = mockVs;
     _item = res;
 }
Beispiel #37
0
 public MockVsServiceProvider(MockVs mockVs) {
     _vs = mockVs;
     _servicesByType.Add(typeof(IOleServiceProvider), this);
 }
Beispiel #38
0
 public MockVsServiceProvider(MockVs mockVs) {
     _vs = mockVs;
     _servicesByGuid.Add(typeof(IOleServiceProvider).GUID, this);
 }
Beispiel #39
0
        public void CtrlSpaceAfterNumber() {
            // http://pytools.codeplex.com/workitem/2323
            string code = @"
2
2.
2..
2.0.
";

            using (var vs = new MockVs()) {
                AssertUtil.ContainsExactly(GetCompletions(vs, code.IndexOfEnd("2"), code));
                AssertUtil.ContainsExactly(GetCompletions(vs, code.IndexOfEnd("2."), code));
                AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("2.."), code), "real", "imag");
                AssertUtil.ContainsAtLeast(GetCompletions(vs, code.IndexOfEnd("2.0."), code), "real", "imag");
            }
        }
Beispiel #40
0
        public void ExceptionCompletions() {
            using (var vs = new MockVs()) {
                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, |"}) {
                    var completionList = GetCompletions(vs, code.IndexOf("|"), code.Replace("|", "")).ToArray();

                    AssertUtil.ContainsAtLeast(completionList,
                        "Exception",
                        "KeyboardInterrupt",
                        "GeneratorExit",
                        "StopIteration",
                        "SystemExit",
                        "sys"
                    );

                    AssertUtil.DoesntContain(completionList, "Warning");
                    AssertUtil.DoesntContain(completionList, "str");
                    AssertUtil.DoesntContain(completionList, "int");
                }

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

                    AssertUtil.DoesntContain(completionList, "Exception");
                    AssertUtil.DoesntContain(completionList, "KeyboardInterrupt");
                    AssertUtil.DoesntContain(completionList, "GeneratorExit");
                    AssertUtil.DoesntContain(completionList, "StopIteration");
                    AssertUtil.DoesntContain(completionList, "SystemExit");

                    AssertUtil.ContainsAtLeast(completionList,
                        "modules",
                        "path",
                        "version"
                    );
                }
            }
        }
Beispiel #41
0
 public void FromOSPathImportCompletions3x() {
     using (var vs = new MockVs())
     using (var db = MockCompletionDB.Create(PythonLanguageVersion.V33, "os", "ntpath", "posixpath", "os2emxpath")) {
         OSPathImportTest(vs, db);
     }
 }
Beispiel #42
0
        private static void OSPathImportTest(MockVs vs, MockCompletionDB db) {
            var code = "from ";
            AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), "os", "sys");

            code = "from o";
            var completions = GetCompletions(vs, -1, code, db.Factory);
            AssertUtil.ContainsAtLeast(completions, "os");
            AssertUtil.DoesntContain(completions, "sys");

            code = "from os ";
            AssertUtil.ContainsExactly(GetCompletions(vs, -1, code, db.Factory), "import");

            code = "from os import";
            AssertUtil.ContainsExactly(GetCompletions(vs, -1, code, db.Factory), "import");

            code = "from os import ";
            AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), "path");

            code = "from os.";
            AssertUtil.ContainsExactly(GetCompletions(vs, -1, code, db.Factory), "path");

            code = "from os.path import ";
            AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), "abspath", "relpath");

            var allNames = new HashSet<string>();
            allNames.UnionWith(GetCompletions(vs, -1, "from ntpath import ", db.Factory));
            allNames.UnionWith(GetCompletions(vs, -1, "from posixpath import ", db.Factory));

            code = "from os.path import ";
            AssertUtil.ContainsAtLeast(GetCompletions(vs, -1, code, db.Factory), allNames);
        }
Beispiel #43
0
        private static IEnumerable<string> EditAndGetCompletions(
            MockVs vs,
            string code,
            string editText,
            int editInsert,
            string completeAfter,
            PythonLanguageVersion version = PythonLanguageVersion.V27
        ) {
            using (var view = new PythonEditor(code, version, vs)) {
                view.AdvancedOptions.HideAdvancedMembers = false;

                var snapshot = view.CurrentSnapshot;
                view.View.MoveCaret(new SnapshotPoint(snapshot, editInsert));
                view.Type(editText);

                var newSnapshot = view.CurrentSnapshot;
                Assert.AreNotSame(snapshot, newSnapshot);

                return view.GetCompletionsAfter(completeAfter);
            }
        }
Beispiel #44
0
        private static ExpressionAnalysis AnalyzeExpression(MockVs vs, int location, string code, PythonLanguageVersion version = PythonLanguageVersion.V27) {
            if (location < 0) {
                location += code.Length + 1;
            }

            using (var view = new PythonEditor(code, version, vs)) {
                var snapshot = view.CurrentSnapshot;
                ExpressionAnalysis expr = null;
                vs.InvokeSync(() => {
                    expr = vs.GetPyService().AnalyzeExpression(
                        view.View.TextView,
                        snapshot,
                        snapshot.CreateTrackingSpan(location, location < snapshot.Length ? 1 : 0, SpanTrackingMode.EdgeInclusive),
                        false
                    );
                });
                return expr;
            }
        }
Beispiel #45
0
        public void CompletionWithLongDocString() {
            using (var vs = new MockVs()) {
                var docString = GenerateText(100, 72, "    ").ToArray();
                string code = @"
def func(a):
    '''" + string.Join(Environment.NewLine, docString) + @"'''
    pass

";

                // Because there is an extra line added for the Quick Info we only
                // want the first 29 lines of the docstring. For signature docs,
                // we'll cut to 15 lines.
                var expected1 = string.Join(Environment.NewLine, docString.Take(29)) + Environment.NewLine + "...";
                var expected2 = string.Join(Environment.NewLine, docString.Take(15)).TrimStart() + Environment.NewLine + "...";

                using (var view = new PythonEditor(code)) {
                    TestQuickInfo(view, code.IndexOf("func"), code.IndexOf("func") + 4, "func: def func(a)\r\n" + expected1);

                    SignatureAnalysis sigs;
                    view.Text += "func(";
                    TestSignature(view, -1, "func", 0, out sigs);
                    Assert.AreEqual(1, sigs.Signatures.Count);
                    Assert.AreEqual(1, sigs.Signatures[0].Parameters.Count);
                    Assert.AreEqual(expected2, sigs.Signatures[0].Documentation);
                }

                docString = GenerateText(100, 250, "    ").ToArray();
                code = @"
def func(a):
    '''" + string.Join(Environment.NewLine, docString) + @"'''
    pass

";

                using (var view = new PythonEditor(code)) {
                    // The long lines cause us to truncate sooner.
                    expected1 = string.Join(Environment.NewLine, docString.Take(15)) + Environment.NewLine + "...";
                    expected2 = string.Join(Environment.NewLine, docString.Take(8)).TrimStart() + Environment.NewLine + "...";

                    TestQuickInfo(view, code.IndexOf("func"), code.IndexOf("func") + 4, "func: def func(a)\r\n" + expected1);

                    SignatureAnalysis sigs;
                    view.Text += "func(";
                    TestSignature(view, -1, "func", 0, out sigs);
                    Assert.AreEqual(1, sigs.Signatures.Count);
                    Assert.AreEqual(1, sigs.Signatures[0].Parameters.Count);
                    Assert.AreEqual(expected2, sigs.Signatures[0].Documentation);
                }
            }
        }
Beispiel #46
0
 public void TestInit() {
     MockPythonToolsPackage.SuppressTaskProvider = true;
     _vs = new MockVs();
 }
Beispiel #47
0
 public void TestInit() {
     _vs = new MockVs();
 }
Beispiel #48
0
        public void FromImportMultilineCompletions() {
            using (var vs = new MockVs()) {
                var code = "from sys import (";
                var completions = GetCompletions(vs, -1, code);
                AssertUtil.ContainsAtLeast(completions, "settrace", "api_version");
                AssertUtil.DoesntContain(completions, "*");

                code = "from nt import (\r\n    ";
                completions = GetCompletions(vs, -1, code);
                AssertUtil.ContainsAtLeast(completions, "abort", "W_OK");
                AssertUtil.DoesntContain(completions, "*");

                code = "from nt import (getfilesystemencoding,\r\n    ";
                completions = GetCompletions(vs, -1, code);
                AssertUtil.ContainsAtLeast(completions, "abort", "W_OK");
                AssertUtil.DoesntContain(completions, "*");

                // Need a comma for more completions
                code = "from sys import (settrace\r\n    ";
                AssertUtil.ContainsExactly(GetCompletions(vs, -1, code), "as");
            }
        }
Beispiel #49
0
        public PythonEditor(
            string content = null,
            PythonLanguageVersion version = PythonLanguageVersion.V27,
            MockVs vs = null,
            IPythonInterpreterFactory factory = null,
            VsProjectAnalyzer analyzer = null,
            string filename = null
        ) {
            if (vs == null) {
                _disposeVS = true;
                vs = new MockVs();
            }
            MockVsTextView view = null;
            try {
                AdvancedOptions = vs.GetPyService().AdvancedOptions;
                AdvancedOptions.AutoListMembers = true;
                AdvancedOptions.AutoListIdentifiers = false;

                if (factory == null) {
                    _disposeFactory = true;
                    factory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());
                }
                if (analyzer == null) {
                    _disposeAnalyzer = true;
                    analyzer = new VsProjectAnalyzer(vs.ServiceProvider, factory);
                    var task = analyzer.ReloadTask;
                    if (task != null) {
                        task.WaitAndUnwrapExceptions();
                    }
                }

                var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                using (var mre = new ManualResetEventSlim()) {
                    EventHandler evt = (s, e) => mre.Set();
                    analyzer.AnalysisStarted += evt;
                    view = vs.CreateTextView(PythonCoreConstants.ContentType, content ?? "", v => {
                        v.TextView.TextBuffer.Properties.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                    }, filename);

                    try {
                        mre.Wait(cts.Token);
                        analyzer.WaitForCompleteAnalysis(x => !cts.IsCancellationRequested);
                    } catch (OperationCanceledException) {
                    } finally {
                        analyzer.AnalysisStarted -= evt;
                    }
                    if (cts.IsCancellationRequested) {
                        Assert.Fail("Timed out waiting for code analysis");
                    }
                }

                View = view;
                view = null;
                Analyzer = analyzer;
                analyzer = null;
                Factory = factory;
                factory = null;
                VS = vs;
                vs = null;
            } finally {
                if (view != null) {
                    view.Dispose();
                }
                if (analyzer != null && _disposeAnalyzer) {
                    analyzer.Dispose();
                }
                if (factory != null && _disposeFactory) {
                    var disp = factory as IDisposable;
                    if (disp != null) {
                        disp.Dispose();
                    }
                }
                if (vs != null && _disposeVS) {
                    vs.Dispose();
                }
            }
        }
Beispiel #50
0
 public static IVisualStudioInstance ToMockVs(this SolutionFile self) {
     MockVs vs = new MockVs();
     vs.Invoke(() => ErrorHandler.ThrowOnFailure(vs.Solution.OpenSolutionFile(0, self.Filename)));
     return vs;
 }
Beispiel #51
0
        private static IEnumerable<string> EditAndGetCompletions(
            MockVs vs,
            string code,
            string editText,
            int editInsert,
            string completeAfter,
            PythonLanguageVersion version = PythonLanguageVersion.V27
        ) {
            using (var view = new PythonEditor(code, version, vs)) {
                view.AdvancedOptions.HideAdvancedMembers = false;

                var snapshot = view.CurrentSnapshot;
                ITextVersion afterEditVersion = null;
                ManualResetEvent mre = new ManualResetEvent(false);
                view.View.TextView.TextBuffer.RegisterForNewAnalysis(entry => {
                    if (afterEditVersion != null &&
                    entry.BufferParser.GetAnalysisVersion(snapshot.TextBuffer).VersionNumber >= afterEditVersion.VersionNumber) {
                        mre.Set();
                    }
                });
                view.View.MoveCaret(new SnapshotPoint(snapshot, editInsert));
                view.Type(editText);
                afterEditVersion = view.CurrentSnapshot.Version;

                if (!mre.WaitOne(10000)) {
                    Assert.Fail("Failed to wait for new analysis");
                }
                var newSnapshot = view.CurrentSnapshot;
                Assert.AreNotSame(snapshot, newSnapshot);

                return view.GetCompletionsAfter(completeAfter);
            }
        }
 public MockDTE(MockVs vs) {
     _vs = vs;
 }
 public MockVsUIHierarchyWindow(MockVs vs) {
     _mockVs = vs;
 }
Beispiel #54
0
 public MockDialog(MockVs vs, string title) {
     Title = title;
     Vs = vs;
 }
 public MockVsRunningDocumentTable(MockVs vs) {
     _vs = vs;
 }
Beispiel #56
0
        public void GotoDefinition() {
            using (var vs = new MockVs()) {
                string code = @"
class C:
    def fff(self): pass

C().fff";

                //var emptyAnalysis = AnalyzeExpression(0, code);
                //AreEqual(emptyAnalysis.Expression, "");

                for (int i = -1; i >= -3; i--) {
                    var analysis = AnalyzeExpression(vs, i, code);
                    Assert.AreEqual("C().fff", analysis.Expression);
                }

                var classAnalysis = AnalyzeExpression(vs, -6, code);
                Assert.AreEqual("C()", classAnalysis.Expression);

                var defAnalysis = AnalyzeExpression(vs, code.IndexOf("def fff") + 4, code);
                Assert.AreEqual("fff", defAnalysis.Expression);
            }
        }
Beispiel #57
0
 public MockMessageBox(MockVs vs, string title, string text) : base(vs, title) {
     Text = text;
 }
 public MockVsMonitorSelection(MockVs vs) {
     _vs = vs;
     _emptyCtx = new MockVsTrackSelectionEx(this);
 }