Esempio n. 1
0
        public void ConsoleWriteLineTest()
        {
            // http://pytools.codeplex.com/workitem/649
            var replEval   = new PythonReplEvaluator(IronPythonInterpreter, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow).Wait();
            var execute = replEval.ExecuteText("import System");

            execute.Wait();
            Assert.AreEqual(execute.Result, ExecutionResult.Success);
            replWindow.ClearScreen();

            execute = replEval.ExecuteText("System.Console.WriteLine(42)");
            execute.Wait();
            Assert.AreEqual(replWindow.Output, "42\r\n");
            replWindow.ClearScreen();

            Assert.AreEqual(execute.Result, ExecutionResult.Success);

            execute = replEval.ExecuteText("System.Console.Write(42)");
            execute.Wait();

            Assert.AreEqual(execute.Result, ExecutionResult.Success);

            Assert.AreEqual(replWindow.Output, "42");
        }
Esempio n. 2
0
        private void ExtractMethodTest(string input, Func <Span> extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters)
        {
            var fact            = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version ?? new Version(2, 7));
            var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider(suppressTaskProvider: true);

            using (var analyzer = new VsProjectAnalyzer(serviceProvider, fact)) {
                var buffer = new MockTextBuffer(input, "Python", "C:\\fob.py");
                var view   = new MockTextView(buffer);
                buffer.Properties.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                analyzer.MonitorTextBufferAsync(buffer).Wait();
                var extractInput = new ExtractMethodTestInput(true, scopeName, targetName, parameters ?? new string[0]);

                view.Selection.Select(
                    new SnapshotSpan(view.TextBuffer.CurrentSnapshot, extract()),
                    false
                    );

                new MethodExtractor(serviceProvider, view).ExtractMethod(extractInput).Wait();

                if (expected.IsError)
                {
                    Assert.AreEqual(expected.Text, extractInput.FailureReason);
                    Assert.AreEqual(input, view.TextBuffer.CurrentSnapshot.GetText());
                }
                else
                {
                    Assert.AreEqual(null, extractInput.FailureReason);
                    Assert.AreEqual(expected.Text, view.TextBuffer.CurrentSnapshot.GetText());
                }
            }
        }
Esempio n. 3
0
        public void GenericMethodCompletions()
        {
            // http://pytools.codeplex.com/workitem/661
            var fact       = IronPythonInterpreter;
            var replEval   = new PythonReplEvaluator(fact, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow).Wait();
            var execute = replEval.ExecuteText("from System.Threading.Tasks import Task");

            execute.Wait();
            Assert.AreEqual(execute.Result, ExecutionResult.Success);
            replWindow.ClearScreen();

            execute = replEval.ExecuteText("def func1(): print 'hello world'\r\n\r\n");
            execute.Wait();
            replWindow.ClearScreen();

            Assert.AreEqual(execute.Result, ExecutionResult.Success);

            execute = replEval.ExecuteText("t = Task.Factory.StartNew(func1)");
            execute.Wait();
            Assert.AreEqual(execute.Result, ExecutionResult.Success);

            using (var analyzer = new VsProjectAnalyzer(PythonToolsTestUtilities.CreateMockServiceProvider(), fact, new[] { fact })) {
                replWindow.TextView.TextBuffer.Properties.AddProperty(typeof(VsProjectAnalyzer), analyzer);

                var names = replEval.GetMemberNames("t");
                foreach (var name in names)
                {
                    Debug.WriteLine(name.Name);
                }
            }
        }
