Ejemplo n.º 1
0
        public void ToggleableOptionTest() {
            using (var app = new PythonVisualStudioApp()) {
                var pyService = app.ServiceProvider.GetPythonToolsService();
                pyService.SetFormattingOption("SpaceBeforeClassDeclarationParen", true);
                foreach (var expectedResult in new bool?[] { false, null, true }) {
                    using (var dialog = ToolsOptionsDialog.FromDte(app)) {
                        dialog.SelectedView = "Text Editor/Python/Formatting/Spacing";
                        var spacingView = FormattingOptionsTreeView.FromDialog(dialog);

                        var value = spacingView.WaitForItem(
                            "Class Definitions",
                            "Insert space between a class declaration's name and bases list"
                        );
                        Assert.IsNotNull(value, "Did not find item");

                        value.SetFocus();
                        Mouse.MoveTo(value.GetClickablePoint());
                        Mouse.Click(System.Windows.Input.MouseButton.Left);

                        dialog.OK();

                        Assert.AreEqual(
                            expectedResult,
                            pyService.GetFormattingOption("SpaceBeforeClassDeclarationParen")
                        );
                    }
                }
            }
        }
Ejemplo n.º 2
0
        private static void CheckCommandLineArgs(string setValue, string expectedValue = null) {
            using (var app = new PythonVisualStudioApp()) {
                var project = app.OpenProject(@"TestData\CheckCommandLineArgs.sln");

                var proj = project.GetCommonProject() as IPythonProject;
                Assert.IsNotNull(proj);

                var outFile = Path.Combine(Path.GetDirectoryName(project.FullName), "output.txt");

                foreach (var cmdName in new[] { "PythonRunWebServerCommand", "PythonDebugWebServerCommand" }) {
                    Console.WriteLine("Testing {0}, writing to {1}", cmdName, outFile);

                    if (File.Exists(outFile)) {
                        File.Delete(outFile);
                    }

                    app.ServiceProvider.GetUIThread().Invoke(() => {
                        proj.SetProperty("CommandLineArguments", string.Format("\"{0}\" \"{1}\"", setValue, outFile));
                        proj.FindCommand(cmdName).Execute(proj);
                    });

                    for (int retries = 10; retries > 0 && !File.Exists(outFile); --retries) {
                        Thread.Sleep(100);
                    }

                    Assert.AreEqual(expectedValue ?? setValue, File.ReadAllText(outFile).Trim());
                }
            }
        }
Ejemplo n.º 3
0
        public void AutomaticBraceCompletion() {
            using (var app = new PythonVisualStudioApp()) {
                var project = app.OpenProject(@"TestData\AutomaticBraceCompletion.sln");

                bool oldState = EnableAutoBraceCompletion(app, true);
                app.OnDispose(() => EnableAutoBraceCompletion(app, oldState));

                // check that braces get auto completed
                AutoBraceCompetionTest(app, project, "foo(", "foo()");
                AutoBraceCompetionTest(app, project, "foo[", "foo[]");
                AutoBraceCompetionTest(app, project, "foo{", "foo{}");
                AutoBraceCompetionTest(app, project, "\"foo", "\"foo\"");
                AutoBraceCompetionTest(app, project, "'foo", "'foo'");

                // check that braces get not autocompleted in comments and strings
                AutoBraceCompetionTest(app, project, "\"foo(\"", "\"foo(\"");
                AutoBraceCompetionTest(app, project, "#foo(", "#foo(");
                AutoBraceCompetionTest(app, project, "\"\"\"\rfoo(\r\"\"\"\"", "\"\"\"\r\nfoo(\r\n\"\"\"\"");

                // check that end braces gets skiped
                AutoBraceCompetionTest(app, project, "foo(bar)", "foo(bar)");
                AutoBraceCompetionTest(app, project, "foo[bar]", "foo[bar]");
                AutoBraceCompetionTest(app, project, "foo{bar}", "foo{bar}");
                AutoBraceCompetionTest(app, project, "\"foo\"", "\"foo\"");
                AutoBraceCompetionTest(app, project, "'foo'", "'foo'");
                AutoBraceCompetionTest(app, project, "foo({[\"\"]})", "foo({[\"\"]})");
            }
        }
