Example #1
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({[\"\"]})");
            }
        }
Example #2
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 {
            }
        }
Example #3
0
        public void DeleteVirtualEnv() {
            using (var app = new PythonVisualStudioApp())
            using (var dis = Init(app)) {
                var options = app.GetService<PythonToolsService>().GeneralOptions;
                var oldAutoAnalyze = options.AutoAnalyzeStandardLibrary;
                app.OnDispose(() => { options.AutoAnalyzeStandardLibrary = oldAutoAnalyze; options.Save(); });
                options.AutoAnalyzeStandardLibrary = false;
                options.Save();

                var project = CreateTemporaryProject(app);

                string envName, envPath;
                TreeNode env;
                using (var ps = new ProcessScope("Microsoft.PythonTools.Analyzer")) {
                    env = app.CreateVirtualEnvironment(project, out envName, out envPath);

                    Assert.IsFalse(ps.WaitForNewProcess(TimeSpan.FromSeconds(10)).Any(), "Unexpected analyzer processes");
                }

                // Need to wait some more for the database to be loaded.
                app.WaitForNoDialog(TimeSpan.FromSeconds(10.0));

                env.Select();
                using (var removeDeleteDlg = RemoveItemDialog.FromDte(app)) {
                    removeDeleteDlg.Delete();
                }

                app.WaitForNoDialog(TimeSpan.FromSeconds(5.0));

                app.OpenSolutionExplorer().WaitForChildOfProjectRemoved(
                    project,
                    SR.GetString(SR.Environments),
                    envName
                );

                var projectHome = (string)project.Properties.Item("ProjectHome").Value;
                envPath = Path.Combine(projectHome, envPath);
                for (int retries = 10;
                    Directory.Exists(envPath) && retries > 0;
                    --retries) {
                    Thread.Sleep(1000);
                }
                Assert.IsFalse(Directory.Exists(envPath), envPath);
            }
        }
Example #4
0
        private static void CloudProjectTest(string roleType, bool openServiceDefinition) {
            Assert.IsTrue(roleType == "Web" || roleType == "Worker", "Invalid roleType: " + roleType);

            Assembly asm = null;
            try {
                asm = Assembly.Load("Microsoft.VisualStudio.CloudService.Wizard,Version=1.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a");
            } catch {
                // Failed to load - we'll skip the test below
            }
            
            if (asm != null && asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)
                .OfType<AssemblyFileVersionAttribute>()
                .Any(a => {
                    Version ver;
                    return Version.TryParse(a.Version, out ver) && ver < new Version(2, 5);
                })
            ) {
                Assert.Inconclusive("Test requires Microsoft Azure Tools 2.5 or later");
            }

            using (var app = new PythonVisualStudioApp())
            using (FileUtils.Backup(TestData.GetPath(@"TestData\CloudProject\ServiceDefinition.csdef"))) {
                app.OpenProject("TestData\\CloudProject.sln", expectedProjects: 3);

                var ccproj = app.Dte.Solution.Projects.Cast<Project>().FirstOrDefault(p => p.Name == "CloudProject");
                Assert.IsNotNull(ccproj);

                if (openServiceDefinition) {
                    var wnd = ccproj.ProjectItems.Item("ServiceDefinition.csdef").Open();
                    wnd.Activate();
                    app.OnDispose(() => wnd.Close());
                }

                IVsHierarchy hier;
                var sln = app.GetService<IVsSolution>(typeof(SVsSolution));
                ErrorHandler.ThrowOnFailure(sln.GetProjectOfUniqueName(ccproj.FullName, out hier));

                app.ServiceProvider.GetUIThread().InvokeAsync(() =>
                    PythonProjectNode.UpdateServiceDefinition(hier, roleType, roleType + "Role1", app.ServiceProvider)
                ).GetAwaiter().GetResult();

                var doc = new XmlDocument();
                for (int retries = 5; retries > 0; --retries) {
                    try {
                        doc.Load(TestData.GetPath(@"TestData\CloudProject\ServiceDefinition.csdef"));
                        break;
                    } catch (IOException ex) {
                        Console.WriteLine("Exception while reading ServiceDefinition.csdef.{0}{1}", Environment.NewLine, ex);
                    } catch (XmlException) {
                        var copyTo = TestData.GetPath(@"TestData\CloudProject\" + Path.GetRandomFileName());
                        File.Copy(TestData.GetPath(@"TestData\CloudProject\ServiceDefinition.csdef"), copyTo);
                        Console.WriteLine("Copied file to " + copyTo);
                        throw;
                    }
                    Thread.Sleep(100);
                }
                var ns = new XmlNamespaceManager(doc.NameTable);
                ns.AddNamespace("sd", "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition");
                doc.Save(Console.Out);

                var nav = doc.CreateNavigator();
                if (roleType == "Web") {
                    Assert.IsNotNull(nav.SelectSingleNode(
                        "/sd:ServiceDefinition/sd:WebRole[@name='WebRole1']/sd:Startup/sd:Task[@commandLine='ps.cmd ConfigureCloudService.ps1']",
                        ns
                    ));
                } else if (roleType == "Worker") {
                    Assert.IsNotNull(nav.SelectSingleNode(
                        "/sd:ServiceDefinition/sd:WorkerRole[@name='WorkerRole1']/sd:Startup/sd:Task[@commandLine='bin\\ps.cmd ConfigureCloudService.ps1']",
                        ns
                    ));
                    Assert.IsNotNull(nav.SelectSingleNode(
                        "/sd:ServiceDefinition/sd:WorkerRole[@name='WorkerRole1']/sd:Runtime/sd:EntryPoint/sd:ProgramEntryPoint[@commandLine='bin\\ps.cmd LaunchWorker.ps1']",
                        ns
                    ));
                }
            }
        }