Esempio n. 4
0
        private static void CodeFormattingTest(string input, object selection, string expected, object expectedSelection, CodeFormattingOptions options, bool selectResult = true)
        {
            var fact     = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7));
            var services = PythonToolsTestUtilities.CreateMockServiceProvider().GetEditorServices();

            using (var analyzer = new VsProjectAnalyzer(services, fact)) {
                var buffer = new MockTextBuffer(input, PythonCoreConstants.ContentType, "C:\\fob.py");
                buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                var view = new MockTextView(buffer);
                analyzer.MonitorTextBufferAsync(buffer).Wait();
                var selectionSpan = new SnapshotSpan(
                    buffer.CurrentSnapshot,
                    ExtractMethodTests.GetSelectionSpan(input, selection)
                    );
                view.Selection.Select(selectionSpan, false);

                analyzer.FormatCodeAsync(
                    selectionSpan,
                    view,
                    options,
                    selectResult
                    ).Wait();

                Assert.AreEqual(expected, view.TextBuffer.CurrentSnapshot.GetText());
                if (expectedSelection != null)
                {
                    Assert.AreEqual(
                        ExtractMethodTests.GetSelectionSpan(expected, expectedSelection),
                        view.Selection.StreamSelectionSpan.SnapshotSpan.Span
                        );
                }
            }
        }
Esempio n. 5
0
        public void AttachSupportMultiThreaded()
        {
            // http://pytools.codeplex.com/workitem/663
            var replEval   = new PythonReplEvaluator(IronPythonInterpreter, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow).Wait();
            var code = new[] {
                "import threading",
                "def sayHello():\r\n    pass",
                "t1 = threading.Thread(target=sayHello)",
                "t1.start()",
                "t2 = threading.Thread(target=sayHello)",
                "t2.start()"
            };

            foreach (var line in code)
            {
                var execute = replEval.ExecuteText(line);
                execute.Wait();
                Assert.AreEqual(execute.Result, ExecutionResult.Success);
            }

            replWindow.ClearScreen();
            var finalExecute = replEval.ExecuteText("42");

            finalExecute.Wait();
            Assert.AreEqual(finalExecute.Result, ExecutionResult.Success);
            Assert.AreEqual(replWindow.Output, "42\r\n");
        }
Esempio n. 6
0
            public ExtractMethodRequest GetExtractionInfo(ExtractedMethodCreator previewer)
            {
                AP.ScopeInfo scope = null;
                if (_scopeName == null)
                {
                    scope = previewer.LastExtraction.scopes[0];
                }
                else
                {
                    foreach (var foundScope in previewer.LastExtraction.scopes)
                    {
                        if (foundScope.name == _scopeName)
                        {
                            scope = foundScope;
                            break;
                        }
                    }
                }

                Assert.AreNotEqual(null, scope);
                var requestView = new ExtractMethodRequestView(PythonToolsTestUtilities.CreateMockServiceProvider(), previewer);

                requestView.TargetScope = requestView.TargetScopes.Single(s => s.Scope == scope);
                requestView.Name        = _targetName;
                foreach (var cv in requestView.ClosureVariables)
                {
                    cv.IsClosure = !_parameters.Contains(cv.Name);
                }
                Assert.IsTrue(requestView.IsValid);
                var request = requestView.GetRequest();

                Assert.IsNotNull(request);
                return(request);
            }
Esempio n. 7
0
        public void BadInterpreterPath()
        {
            // http://pytools.codeplex.com/workitem/662

            var emptyFact = InterpreterFactoryCreator.CreateInterpreterFactory(
                new InterpreterFactoryCreationOptions()
            {
                Description     = "Test Interpreter",
                InterpreterPath = "C:\\Does\\Not\\Exist\\Some\\Interpreter.exe"
            }
                );
            var replEval   = new PythonReplEvaluator(emptyFact, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow);
            var          execute   = replEval.ExecuteText("42");
            var          errorText = replWindow.Error;
            const string expected  =
                "The interactive window could not be started because the associated Python environment could not be found.\r\n" +
                "If this version of Python has recently been uninstalled, you can close this window.\r\n" +
                "Current interactive window is disconnected.";

            if (!errorText.Contains(expected))
            {
                Assert.Fail(string.Format(
                                "Did not find:\n{0}\n\nin:\n{1}",
                                expected,
                                errorText
                                ));
            }
        }