Ejemplo n.º 4
0
        public void DebugProjectProperties()
        {
            using (var app = new PythonVisualStudioApp()) {
                var project = app.CreateProject(
                    PythonVisualStudioApp.TemplateLanguageName,
                    PythonVisualStudioApp.DjangoWebProjectTemplate,
                    TestData.GetTempPath(),
                    "DebugProjectProperties"
                );
                app.SolutionExplorerTreeView.SelectProject(project);

                app.Dte.ExecuteCommand("ClassViewContextMenus.ClassViewMultiselectProjectreferencesItems.Properties");
                var window = app.Dte.Windows.OfType<EnvDTE.Window>().FirstOrDefault(w => w.Caption == project.Name);
                Assert.IsNotNull(window);

                window.Activate();
                var hwnd = window.HWnd;
                var projProps = new ProjectPropertiesWindow(new IntPtr(hwnd));

                var debugPage = projProps[new Guid(PythonConstants.DebugPropertyPageGuid)];
                Assert.IsNotNull(debugPage);

                var dbgProps = new PythonProjectDebugProperties(debugPage);
                Assert.AreEqual("Django Web launcher", dbgProps.LaunchMode);
                dbgProps.AssertMatchesProject(project.GetPythonProject());
            }
        }
Ejemplo n.º 5
0
 static DefaultInterpreterSetter Init3(PythonVisualStudioApp app, bool installVirtualEnv = false) {
     return app.SelectDefaultInterpreter(
         PythonPaths.Python35 ?? PythonPaths.Python35_x64 ??
         PythonPaths.Python34 ?? PythonPaths.Python34_x64 ??
         PythonPaths.Python33 ?? PythonPaths.Python33_x64,
         installVirtualEnv ? "virtualenv" : null
     );
 }
Ejemplo n.º 6
0
        public virtual void ExecuteInReplSysArgv() {
            using (var app = new PythonVisualStudioApp()) {
                var project = app.OpenProject(@"TestData\SysArgvRepl.sln");

                using (var interactive = app.ExecuteInInteractive(project)) {
                    interactive.WaitForTextEnd("Program.py']", ">");
                }
            }
        }
Ejemplo n.º 7
0
 static DefaultInterpreterSetter Init(PythonVisualStudioApp app) {
     var dis = app.SelectDefaultInterpreter(PythonPaths.Python27 ?? PythonPaths.Python27_x64);
     try {
         dis.CurrentDefault.PipInstall("-U virtualenv");
         var r = dis;
         dis = null;
         return r;
     } finally {
         dis?.Dispose();
     }
 }
Ejemplo n.º 8
0
 static DefaultInterpreterSetter Init(PythonVisualStudioApp app, PythonVersion interp, bool install) {
     var dis = app.SelectDefaultInterpreter(interp);
     try {
         if (install) {
             dis.CurrentDefault.PipInstall("-U virtualenv");
         }
         var r = dis;
         dis = null;
         return r;
     } finally {
         dis?.Dispose();
     }
 }
Ejemplo n.º 9
0
        public void UnregisteredFileExtensionEditor() {
            using (var app = new PythonVisualStudioApp()) {
                var project = app.OpenProject(@"TestData\UnregisteredFileExtension.sln");

                var item = project.ProjectItems.Item("Fob.unregfileext");
                var window = item.Open();
                window.Activate();

                var doc = app.GetDocument(item.Document.FullName);
                var snapshot = doc.TextView.TextBuffer.CurrentSnapshot;

                // we shouldn't have opened this as a .py file, so we should have no classifications.
                var classifier = doc.Classifier;
                var spans = classifier.GetClassificationSpans(new SnapshotSpan(snapshot, 0, snapshot.Length));
                Assert.AreEqual(spans.Count, 0);
            }
        }