Example #5
0
        /// <summary>
        /// Runs a single formatting test
        /// </summary>
        /// <param name="filename">The filename of the document to perform formatting in (lives in FormattingTests.sln)</param>
        /// <param name="selection">The selection to format, or null if formatting the entire document</param>
        /// <param name="expectedText">The expected source code after the formatting</param>
        /// <param name="changedSpans">The spans which should be marked as changed in the buffer after formatting</param>
        private static void FormattingTest(
            string filename,
            Span? selection,
            string expectedText,
            Span[] changedSpans,
            Func<PythonToolsService, object> updateSettings,
            Action<PythonToolsService, object> revertSettings,
            Version version = null
        ) {
            using (var app = new PythonVisualStudioApp())
            using (version == null ? null : app.SelectDefaultInterpreter(PythonPaths.Versions.FirstOrDefault(v => v.Version.ToVersion() >= version))) {
                var o = updateSettings?.Invoke(app.PythonToolsService);
                if (revertSettings != null) {
                    app.OnDispose(() => revertSettings(app.PythonToolsService, o));
                }

                var project = app.OpenProject(@"TestData\FormattingTests\FormattingTests.sln");
                var item = project.ProjectItems.Item(filename);
                var window = item.Open();
                window.Activate();
                var doc = app.GetDocument(item.Document.FullName);

                var aggFact = app.ComponentModel.GetService<IViewTagAggregatorFactoryService>();
                var changeTags = aggFact.CreateTagAggregator<ChangeTag>(doc.TextView);

                // format the selection or document
                if (selection == null) {
                    DoFormatDocument();
                } else {
                    doc.Invoke(() => doc.TextView.Selection.Select(new SnapshotSpan(doc.TextView.TextBuffer.CurrentSnapshot, selection.Value), false));
                    DoFormatSelection();
                }

                // verify the contents are correct
                string actual = null;
                int steady = 50;
                for (int i = 0; i < 100; i++) {
                    actual = doc.TextView.TextBuffer.CurrentSnapshot.GetText();

                    if (expectedText == actual) {
                        if (--steady <= 0) {
                            break;
                        }
                    } else {
                        steady = 50;
                    }
                    System.Threading.Thread.Sleep(100);
                }
                Assert.AreEqual(expectedText, actual);

                // verify the change tags are correct
                var snapshot = doc.TextView.TextBuffer.CurrentSnapshot;
                var tags = changeTags.GetTags(
                    new SnapshotSpan(
                        doc.TextView.TextBuffer.CurrentSnapshot,
                        new Span(0, doc.TextView.TextBuffer.CurrentSnapshot.Length)
                    )
                );
                List<Span> result = new List<Span>();
                foreach (var tag in tags) {
                    result.Add(
                        new Span(
                            tag.Span.Start.GetPoint(doc.TextView.TextBuffer.CurrentSnapshot, PositionAffinity.Successor).Value.Position,
                            tag.Span.End.GetPoint(doc.TextView.TextBuffer.CurrentSnapshot, PositionAffinity.Successor).Value.Position
                        )
                    );
                }

                // dump the spans for creating tests easier
                foreach (var span in result) {
                    Console.WriteLine(span);
                }

                Assert.AreEqual(result.Count, changedSpans.Length);
                for (int i = 0; i < result.Count; i++) {
                    Assert.AreEqual(result[i], changedSpans[i]);
                }
            }
        }