Esempio n. 8
0
        public void BadInterpreterPath()
        {
            // http://pytools.codeplex.com/workitem/662

            var replEval = new PythonInteractiveEvaluator(PythonToolsTestUtilities.CreateMockServiceProvider())
            {
                DisplayName   = "Test Interpreter",
                Configuration = new LaunchConfiguration(new VisualStudioInterpreterConfiguration("InvalidInterpreter", "Test Interpreter", pythonExePath: "C:\\Does\\Not\\Exist\\Some\\Interpreter.exe"))
            };
            var replWindow = new MockReplWindow(replEval);

            replEval._Initialize(replWindow);
            var          execute   = replEval.ExecuteText("42");
            var          errorText = replWindow.Error;
            const string expected  = "the associated Python environment could not be found.";

            if (!errorText.Contains(expected))
            {
                Assert.Fail(string.Format(
                                "Did not find:\n{0}\n\nin:\n{1}",
                                expected,
                                errorText
                                ));
            }
        }
Esempio n. 9
0
        public void LoadAndUnloadModule()
        {
            var factories = new[] { InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 3)) };
            var services  = PythonToolsTestUtilities.CreateMockServiceProvider().GetEditorServices();

            using (var analyzer = new VsProjectAnalyzer(services, factories[0])) {
                var m1Path = TestData.GetPath("TestData\\SimpleImport\\module1.py");
                var m2Path = TestData.GetPath("TestData\\SimpleImport\\module2.py");

                var taskEntry1 = analyzer.AnalyzeFileAsync(m1Path);
                var taskEntry2 = analyzer.AnalyzeFileAsync(m2Path);
                taskEntry1.Wait(CancellationTokens.After5s);
                taskEntry2.Wait(CancellationTokens.After5s);
                var entry1 = taskEntry1.Result;
                var entry2 = taskEntry2.Result;

                var cancel = CancellationTokens.After60s;
                analyzer.WaitForCompleteAnalysis(_ => !cancel.IsCancellationRequested);
                cancel.ThrowIfCancellationRequested();

                var loc = new Microsoft.PythonTools.Parsing.SourceLocation(0, 1, 1);
                AssertUtil.ContainsExactly(
                    analyzer.GetEntriesThatImportModuleAsync("module1", true).Result.Select(m => m.moduleName),
                    "module2"
                    );

                AssertUtil.ContainsExactly(
                    analyzer.GetValueDescriptions(entry2, "x", loc),
                    "int"
                    );

                analyzer.UnloadFileAsync(entry1).Wait();
                analyzer.WaitForCompleteAnalysis(_ => true);

                // Even though module1 has been unloaded, we still know that
                // module2 imports it.
                AssertUtil.ContainsExactly(
                    analyzer.GetEntriesThatImportModuleAsync("module1", true).Result.Select(m => m.moduleName),
                    "module2"
                    );

                AssertUtil.ContainsExactly(
                    analyzer.GetValueDescriptions(entry2, "x", loc)
                    );

                analyzer.AnalyzeFileAsync(m1Path).Wait();
                analyzer.WaitForCompleteAnalysis(_ => true);

                AssertUtil.ContainsExactly(
                    analyzer.GetEntriesThatImportModuleAsync("module1", true).Result.Select(m => m.moduleName),
                    "module2"
                    );

                AssertUtil.ContainsExactly(
                    analyzer.GetValueDescriptions(entry2, "x", loc),
                    "int"
                    );
            }
        }
Esempio n. 10
0
 private static PythonInteractiveEvaluator MakeEvaluator() {
     var python = PythonPaths.Python27_x64 ?? PythonPaths.Python27;
     python.AssertInstalled();
     var provider = new SimpleFactoryProvider(python.InterpreterPath, python.InterpreterPath);
     var eval = new PythonInteractiveEvaluator(PythonToolsTestUtilities.CreateMockServiceProvider()) {
         Configuration = new LaunchConfiguration(python.Configuration)
     };
     Assert.IsTrue(eval._Initialize(new MockReplWindow(eval)).Result.IsSuccessful);
     return eval;
 }
Esempio n. 11
0
        public void TestInit()
        {
            Version.AssertInstalled();
            var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();

            _evaluator = new PythonDebugReplEvaluator(serviceProvider);
            _window    = new MockReplWindow(_evaluator);
            _evaluator._Initialize(_window);
            _processes = new List <PythonProcess>();
        }