Ejemplo n.º 10
0
        public void AbsolutePaths()
        {
            var proj = File.ReadAllText(TestData.GetPath(@"TestData\AbsolutePath\AbsolutePath.pyproj"));
            proj = proj.Replace("[ABSPATH]", TestData.GetPath(@"TestData\AbsolutePath"));
            File.WriteAllText(TestData.GetPath(@"TestData\AbsolutePath\AbsolutePath.pyproj"), proj);

            using (var app = new PythonVisualStudioApp()) {
                var project = app.OpenProject(@"TestData\AbsolutePath.sln");

                app.OpenSolutionExplorer();
                var window = app.SolutionExplorerTreeView;

                // find Program.py, send copy & paste, verify copy of file is there
                var programPy = window.WaitForItem("Solution 'AbsolutePath' (1 project)", "AbsolutePath", "Program.py");
                Assert.IsNotNull(programPy);
            }
        }
Ejemplo n.º 11
0
 static DefaultInterpreterSetter Init3(PythonVisualStudioApp app, bool installVirtualEnv = false) {
     var dis = app.SelectDefaultInterpreter(
         PythonPaths.Python35 ?? PythonPaths.Python35_x64 ??
         PythonPaths.Python34 ?? PythonPaths.Python34_x64 ??
         PythonPaths.Python33 ?? PythonPaths.Python33_x64
     );
     try {
         if (installVirtualEnv) {
             dis.CurrentDefault.PipInstall("-U virtualenv");
         }
         var r = dis;
         dis = null;
         return r;
     } finally {
         dis?.Dispose();
     }
 }
Ejemplo n.º 12
0
        public void DefaultInterpreterSelected() {
            using (var app = new PythonVisualStudioApp()) {
                var service = app.InterpreterService;
                var originalDefault = service.DefaultInterpreter;

                try {
                    foreach (var interpreter in service.Interpreters) {
                        service.DefaultInterpreter = interpreter;
                        using (var dialog = app.LaunchPythonProfiling()) {
                            Assert.AreEqual(interpreter.Description, dialog.SelectedInterpreter);
                        }
                        app.WaitForDialogDismissed();
                    }
                } finally {
                    service.DefaultInterpreter = originalDefault;
                }
            }
        }
Ejemplo n.º 13
0
        public void LoadWebFlavoredProject() {
            using (var app = new PythonVisualStudioApp()) {
                var project = app.OpenProject(@"TestData\EmptyWebProject.sln");
                Assert.AreEqual("EmptyWebProject.pyproj", Path.GetFileName(project.FileName), "Wrong project file name");

                var catids = app.Dte.ObjectExtenders.GetContextualExtenderCATIDs();
                dynamic extender = project.Extender["WebApplication"];
                Assert.IsNotNull(extender, "No WebApplication extender");
                extender.StartWebServerOnDebug = true;
                extender.StartWebServerOnDebug = false;

                var proj = project.GetCommonProject();
                var ccp = proj as IPythonProject;
                Assert.IsNotNull(ccp);
                Assert.IsNotNull(ccp.FindCommand("PythonRunWebServerCommand"), "No PythonRunWebServerCommand");
                Assert.IsNotNull(ccp.FindCommand("PythonDebugWebServerCommand"), "No PythonDebugWebServerCommand");
            }
        }
Ejemplo n.º 14
0
        public void DeferredSaveWithDot() {
            string fullname;
            using (var app = new PythonVisualStudioApp()) {
                // http://pytools.codeplex.com/workitem/623
                // enable deferred saving on projects
                var props = app.Dte.get_Properties("Environment", "ProjectsAndSolution");
                var prevValue = props.Item("SaveNewProjects").Value;
                props.Item("SaveNewProjects").Value = false;
                app.OnDispose(() => { props.Item("SaveNewProjects").Value = prevValue; });


                using (var newProjDialog = app.FileNewProject()) {
                    newProjDialog.FocusLanguageNode();

                    var consoleApp = newProjDialog.ProjectTypes.FindItem("Python Application");
                    consoleApp.Select();
                    newProjDialog.ProjectName = "Fob.Oar";
                    newProjDialog.OK();
                }

                // wait for new solution to load...
                for (int i = 0; i < 100 && app.Dte.Solution.Projects.Count == 0; i++) {
                    System.Threading.Thread.Sleep(1000);
                }

                using (var saveDialog = AutomationDialog.FromDte(app, "File.SaveAll")) {
                    saveDialog.ClickButtonAndClose("Save");
                }

                fullname = app.Dte.Solution.FullName;
            }

            try {
                // Delete the created directory after the solution has been
                // closed.
                Directory.Delete(Path.GetDirectoryName(fullname), true);
            } catch {
            }
        }