Example #6
0
        private static void SquiggleShowHide(string document, Action<PythonVisualStudioApp> test) {
            using (var app = new PythonVisualStudioApp()) {
                UnresolvedImportSquiggleProvider._alwaysCreateSquiggle = true;
                app.OnDispose(() => UnresolvedImportSquiggleProvider._alwaysCreateSquiggle = false);


                var project = app.OpenProject(@"TestData\MissingImport.sln");

                var editorWindows = app.Dte.Windows
                    .OfType<EnvDTE.Window>()
                    .Where(w => w.Kind == "Editor")
                    .ToArray();
                foreach (var w in editorWindows) {
                    w.Close(vsSaveChanges.vsSaveChangesNo);
                }

                var wnd = project.ProjectItems.Item(document).Open();
                wnd.Activate();
                try {
                    test(app);
                } finally {
                    wnd.Close();
                }
            }
        }
Example #7
0
        public void IndentationInconsistencyIgnore() {
            using (var app = new PythonVisualStudioApp()) {
                var options = app.Options;
                var severity = options.IndentationInconsistencySeverity;
                options.IndentationInconsistencySeverity = Severity.Ignore;
                app.OnDispose(() => options.IndentationInconsistencySeverity = severity);

                var project = app.OpenProject(@"TestData\InconsistentIndentation.sln");

                List<IVsTaskItem> items = app.WaitForErrorListItems(0);
                Assert.AreEqual(0, items.Count);
            }
        }
Example #8
0
        public void IndentationInconsistencyError() {
            using (var app = new PythonVisualStudioApp()) {
                var options = app.Options;
                var severity = options.IndentationInconsistencySeverity;
                options.IndentationInconsistencySeverity = Severity.Error;
                app.OnDispose(() => options.IndentationInconsistencySeverity = severity);

                var project = app.OpenProject(@"TestData\InconsistentIndentation.sln");

                var items = app.WaitForErrorListItems(1);
                Assert.AreEqual(1, items.Count);

                VSTASKPRIORITY[] pri = new VSTASKPRIORITY[1];
                ErrorHandler.ThrowOnFailure(items[0].get_Priority(pri));
                Assert.AreEqual(VSTASKPRIORITY.TP_HIGH, pri[0]);
            }
        }