Esempio n. 12
0
        public void IronPythonCommentInput()
        {
            // http://pytools.codeplex.com/workitem/649
            var replEval   = new PythonReplEvaluator(IronPythonInterpreter, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow).Wait();
            var execute = replEval.ExecuteText("#fob\n1+2");

            execute.Wait();
            Assert.AreEqual(execute.Result, ExecutionResult.Success);
        }
Esempio n. 13
0
        public void CommentFollowedByBlankLine()
        {
            // http://pytools.codeplex.com/workitem/659
            var replEval   = new PythonReplEvaluator(IronPythonInterpreter, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow).Wait();
            var execute = replEval.ExecuteText("# fob\r\n\r\n    \r\n\t\t\r\na = 42");

            execute.Wait();
            Assert.AreEqual(execute.Result, ExecutionResult.Success);
            replWindow.ClearScreen();
        }
Esempio n. 14
0
        public void IronPythonModuleName()
        {
            var replEval   = new PythonReplEvaluator(IronPythonInterpreter, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow).Wait();
            replWindow.ClearScreen();
            var execute = replEval.ExecuteText("__name__");

            execute.Wait();
            Assert.AreEqual(execute.Result, ExecutionResult.Success);
            Assert.AreEqual(replWindow.Output, "'__main__'\r\n");
            replWindow.ClearScreen();
        }
        public void LoadAndUnloadModule()
        {
            var factories = new[] { InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 3)) };

            using (var analyzer = new VsProjectAnalyzer(PythonToolsTestUtilities.CreateMockServiceProvider(), factories[0], factories)) {
                var m1Path = TestData.GetPath("TestData\\SimpleImport\\module1.py");
                var m2Path = TestData.GetPath("TestData\\SimpleImport\\module2.py");

                var entry1 = analyzer.AnalyzeFile(m1Path) as IPythonProjectEntry;
                var entry2 = analyzer.AnalyzeFile(m2Path) as IPythonProjectEntry;
                analyzer.WaitForCompleteAnalysis(_ => true);

                AssertUtil.ContainsExactly(
                    analyzer.Project.GetEntriesThatImportModule("module1", true).Select(m => m.ModuleName),
                    "module2"
                    );

                AssertUtil.ContainsExactly(
                    entry2.Analysis.GetValuesByIndex("x", 0).Select(v => v.TypeId),
                    BuiltinTypeId.Int
                    );

                analyzer.UnloadFile(entry1);
                analyzer.WaitForCompleteAnalysis(_ => true);

                // Even though module1 has been unloaded, we still know that
                // module2 imports it.
                AssertUtil.ContainsExactly(
                    analyzer.Project.GetEntriesThatImportModule("module1", true).Select(m => m.ModuleName),
                    "module2"
                    );

                AssertUtil.ContainsExactly(
                    entry2.Analysis.GetValuesByIndex("x", 0).Select(v => v.TypeId)
                    );

                analyzer.AnalyzeFile(m1Path);
                analyzer.WaitForCompleteAnalysis(_ => true);

                AssertUtil.ContainsExactly(
                    analyzer.Project.GetEntriesThatImportModule("module1", true).Select(m => m.ModuleName),
                    "module2"
                    );

                AssertUtil.ContainsExactly(
                    entry2.Analysis.GetValuesByIndex("x", 0).Select(v => v.TypeId),
                    BuiltinTypeId.Int
                    );
            }
        }
Esempio n. 16
0
        public async Task NoInterpreterPath() {
            // http://pytools.codeplex.com/workitem/662

            var replEval = new PythonInteractiveEvaluator(PythonToolsTestUtilities.CreateMockServiceProvider()) {
                DisplayName = "Test Interpreter"
            };
            var replWindow = new MockReplWindow(replEval);
            await replEval._Initialize(replWindow);
            await replEval.ExecuteText("42");
            Console.WriteLine(replWindow.Error);
            Assert.IsTrue(
                replWindow.Error.Contains("Test Interpreter cannot be started"),
                "Expected: <Test Interpreter cannot be started>\r\nActual: <" + replWindow.Error + ">"
            );
        }