Ejemplo n.º 15
0
        public void DjangoCollectStaticFilesCommand() {
            using (var app = new PythonVisualStudioApp()) {
                var service = app.GetService<IComponentModel>(typeof(SComponentModel)).GetService<IInterpreterOptionsService>();

                var envWithDjango = service.Interpreters.LastOrDefault(env => env.FindModulesAsync("django").WaitAndUnwrapExceptions().Contains("django"));
                if (envWithDjango == null) {
                    Assert.Inconclusive("No available environments have Django installed");
                }

                using (var dis = new DefaultInterpreterSetter(envWithDjango)) {
                    var project = app.OpenProject("TestData\\DjangoApplication1\\DjangoApplication1.sln");
                    app.SolutionExplorerTreeView.SelectProject(project);

                    app.Dte.ExecuteCommand("Project.CollectStaticFiles");

                    var console = app.GetInteractiveWindow("Django Management Console - " + project.Name);
                    Assert.IsNotNull(console);

                    console.WaitForTextEnd("The Python REPL process has exited", ">>> ");

                    Assert.IsTrue(console.Text.Contains("0 static files copied"));
                }
            }
        }
Ejemplo n.º 16
0
        public void InstallUninstallPackage() {
            using (var app = new PythonVisualStudioApp())
            using (var dis = Init(app)) {
                var project = CreateTemporaryProject(app);

                string envName;
                var env = app.CreateVirtualEnvironment(project, out envName);
                env.Select();

                using (var installPackage = AutomationDialog.FromDte(app, "Python.InstallPackage")) {
                    var packageName = new TextBox(installPackage.FindByAutomationId("Name"));
                    packageName.SetValue("azure==0.6.2");
                    installPackage.ClickButtonAndClose("OK", nameIsAutomationId: true);
                }

                var azure = app.SolutionExplorerTreeView.WaitForChildOfProject(
                    project,
                    SR.GetString(SR.Environments),
                    envName,
                    "azure (0.6.2)"
                );

                azure.Select();

                using (var confirmation = AutomationDialog.FromDte(app, "Edit.Delete")) {
                    confirmation.OK();
                }

                app.SolutionExplorerTreeView.WaitForChildOfProjectRemoved(
                    project,
                    SR.GetString(SR.Environments),
                    envName,
                    "azure (0.6.2)"
                );
            }
        }
Ejemplo n.º 17
0
        public void CustomCommandsRunProcessInOutput() {
            using (var app = new PythonVisualStudioApp()) {
                PythonProjectNode node;
                EnvDTE.Project proj;
                OpenProject(app, "Commands3.sln", out node, out proj);

                Execute(node, "Write to Output");

                var outputWindow = app.Element.FindFirst(TreeScope.Descendants,
                    new AndCondition(
                        new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"),
                        new PropertyCondition(AutomationElement.NameProperty, "Output")
                    )
                );
                Assert.IsNotNull(outputWindow, "Output Window was not opened");

                ExpectOutputWindowText(app, string.Format("({0}, {1})", PythonVersion.Configuration.Version.Major, PythonVersion.Configuration.Version.Minor));
            }
        }