Example #9
0
        public void AutoIndent() {
            using (var app = new PythonVisualStudioApp()) {
                var options = app.GetService<PythonToolsService>().AdvancedOptions;
                var prevSetting = options.AddNewLineAtEndOfFullyTypedWord;
                app.OnDispose(() => options.AddNewLineAtEndOfFullyTypedWord = prevSetting);
                options.AddNewLineAtEndOfFullyTypedWord = true;

                var project = app.OpenProject(@"TestData\AutoIndent.sln");


                // http://pytools.codeplex.com/workitem/116
                AutoIndentTest(app, project, "def f():\rprint 'hi'\r\rdef inner(): pass←←←←←←←←←←←←←←←←←\r", @"def f():
    print 'hi'

    
    def inner(): pass");

                // http://pytools.codeplex.com/workitem/121
                AutoIndentTest(app, project, "x = {'a': [1, 2, 3],\r\r'b':42}", @"x = {'a': [1, 2, 3],

     'b':42}");

                AutoIndentTest(app, project, "x = {  #comment\r'a': [\r1,\r2,\r3\r],\r\r'b':42\r}", @"x = {  #comment
    'a': [
        1,
        2,
        3
        ],

    'b':42
    }");

                AutoIndentTest(app, project, "if True:\rpass\r\r42\r\r", @"if True:
    pass

42

");

                AutoIndentTest(app, project, "def f():\rreturn\r\r42\r\r", @"def f():
    return

42

");

                AutoIndentTest(app, project, "if True: #fob\rpass\relse: #oar\rpass\r\r42\r\r", @"if True: #fob
    pass
else: #oar
    pass

42

");

                AutoIndentTest(app, project, "if True:\rraise Exception()\r\r42\r\r", @"if True:
    raise Exception()

42

");

                AutoIndentTest(app, project, "while True:\rcontinue\r\r42\r\r", @"while True:
    continue

42

");

                AutoIndentTest(app, project, "while True:\rbreak\r\r42\r\r", @"while True:
    break

42

");
                // http://pytools.codeplex.com/workitem/127
                AutoIndentTest(app, project, "print ('%s, %s' %\r(1, 2))", @"print ('%s, %s' %
       (1, 2))");

                // http://pytools.codeplex.com/workitem/125
                AutoIndentTest(app, project, "def f():\rx = (\r7)\rp", @"def f():
    x = (
        7)
    p");

                AutoIndentTest(app, project, "def f():\rassert False, \\\r'A message'\rp", @"def f():
    assert False, \
        'A message'
    p");

                // other tests...
                AutoIndentTest(app, project, "1 +\\\r2 +\\\r3 +\\\r4 + 5\r", @"1 +\
    2 +\
    3 +\
    4 + 5
");


                AutoIndentTest(app, project, "x = {42 :\r42}\rp", @"x = {42 :
     42}
p");

                AutoIndentTest(app, project, "def f():\rreturn (42,\r100)\r\rp", @"def f():
    return (42,
            100)

p");

                AutoIndentTest(app, project, "print ('a',\r'b',\r'c')\rp", @"print ('a',
       'b',
       'c')
p");

                AutoIndentTest(app, project, "foooo ('a',\r'b',\r'c')\rp", @"foooo ('a',
       'b',
       'c')
p");

                // http://pytools.codeplex.com/workitem/157
                AutoIndentTest(app, project, "def a():\rif b():\rif c():\rd()\rp", @"def a():
    if b():
        if c():
            d()
            p");

                AutoIndentTest(app, project, "a_list = [1, 2, 3]\rdef func():\rpass", @"a_list = [1, 2, 3]
def func():
    pass");

                AutoIndentTest(app, project, "class A:\rdef funcA(self, a):\rreturn a\r\rdef funcB(self):\rpass", @"class A:
    def funcA(self, a):
        return a

    def funcB(self):
        pass");

                AutoIndentTest(app, project, "print('abc')\rimport sys\rpass", @"print('abc')
import sys
pass");

                AutoIndentTest(app, project, "a_list = [1, 2, 3]\rimport os\rpass", @"a_list = [1, 2, 3]
import os
pass");

                AutoIndentTest(app, project, "class C:\rdef fob(self):\r'doc string'\rpass", @"class C:
    def fob(self):
        'doc string'
        pass");

                AutoIndentTest(app, project, "def g():\rfob(15)\r\r\bfob(1)\rpass", @"def g():
    fob(15)

fob(1)
pass");

                AutoIndentTest(app, project, "def m():\rif True:\rpass\relse:\rabc()\r\r\b\bm()\r\rm()\rpass", @"def m():
    if True:
        pass
    else:
        abc()

m()

m()
pass");
            }
        }