Esempio n. 17
0
        public void AnalyzeBadEgg()
        {
            var factories = new[] { InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 4)) };

            using (var analyzer = new VsProjectAnalyzer(PythonToolsTestUtilities.CreateMockServiceProvider(), factories[0], factories)) {
                analyzer.AnalyzeZipArchive(TestData.GetPath(@"TestData\BadEgg.egg"));
                analyzer.WaitForCompleteAnalysis(_ => true);

                // Analysis result must contain the module for the filename inside the egg that is a valid identifier,
                // and no entries for the other filename which is not.
                var moduleNames = analyzer.Project.Modules.Select(kv => kv.Key);
                AssertUtil.Contains(moduleNames, "module");
                AssertUtil.DoesntContain(moduleNames, "42");
            }
        }
Esempio n. 18
0
        public void IronPythonSignatures()
        {
            var replEval   = new PythonReplEvaluator(IronPythonInterpreter, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow).Wait();
            var execute = replEval.ExecuteText("from System import Array");

            execute.Wait();
            Assert.AreEqual(execute.Result, ExecutionResult.Success);

            var sigs = replEval.GetSignatureDocumentation("Array[int]");

            Assert.AreEqual(sigs.Length, 1);
            Assert.AreEqual("Array[int](: int)\r\n", sigs[0].Documentation);
        }
Esempio n. 19
0
        public void AnalyzeBadEgg()
        {
            var factories = new[] { InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 4)) };
            var services  = PythonToolsTestUtilities.CreateMockServiceProvider().GetEditorServices();

            using (var analyzer = new VsProjectAnalyzer(services, factories[0])) {
                analyzer.SetSearchPathsAsync(new[] { TestData.GetPath(@"TestData\BadEgg.egg") }).Wait();
                analyzer.WaitForCompleteAnalysis(_ => true);

                // Analysis result must contain the module for the filename inside the egg that is a valid identifier,
                // and no entries for the other filename which is not.
                var moduleNames = analyzer.GetModulesResult(true).Result.Select(x => x.Name);
                AssertUtil.Contains(moduleNames, "module");
                AssertUtil.DoesntContain(moduleNames, "42");
            }
        }
Esempio n. 20
0
        private DjangoAnalyzer AnalyzerTest(string path)
        {
            string djangoDbPath = TestData.GetPath("TestData\\DjangoDB");

            Assert.IsTrue(
                PythonTypeDatabase.IsDatabaseVersionCurrent(djangoDbPath),
                "TestData\\DjangoDB needs updating."
                );

            var testFact = PythonInterpreterFactoryWithDatabase.CreateFromDatabase(
                new Version(2, 7),
                TestData.GetPath("CompletionDB"),
                djangoDbPath
                );

            var            serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();
            PythonAnalyzer analyzer        = PythonAnalyzer.CreateAsync(testFact).WaitAndUnwrapExceptions();
            DjangoAnalyzer djangoAnalyzer  = new DjangoAnalyzer();

            djangoAnalyzer.Register(analyzer);

            analyzer.SetSearchPaths(new[] { path });

            List <IPythonProjectEntry> entries = new List <IPythonProjectEntry>();

            foreach (string file in Directory.EnumerateFiles(path, "*.py", SearchOption.AllDirectories))
            {
                var entry  = analyzer.AddModule(ModulePath.FromFullPath(file).ModuleName, file);
                var parser = Parser.CreateParser(
                    new FileStream(file, FileMode.Open, FileAccess.Read),
                    PythonLanguageVersion.V27
                    );
                using (var p = entry.BeginParse()) {
                    p.Tree = parser.ParseFile();
                    p.Complete();
                }
                entries.Add(entry);
            }

            foreach (var entry in entries)
            {
                entry.Analyze(CancellationToken.None, false);
            }

            return(djangoAnalyzer);
        }
        public void NoTraceFunction()
        {
            // http://pytools.codeplex.com/workitem/662
            var replEval   = new PythonReplEvaluator(IronPythonInterpreter, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow).Wait();
            var execute = replEval.ExecuteText("import sys");

            execute.Wait();
            Assert.AreEqual(execute.Result, ExecutionResult.Success);
            replWindow.ClearScreen();

            execute = replEval.ExecuteText("sys.gettrace()");
            execute.Wait();
            Assert.AreEqual(replWindow.Output, "");
            replWindow.ClearScreen();
        }