Ejemplo n.º 18
0
        public void CustomCommandsRunProcessInRepl() {
            using (var app = new PythonVisualStudioApp()) {
                PythonProjectNode node;
                EnvDTE.Project proj;
                OpenProject(app, "Commands3.sln", out node, out proj);

                Execute(node, "Write to Repl");

                using (var repl = app.GetInteractiveWindow("Test Repl")) {
                    Assert.IsNotNull(repl, "Could not find repl window");
                    repl.WaitForTextEnd(
                        string.Format("({0}, {1})", PythonVersion.Configuration.Version.Major, PythonVersion.Configuration.Version.Minor),
                        ">"
                    );
                }
            }
        }
Ejemplo n.º 19
0
        public void CustomCommandsRunInRepl() {
            using (var app = new PythonVisualStudioApp()) {
                PythonProjectNode node;
                EnvDTE.Project proj;
                OpenProject(app, "Commands1.sln", out node, out proj);

                Execute(node, "Test Command 2");

                using (var repl = app.GetInteractiveWindow("Test Repl")) {
                    Assert.IsNotNull(repl, "Could not find repl window");
                    repl.WaitForTextEnd(
                        "Program.py completed",
                        ">"
                    );
                }

                app.Dte.Solution.Close();

                using (var repl = app.GetInteractiveWindow("Test Repl")) {
                    Assert.IsNull(repl, "Repl window was not closed");
                }
            }
        }
Ejemplo n.º 20
0
        public void CustomCommandsReplWithResourceLabel() {
            using (var app = new PythonVisualStudioApp()) {
                PythonProjectNode node;
                EnvDTE.Project proj;
                OpenProject(app, "Commands2.sln", out node, out proj);

                Execute(node, "Command from Resource");

                using (var repl = app.GetInteractiveWindow("Repl from Resource")) {
                    Assert.IsNotNull(repl, "Could not find repl window");
                    repl.WaitForTextEnd(
                        "Program.py completed",
                        ">"
                    );
                }

                using (var repl = app.GetInteractiveWindow("resource:PythonToolsUITests;PythonToolsUITests.Resources;ReplName")) {
                    Assert.IsNull(repl);
                }
            }
        }
Ejemplo n.º 21
0
        public void EnvironmentReplWorkingDirectory() {
            using (var app = new PythonVisualStudioApp())
            using (var dis = Init(app)) {
                var project = CreateTemporaryProject(app);

                app.ServiceProvider.GetUIThread().Invoke(() => {
                    var pp = project.GetPythonProject();
                    pp.Interpreters.AddInterpreter(dis.CurrentDefault);
                });

                var envName = dis.CurrentDefault.Description;
                var sln = app.OpenSolutionExplorer();
                var env = sln.FindChildOfProject(project, SR.GetString(SR.Environments), envName);

                EnvironmentReplWorkingDirectoryTest(app, project, env, envName);
            }
        }
Ejemplo n.º 22
0
        public void VirtualEnvironmentReplWorkingDirectory() {
            using (var app = new PythonVisualStudioApp())
            using (var dis = Init(app)) {
                var project = CreateTemporaryProject(app);

                string envName;
                var env = app.CreateVirtualEnvironment(project, out envName);

                EnvironmentReplWorkingDirectoryTest(app, project, env, envName);
            }
        }
Ejemplo n.º 23
0
 static DefaultInterpreterSetter Init(PythonVisualStudioApp app, PythonVersion interp, bool install) {
     return app.SelectDefaultInterpreter(interp, install ? "virtualenv" : null);
 }