Esempio n. 22
0
        private DjangoAnalyzer AnalyzerTest(string path)
        {
            string djangoDbPath = TestData.GetPath("TestData\\DjangoDB");

            Assert.IsTrue(
                PythonTypeDatabase.IsDatabaseVersionCurrent(djangoDbPath),
                "TestData\\DjangoDB needs updating."
                );

            var testFact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(
                new Version(2, 7),
                "Django Test Interpreter",
                TestData.GetPath("CompletionDB"),
                djangoDbPath
                );

            var            serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();
            PythonAnalyzer analyzer        = new PythonAnalyzer(testFact);
            DjangoAnalyzer djangoAnalyzer  = new DjangoAnalyzer(serviceProvider);

            djangoAnalyzer.OnNewAnalyzer(analyzer);

            analyzer.AddAnalysisDirectory(path);

            List <IPythonProjectEntry> entries = new List <IPythonProjectEntry>();

            foreach (string file in Directory.EnumerateFiles(path, "*.py", SearchOption.AllDirectories))
            {
                var entry  = analyzer.AddModule(ModulePath.FromFullPath(file).ModuleName, file);
                var parser = Parser.CreateParser(
                    new FileStream(file, FileMode.Open, FileAccess.Read),
                    PythonLanguageVersion.V27
                    );
                entry.UpdateTree(parser.ParseFile(), null);
                entries.Add(entry);
            }

            foreach (var entry in entries)
            {
                entry.Analyze(CancellationToken.None, false);
            }

            return(djangoAnalyzer);
        }