Ejemplo n.º 24
0
        private void EnvironmentReplWorkingDirectoryTest(
            PythonVisualStudioApp app,
            EnvDTE.Project project,
            TreeNode env,
            string envName
        ) {
            var path1 = Path.Combine(Path.GetDirectoryName(project.FullName), Guid.NewGuid().ToString("N"));
            var path2 = Path.Combine(Path.GetDirectoryName(project.FullName), Guid.NewGuid().ToString("N"));
            Directory.CreateDirectory(path1);
            Directory.CreateDirectory(path2);

            env.Select();
            app.Dte.ExecuteCommand("Python.Interactive");

            var window = app.GetInteractiveWindow(string.Format("{0} Interactive", envName));
            Assert.IsNotNull(window, string.Format("Failed to find '{0} Interactive'", envName));
            try {
                app.ServiceProvider.GetUIThread().Invoke(() => project.GetPythonProject().SetProjectProperty("WorkingDirectory", path1));

                window.Reset();
                window.ReplWindow.Evaluator.ExecuteText("import os; os.getcwd()").Wait();
                window.WaitForTextEnd(
                    string.Format("'{0}'", path1.Replace("\\", "\\\\")),
                    ">>>"
                );

                app.ServiceProvider.GetUIThread().Invoke(() => project.GetPythonProject().SetProjectProperty("WorkingDirectory", path2));

                window.Reset();
                window.ReplWindow.Evaluator.ExecuteText("import os; os.getcwd()").Wait();
                window.WaitForTextEnd(
                    string.Format("'{0}'", path2.Replace("\\", "\\\\")),
                    ">>>"
                );
            } finally {
                window.Close();
            }
        }
Ejemplo n.º 25
0
 static DefaultInterpreterSetter Init(PythonVisualStudioApp app) {
     return app.SelectDefaultInterpreter(PythonPaths.Python27 ?? PythonPaths.Python27_x64, "virtualenv");
 }
Ejemplo n.º 26
0
        public void CustomCommandsRunProcessInConsole() {
            using (var app = new PythonVisualStudioApp()) {
                PythonProjectNode node;
                EnvDTE.Project proj;
                OpenProject(app, "Commands3.sln", out node, out proj);

                var existingProcesses = new HashSet<int>(Process.GetProcessesByName("cmd").Select(p => p.Id));

                Execute(node, "Write to Console");

                Process newProcess = null;
                for (int retries = 100; retries > 0 && newProcess == null; --retries) {
                    Thread.Sleep(100);
                    newProcess = Process.GetProcessesByName("cmd").Where(p => !existingProcesses.Contains(p.Id)).FirstOrDefault();
                }
                Assert.IsNotNull(newProcess, "Process did not start");
                try {
                    Keyboard.PressAndRelease(System.Windows.Input.Key.Space);
                    newProcess.WaitForExit(1000);
                    if (newProcess.HasExited) {
                        newProcess = null;
                    }
                } finally {
                    if (newProcess != null) {
                        newProcess.Kill();
                    }
                }
            }
        }
Ejemplo n.º 27
0
        public void CustomCommandsRequiredPackages() {
            using (var app = new PythonVisualStudioApp())
            using (var dis = app.SelectDefaultInterpreter(PythonVersion, "virtualenv")) {
                PythonProjectNode node;
                EnvDTE.Project proj;
                OpenProject(app, "CommandRequirePackages.sln", out node, out proj);

                string envName;
                var env = app.CreateVirtualEnvironment(proj, out envName);

                env.Select();
                app.Dte.ExecuteCommand("Python.ActivateEnvironment");
                // Ensure that no error dialog appears
                app.WaitForNoDialog(TimeSpan.FromSeconds(5.0));

                // First, execute the command and cancel it.
                var task = ExecuteAsync(node, "Require Packages");
                try {
                    var dialogHandle = app.WaitForDialog(task);
                    if (dialogHandle == IntPtr.Zero) {
                        if (task.IsFaulted && task.Exception != null) {
                            Assert.Fail("Unexpected exception in package install confirmation dialog:\n{0}", task.Exception);
                        } else {
                            Assert.AreNotEqual(IntPtr.Zero, dialogHandle);
                        }
                    }

                    using (var dialog = new AutomationDialog(app, AutomationElement.FromHandle(dialogHandle))) {
                        var label = dialog.FindByAutomationId("CommandLink_1000");
                        Assert.IsNotNull(label);

                        string expectedLabel =
                            "The following packages will be installed using pip:\r\n" +
                            "\r\n" +
                            "ptvsd\r\n" +
                            "azure==0.1"; ;
                        Assert.AreEqual(expectedLabel, label.Current.HelpText);

                        dialog.Cancel();
                        try {
                            task.Wait(1000);
                            Assert.Fail("Command was not canceled after dismissing the package install confirmation dialog");
                        } catch (AggregateException ex) {
                            if (!(ex.InnerException is TaskCanceledException)) {
                                throw;
                            }
                        }
                    }
                } finally {
                    if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted) {
                        if (task.Wait(10000)) {
                            task.Dispose();
                        }
                    } else {
                        task.Dispose();
                    }
                }

                // Then, execute command and allow it to proceed.
                task = ExecuteAsync(node, "Require Packages");
                try {
                    var dialogHandle = app.WaitForDialog(task);
                    if (dialogHandle == IntPtr.Zero) {
                        if (task.IsFaulted && task.Exception != null) {
                            Assert.Fail("Unexpected exception in package install confirmation dialog:\n{0}", task.Exception);
                        } else {
                            Assert.AreNotEqual(IntPtr.Zero, dialogHandle);
                        }
                    }

                    using (var dialog = new AutomationDialog(app, AutomationElement.FromHandle(dialogHandle))) {
                        dialog.ClickButtonAndClose("CommandLink_1000", nameIsAutomationId: true);
                    }
                    task.Wait();

                    var ver = PythonVersion.Version.ToVersion();
                    ExpectOutputWindowText(app, string.Format("pass {0}.{1}", ver.Major, ver.Minor));
                } finally {
                    if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted) {
                        if (task.Wait(10000)) {
                            task.Dispose();
                        }
                    } else {
                        task.Dispose();
                    }
                }
            }
        }
Ejemplo n.º 28
0
        public void CustomCommandsErrorList() {
            using (var app = new PythonVisualStudioApp()) {
                PythonProjectNode node;
                EnvDTE.Project proj;
                OpenProject(app, "ErrorCommand.sln", out node, out proj);

                var expectedItems = new[] {
                    new { Document = "Program.py", Line = 0, Column = 1, Category = __VSERRORCATEGORY.EC_ERROR, Message = "This is an error with a relative path." },
                    new { Document = Path.Combine(node.ProjectHome, "Program.py"), Line = 2, Column = 3, Category = __VSERRORCATEGORY.EC_WARNING, Message = "This is a warning with an absolute path." },
                    new { Document = ">>>", Line = 4, Column = -1, Category = __VSERRORCATEGORY.EC_ERROR, Message = "This is an error with an invalid path." },
                };

                Execute(node, "Produce Errors");
                var items = app.WaitForErrorListItems(3);
                Console.WriteLine("Got errors:");
                foreach (var item in items) {
                    string document, text;
                    Assert.AreEqual(0, item.Document(out document), "HRESULT getting document");
                    Assert.AreEqual(0, item.get_Text(out text), "HRESULT getting message");
                    Console.WriteLine("  {0}: {1}", document ?? "(null)", text ?? "(null)");
                }
                Assert.AreEqual(expectedItems.Length, items.Count);

                // Second invoke should replace the error items in the list, not add new ones to those already existing.
                Execute(node, "Produce Errors");
                items = app.WaitForErrorListItems(3);
                Assert.AreEqual(expectedItems.Length, items.Count);

                items.Sort(Comparer<IVsTaskItem>.Create((x, y) => {
                    int lx, ly;
                    x.Line(out lx);
                    y.Line(out ly);
                    return lx.CompareTo(ly);
                }));

                for (int i = 0; i < expectedItems.Length; ++i) {
                    var item = items[i];
                    var expectedItem = expectedItems[i];

                    string document, message;
                    item.get_Text(out message);
                    item.Document(out document);

                    int line, column;
                    item.Line(out line);
                    item.Column(out column);

                    uint category;
                    ((IVsErrorItem)item).GetCategory(out category);

                    Assert.AreEqual(expectedItem.Document, document);
                    Assert.AreEqual(expectedItem.Line, line);
                    Assert.AreEqual(expectedItem.Column, column);
                    Assert.AreEqual(expectedItem.Message, message);
                    Assert.AreEqual(expectedItem.Category, (__VSERRORCATEGORY)category);
                }

                app.ServiceProvider.GetUIThread().Invoke((Action)delegate { items[0].NavigateTo(); });

                var doc = app.Dte.ActiveDocument;
                Assert.IsNotNull(doc);
                Assert.AreEqual("Program.py", doc.Name);

                var textDoc = (EnvDTE.TextDocument)doc.Object("TextDocument");
                Assert.AreEqual(1, textDoc.Selection.ActivePoint.Line);
                Assert.AreEqual(2, textDoc.Selection.ActivePoint.DisplayColumn);
            }
        }