Esempio n. 23
0
        public void IronPythonSignatures()
        {
            var replEval   = new PythonReplEvaluator(IronPythonInterpreter, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval._Initialize(replWindow).Wait();
            var execute = replEval.ExecuteText("from System import Array");

            execute.Wait();
            Assert.IsTrue(execute.Result.IsSuccessful);

            OverloadDoc[] sigs = null;
            for (int retries = 0; retries < 5 && sigs == null; retries += 1)
            {
                sigs = replEval.GetSignatureDocumentation("Array[int]");
            }
            Assert.IsNotNull(sigs, "GetSignatureDocumentation timed out");
            Assert.AreEqual(sigs.Length, 1);
            Assert.AreEqual("Array[int](: int)\r\n", sigs[0].Documentation);
        }
Esempio n. 24
0
        private DjangoAnalyzer AnalyzerTest(string path)
        {
            var version  = new Version(2, 7);
            var testFact = new AstPythonInterpreterFactory(
                new InterpreterConfiguration($"AnalysisOnly|{version}", $"Analysis Only {version}", version: version, uiMode: InterpreterUIMode.Normal),
                new InterpreterFactoryCreationOptions {
                WatchFileSystem = false
            }
                );

            var            serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();
            PythonAnalyzer analyzer        = PythonAnalyzer.CreateAsync(testFact).WaitAndUnwrapExceptions();
            DjangoAnalyzer djangoAnalyzer  = new DjangoAnalyzer();

            djangoAnalyzer.Register(analyzer);

            analyzer.SetSearchPaths(new[] { path });

            List <IPythonProjectEntry> entries = new List <IPythonProjectEntry>();

            foreach (string file in Directory.EnumerateFiles(path, "*.py", SearchOption.AllDirectories))
            {
                var entry  = analyzer.AddModule(ModulePath.FromFullPath(file).ModuleName, file);
                var parser = Parser.CreateParser(
                    new FileStream(file, FileMode.Open, FileAccess.Read),
                    PythonLanguageVersion.V27
                    );
                using (var p = entry.BeginParse()) {
                    p.Tree = parser.ParseFile();
                    p.Complete();
                }
                entries.Add(entry);
            }

            foreach (var entry in entries)
            {
                entry.Analyze(CancellationToken.None, false);
            }

            return(djangoAnalyzer);
        }
Esempio n. 25
0
        public void NoTraceFunction()
        {
            // http://pytools.codeplex.com/workitem/662
            var replEval   = new PythonReplEvaluator(IronPythonInterpreter, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval._Initialize(replWindow).Wait();
            var execute = replEval.ExecuteText("import sys");

            execute.Wait();
            Assert.IsTrue(execute.Result.IsSuccessful);
            replWindow.ClearScreen();

            execute = replEval.ExecuteText("sys.gettrace()");
            execute.Wait();
            AssertUtil.AreEqual(
                new Regex(@"\<bound method Thread.trace_func of \<Thread.+\>\>"),
                replWindow.Output
                );
            replWindow.ClearScreen();
        }
Esempio n. 26
0
        private static async Task <IEnumerable <TrackingTagSpan <ErrorTag> > > AnalyzeTextBufferAsync(
            MockTextBuffer buffer,
            PythonLanguageVersion version = PythonLanguageVersion.V27
            )
        {
            var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());

            try {
                var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();
                var errorProvider   = serviceProvider.ComponentModel.GetService <IErrorProviderFactory>();
                Assert.IsNotNull(errorProvider, "Error provider factory is not available");
                var analyzer = new VsProjectAnalyzer(serviceProvider, fact, new[] { fact });
                buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                var classifierProvider = new PythonClassifierProvider(new MockContentTypeRegistryService(PythonCoreConstants.ContentType), serviceProvider);
                classifierProvider._classificationRegistry = new MockClassificationTypeRegistryService();
                classifierProvider.GetClassifier(buffer);
                var squiggles       = errorProvider.GetErrorTagger(buffer);
                var textView        = new MockTextView(buffer);
                var monitoredBuffer = analyzer.MonitorTextBuffer(textView, buffer);

                var tcs = new TaskCompletionSource <object>();
                buffer.GetPythonProjectEntry().OnNewAnalysis += (s, e) => tcs.SetResult(null);
                await tcs.Task;

                var snapshot = buffer.CurrentSnapshot;

                // Ensure all tasks have been updated
                var taskProvider = (ErrorTaskProvider)serviceProvider.GetService(typeof(ErrorTaskProvider));
                var time         = await taskProvider.FlushAsync();

                Console.WriteLine("TaskProvider.FlushAsync took {0}ms", time.TotalMilliseconds);

                var spans = squiggles.GetTaggedSpans(new SnapshotSpan(snapshot, 0, snapshot.Length));

                analyzer.StopMonitoringTextBuffer(monitoredBuffer.BufferParser, textView);

                return(spans);
            } finally {
            }
        }
Esempio n. 27
0
        private async Task ExtractMethodTest(string input, Func <Span> extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters)
        {
            var fact     = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version ?? new Version(2, 7));
            var services = PythonToolsTestUtilities.CreateMockServiceProvider().GetEditorServices();

            using (var analyzer = await VsProjectAnalyzer.CreateForTestsAsync(services, fact)) {
                var buffer = new MockTextBuffer(input, PythonCoreConstants.ContentType, Path.Combine(TestData.GetTempPath(), "fob.py"));
                var view   = new MockTextView(buffer);
                buffer.Properties.AddProperty(typeof(VsProjectAnalyzer), analyzer);

                var bi = services.GetBufferInfo(buffer);
                bi.ParseImmediately = true;
                var entry = await analyzer.AnalyzeFileAsync(bi.DocumentUri);

                Assert.AreEqual(entry, bi.TrySetAnalysisEntry(entry, null));
                var bp = entry.GetOrCreateBufferParser(services);
                bp.AddBuffer(buffer);
                await bp.EnsureCodeSyncedAsync(bi.Buffer, true);

                var extractInput = new ExtractMethodTestInput(true, scopeName, targetName, parameters ?? new string[0]);

                view.Selection.Select(
                    new SnapshotSpan(view.TextBuffer.CurrentSnapshot, extract()),
                    false
                    );

                await new Microsoft.PythonTools.Refactoring.MethodExtractor(services, view).ExtractMethod(extractInput);

                if (expected.IsError)
                {
                    Assert.AreEqual(expected.Text, extractInput.FailureReason);
                    Assert.AreEqual(input, view.TextBuffer.CurrentSnapshot.GetText());
                }
                else
                {
                    Assert.AreEqual(null, extractInput.FailureReason);
                    Assert.AreEqual(expected.Text, view.TextBuffer.CurrentSnapshot.GetText());
                }
            }
        }