Ejemplo n.º 29
0
        public void LaunchUnknownEnvironment() {
            using (var app = new PythonVisualStudioApp()) {
                var project = app.OpenProject(@"TestData\Environments\Unknown.sln");

                app.ExecuteCommand("Debug.Start");
                PythonVisualStudioApp.CheckMessageBox(MessageBoxButton.Ok, "Unknown Python 2.7", "incorrectly configured");
            }
        }
Ejemplo n.º 30
0
        public void CustomCommandsSearchPath() {
            var expectedSearchPath = string.Format("['{0}', '{1}', '{2}']",
                // Includes CWD (ProjectHome) first
                TestData.GetPath(@"TestData\Targets\Package\Subpackage").Replace("\\", "\\\\"),
                // Specified as '..\..' from ProjectHome
                TestData.GetPath(@"TestData\Targets").Replace("\\", "\\\\"),
                // Specified as '..' from ProjectHome
                TestData.GetPath(@"TestData\Targets\Package").Replace("\\", "\\\\")
            );
           
            using (var app = new PythonVisualStudioApp()) {
                PythonProjectNode node;
                EnvDTE.Project proj;
                OpenProject(app, "CommandSearchPath.sln", out node, out proj);

                Execute(node, "Import From Search Path");

                var outputWindow = app.Element.FindFirst(TreeScope.Descendants,
                    new AndCondition(
                        new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"),
                        new PropertyCondition(AutomationElement.NameProperty, "Output")
                    )
                );
                Assert.IsNotNull(outputWindow, "Output Window was not opened");

                ExpectOutputWindowText(app, expectedSearchPath);
            }
        }
Ejemplo n.º 31
0
        public static ReplWindowProxy Prepare(
            ReplWindowProxySettings settings,
            string projectName = null,
            bool useIPython    = false
            )
        {
            settings.AssertValid();

            var             app    = new PythonVisualStudioApp();
            ReplWindowProxy result = null;

            try {
                result = OpenInteractive(app, settings, projectName, useIPython ? IPythonBackend : StandardBackend);
                app    = null;

                for (int retries = 10; retries > 0; --retries)
                {
                    result.Reset();
                    result.ClearScreen();
                    result.ClearInput();

                    try {
                        var task = result.ExecuteText("print('READY')");
                        Assert.IsTrue(task.Wait(useIPython ? 30000 : 15000), "ReplWindow did not initialize in time");
                        if (!task.Result.IsSuccessful)
                        {
                            continue;
                        }
                    } catch (TaskCanceledException) {
                        continue;
                    }


                    if (useIPython)
                    {
                        // The longer we wait, the better are the chances of detecting this error
                        // This seems long enough to detect it when running locally
                        Thread.Sleep(500);

                        if (result.TextView.TextBuffer.CurrentSnapshot.Lines
                            .Any(l => l.GetText().Contains("Error using selected REPL back-end"))
                            )
                        {
                            Assert.Inconclusive("IPython is not available");
                        }

                        // In IPython mode, a help header appears at startup,
                        // but the output order is inconsistent, so we can't WaitForTextEnd
                        // (sometimes READY appears before help, sometimes after)
                        result.WaitForAnyLineContainsTextInternal("READY");
                        result.WaitForReadyForInput(TimeSpan.FromSeconds(5));
                    }
                    else
                    {
                        result.WaitForTextEnd("READY", ">");
                    }

                    result.ClearScreen();
                    return(result);
                }
                Assert.Fail("ReplWindow did not initialize");
                return(null);
            } finally {
                if (app != null)
                {
                    app.Dispose();
                }
            }
        }