Esempio n. 28
0
        public void NoInterpreterPath()
        {
            // http://pytools.codeplex.com/workitem/662

            var emptyFact = InterpreterFactoryCreator.CreateInterpreterFactory(
                new InterpreterFactoryCreationOptions()
            {
                Description = "Test Interpreter"
            }
                );
            var replEval   = new PythonReplEvaluator(emptyFact, PythonToolsTestUtilities.CreateMockServiceProvider(), new ReplTestReplOptions());
            var replWindow = new MockReplWindow(replEval);

            replEval.Initialize(replWindow);
            var execute = replEval.ExecuteText("42");

            Console.WriteLine(replWindow.Error);
            Assert.IsTrue(
                replWindow.Error.Contains("Test Interpreter cannot be started"),
                "Expected: <Test Interpreter cannot be started>\r\nActual: <" + replWindow.Error + ">"
                );
        }
Esempio n. 29
0
        private static async Task CodeFormattingTest(string input, object selection, string expected, object expectedSelection, CodeFormattingOptions options, bool selectResult = true)
        {
            var fact     = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7));
            var services = PythonToolsTestUtilities.CreateMockServiceProvider().GetEditorServices();

            using (var analyzer = await VsProjectAnalyzer.CreateForTestsAsync(services, fact)) {
                var buffer = new MockTextBuffer(input, PythonCoreConstants.ContentType, Path.Combine(TestData.GetTempPath(), "fob.py"));
                buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);
                var view  = new MockTextView(buffer);
                var bi    = services.GetBufferInfo(buffer);
                var entry = await analyzer.AnalyzeFileAsync(bi.Filename);

                Assert.AreEqual(entry, bi.TrySetAnalysisEntry(entry, null), "Failed to set analysis entry");
                entry.GetOrCreateBufferParser(services).AddBuffer(buffer);

                var selectionSpan = new SnapshotSpan(
                    buffer.CurrentSnapshot,
                    ExtractMethodTests.GetSelectionSpan(input, selection)
                    );
                view.Selection.Select(selectionSpan, false);

                await analyzer.FormatCodeAsync(
                    selectionSpan,
                    view,
                    options,
                    selectResult
                    );

                Assert.AreEqual(expected, view.TextBuffer.CurrentSnapshot.GetText());
                if (expectedSelection != null)
                {
                    Assert.AreEqual(
                        ExtractMethodTests.GetSelectionSpan(expected, expectedSelection),
                        view.Selection.StreamSelectionSpan.SnapshotSpan.Span
                        );
                }
            }
        }
            public ClassifierHelper(MockTextBuffer buffer, PythonLanguageVersion version)
            {
                var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider();

                _contentRegistry        = new MockContentTypeRegistryService(PythonCoreConstants.ContentType);
                _classificationRegistry = new MockClassificationTypeRegistryService();
                _provider1 = new PythonClassifierProvider(_contentRegistry, serviceProvider)
                {
                    _classificationRegistry = _classificationRegistry
                };
                _provider2 = new PythonAnalysisClassifierProvider(_contentRegistry, serviceProvider)
                {
                    _classificationRegistry = _classificationRegistry
                };

                _buffer  = buffer;
                _factory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());

                var analyzer = new VsProjectAnalyzer(serviceProvider, _factory, new[] { _factory });

                _buffer.AddProperty(typeof(VsProjectAnalyzer), analyzer);

                _view = new MockTextView(_buffer);
            }