Esempio n. 1
0
        /// <summary>
        /// 删除空间留言
        /// </summary>
        /// <param name="loginUserId">登录用户编号</param>
        /// <param name="commentId">留言内容</param>
        /// <returns></returns>
        public bool DeleteSpaceComment(int loginUserId, int commentId)
        {
            #region 验证参数是否正确
            AssertUtil.AreBigger(loginUserId, 0, "用户未登录");
            AssertUtil.AreBigger(commentId, 0, "回复留言不存在");
            #endregion

            var success = Execute <bool>((db) =>
            {
                #region 验证数据库是否存在
                var loginUser = db.User.FirstOrDefault(u => u.State == false && u.Id == loginUserId);
                AssertUtil.IsNotNull(loginUser, "用户不存在或者被禁用");
                var comment = db.Comments.FirstOrDefault(c => c.State >= 0 &&
                                                         c.Id == commentId &&
                                                         c.EntityType == (int)CommentEnum.User);
                AssertUtil.IsNotNull(comment, "回复的留言可能已经被删除或者审核不通过");
                #endregion

                AssertUtil.AreEqual(loginUser.Id, comment.EntityId, "只有空间用户才能删除留言");

                var childCommnets = db.Comments.Where(c => c.State >= (int)CommentStateEnum.Waiting && c.EntityType == (int)CommentEnum.User && c.LocalPath.StartsWith(comment.LocalPath));
                foreach (var childCommnet in childCommnets)
                {
                    db.Entry <Comments>(childCommnet).State = EntityState.Deleted;
                }
                db.Configuration.ValidateOnSaveEnabled = false;
                return(db.SaveChanges() > 0);
            });
            if (success)
            {
                CreateCache <Comments>();
            }
            return(success);
        }
Esempio n. 2
0
        public void ProviderLoadLog_Success()
        {
            var sp  = new MockServiceProvider();
            var log = new MockActivityLog();

            sp.Services[typeof(SVsActivityLog).GUID] = log;
            var sm = new MockSettingsManager();

            sp.Services[typeof(SVsSettingsManager).GUID] = sm;

            var path = FactoryProviderSuccessPath;

            sm.Store.AddSetting(@"PythonTools\InterpreterFactories\Test", "CodeBase", path);

            var service = new InterpreterOptionsService(sp);

            foreach (var msg in log.AllItems)
            {
                Console.WriteLine(msg);
            }

            AssertUtil.AreEqual(
                new Regex(@"Information//Python Tools//Loading interpreter provider assembly.*//" + Regex.Escape(path)),
                log.AllItems.Single()
                );

            Assert.AreEqual(1, service.KnownProviders.Count());
        }
Esempio n. 3
0
        public void UpdateWebRoleServiceDefinitionTest()
        {
            var doc = new XmlDocument();

            doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
<ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3"">
  <WorkerRole name=""PythonApplication1"" vmsize=""Small"" />
  <WebRole name=""PythonApplication2"" />
</ServiceDefinition>");

            PythonProjectNode.UpdateServiceDefinition(doc, "Web", "PythonApplication2");

            AssertUtil.AreEqual(@"<?xml version=""1.0"" encoding=""utf-8""?>
<ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3"">
  <WorkerRole name=""PythonApplication1"" vmsize=""Small"" />
  <WebRole name=""PythonApplication2"">
    <Startup>
      <Task commandLine=""ps.cmd ConfigureCloudService.ps1"" executionContext=""elevated"" taskType=""simple"">
        <Environment>
          <Variable name=""EMULATED"">
            <RoleInstanceValue xpath=""/RoleEnvironment/Deployment/@emulated"" />
          </Variable>
        </Environment>
      </Task>
    </Startup>
  </WebRole>
</ServiceDefinition>", doc);
        }
Esempio n. 4
0
        public void ProviderLoadLog_SuccessAndFailure()
        {
            var sp  = new MockServiceProvider();
            var log = new MockActivityLog();

            sp.Services[typeof(SVsActivityLog).GUID] = log;
            var sm = new MockSettingsManager();

            sp.Services[typeof(SVsSettingsManager).GUID] = sm;

            var path1 = FactoryProviderTypeLoadErrorPath;
            var path2 = FactoryProviderSuccessPath;

            sm.Store.AddSetting(@"PythonTools\InterpreterFactories\Test1", "CodeBase", path1);
            sm.Store.AddSetting(@"PythonTools\InterpreterFactories\Test2", "CodeBase", path2);

            var service = new InterpreterOptionsService(sp);

            foreach (var msg in log.AllItems)
            {
                Console.WriteLine(msg);
            }

            AssertUtil.AreEqual(
                new Regex(@"Error//Python Tools//Failed to import factory providers.*System\.ComponentModel\.Composition\.CompositionException"),
                log.ErrorsAndWarnings.Single()
                );

            Assert.AreEqual(1, service.KnownProviders.Count());
        }
Esempio n. 5
0
        public void ProviderLoadLog_CorruptImage()
        {
            var sp  = new MockServiceProvider();
            var log = new MockActivityLog();

            sp.Services[typeof(SVsActivityLog).GUID] = log;
            var sm = new MockSettingsManager();

            sp.Services[typeof(SVsSettingsManager).GUID] = sm;

            var path = FactoryProviderCorruptPath;

            sm.Store.AddSetting(@"PythonTools\InterpreterFactories\Test", "CodeBase", path);

            var service = new InterpreterOptionsService(sp);

            foreach (var msg in log.AllItems)
            {
                Console.WriteLine(msg);
            }

            AssertUtil.AreEqual(
                new Regex(@"Error//Python Tools//Failed to load interpreter provider assembly.+System\.BadImageFormatException.+//" + Regex.Escape(path)),
                log.ErrorsAndWarnings.Single()
                );
        }
Esempio n. 6
0
        public void ProviderLoadLog_FileNotFound()
        {
            var sp  = new MockServiceProvider();
            var log = new MockActivityLog();

            sp.Services[typeof(SVsActivityLog).GUID] = log;
            var sm = new MockSettingsManager();

            sp.Services[typeof(SVsSettingsManager).GUID] = sm;

            var path = Path.ChangeExtension(Path.GetTempFileName(), "dll");

            File.Delete(path);
            Assert.IsFalse(File.Exists(path));

            sm.Store.AddSetting(@"PythonTools\InterpreterFactories\Test", "CodeBase", path);

            var service = new InterpreterOptionsService(sp);

            foreach (var msg in log.AllItems)
            {
                Console.WriteLine(msg);
            }

            AssertUtil.AreEqual(
                new Regex(@"Error//Python Tools//Failed to load interpreter provider assembly.+System\.IO\.FileNotFoundException.+//" + Regex.Escape(path)),
                log.ErrorsAndWarnings.Single()
                );
        }
Esempio n. 7
0
        public void RunElevatedProcess()
        {
            var fact       = Factories.First();
            var output     = new List <string>();
            var redirector = new ListRedirector(output);

            using (var process = ProcessOutput.RunElevated(
                       fact.Configuration.InterpreterPath,
                       new[] { "-c", "import os, sys; print(sys.version[:3]); print(os.getcwd()); print(os.getenv('TEST_KEY')); sys.exit(7)" },
                       fact.Configuration.GetPrefixPath(),
                       new[] { new KeyValuePair <string, string>("TEST_KEY", "TEST_VALUE") },
                       redirector,
                       quoteArgs: true,
                       elevate: false // don't really elevate for the test
                       )) {
                Assert.IsTrue(process.Wait(TimeSpan.FromSeconds(30)), "Running " + fact.Configuration.Description + " exceeded timeout");

                Console.WriteLine(string.Join(Environment.NewLine, output));

                Assert.AreEqual(7, process.ExitCode);
                AssertUtil.AreEqual(output,
                                    fact.Configuration.Version.ToString(),
                                    PathUtils.TrimEndSeparator(fact.Configuration.GetPrefixPath()),
                                    "TEST_VALUE"
                                    );
            }
        }
Esempio n. 8
0
        public void UnresolvedImportSquiggle()
        {
            var buffer    = new MockTextBuffer("import fob, oar\r\nfrom baz import *\r\nfrom .spam import eggs", PythonCoreConstants.ContentType, filename: "C:\\name.py");
            var squiggles = AnalyzeTextBuffer(buffer).Select(FormatErrorTag).ToArray();

            Console.WriteLine(" Squiggles found:");
            foreach (var actual in squiggles)
            {
                Console.WriteLine(actual);
            }
            Console.WriteLine(" Found {0} squiggle(s)", squiggles.Length);

            int i = 0;

            foreach (var expected in new[] {
                // Ensure that the warning includes the module name
                @".*warning:.*fob.*\(7-10\)",
                @".*warning:.*oar.*\(12-15\)",
                @".*warning:.*baz.*\(22-25\)",
                @".*warning:.*\.spam.*\(41-46\)"
            })
            {
                Assert.IsTrue(i < squiggles.Length, "Not enough squiggles");
                AssertUtil.AreEqual(new Regex(expected, RegexOptions.IgnoreCase | RegexOptions.Singleline), squiggles[i]);
                i += 1;
            }
        }
Esempio n. 9
0
        public void Scripting_Nudge()
        {
            var client = this.GetScriptingClient();

            client.Document.New();
            client.Page.New(new VA.Drawing.Size(4, 4), false);

            var s1 = client.Draw.Rectangle(1, 1, 1.25, 1.5);
            var s2 = client.Draw.Rectangle(2, 3, 2.5, 3.5);
            var s3 = client.Draw.Rectangle(4.5, 2.5, 6, 3.5);

            client.Selection.SelectNone();
            client.Selection.Select(s1);
            client.Selection.Select(s2);
            client.Selection.Select(s3);

            var targets = new VisioAutomation.Scripting.TargetShapes();

            client.Arrange.Nudge(targets, 1, -1);

            var xforms = VisioAutomation.Shapes.XFormCells.GetCells(client.Page.Get(), new[] { s1.ID, s2.ID, s3.ID });

            AssertUtil.AreEqual(2.125, 0.25, xforms[0].GetPinPosResult(), 0.00001);
            AssertUtil.AreEqual(3.25, 2.25, xforms[1].GetPinPosResult(), 0.00001);
            AssertUtil.AreEqual(6.25, 2, xforms[2].GetPinPosResult(), 0.00001);
            client.Document.Close(true);
        }
Esempio n. 10
0
        public void UnavailableEnvironments()
        {
            var collection = new Microsoft.Build.Evaluation.ProjectCollection();

            try {
                var service = new MockInterpreterOptionsService();
                var proj    = collection.LoadProject(TestData.GetPath(@"TestData\Environments\Unavailable.pyproj"));

                using (var provider = new MSBuildProjectInterpreterFactoryProvider(service, proj)) {
                    try {
                        provider.DiscoverInterpreters();
                        Assert.Fail("Expected InvalidDataException in DiscoverInterpreters");
                    } catch (InvalidDataException ex) {
                        AssertUtil.AreEqual(ex.Message
                                            .Replace(TestData.GetPath("TestData\\Environments\\"), "$")
                                            .Split('\r', '\n')
                                            .Where(s => !string.IsNullOrEmpty(s))
                                            .Select(s => s.Trim()),
                                            "Some project interpreters failed to load:",
                                            @"Interpreter $env\ has invalid value for 'Id': INVALID ID",
                                            @"Interpreter $env\ has invalid value for 'Version': INVALID VERSION",
                                            @"Base interpreter $env\ has invalid value for 'BaseInterpreter': INVALID BASE",
                                            @"Interpreter $env\ has invalid value for 'InterpreterPath': INVALID<>PATH",
                                            @"Interpreter $env\ has invalid value for 'WindowsInterpreterPath': INVALID<>PATH",
                                            @"Interpreter $env\ has invalid value for 'LibraryPath': INVALID<>PATH",
                                            @"Base interpreter $env\ has invalid value for 'BaseInterpreter': {98512745-4ac7-4abb-9f33-120af32edc77}"
                                            );
                    }

                    var factories = provider.GetInterpreterFactories().ToList();
                    foreach (var fact in factories)
                    {
                        Console.WriteLine("{0}: {1}", fact.GetType().FullName, fact.Description);
                    }

                    foreach (var fact in factories)
                    {
                        Assert.IsInstanceOfType(
                            fact,
                            typeof(MSBuildProjectInterpreterFactoryProvider.NotFoundInterpreterFactory),
                            string.Format("{0} was not correct type", fact.Description)
                            );
                        Assert.IsFalse(provider.IsAvailable(fact), string.Format("{0} was not unavailable", fact.Description));
                    }

                    AssertUtil.AreEqual(factories.Select(f => f.Description),
                                        "Invalid BaseInterpreter (unavailable)",
                                        "Invalid InterpreterPath (unavailable)",
                                        "Invalid WindowsInterpreterPath (unavailable)",
                                        "Invalid LibraryPath (unavailable)",
                                        "Absent BaseInterpreter (unavailable)",
                                        "Unknown Python 2.7"
                                        );
                }
            } finally {
                collection.UnloadAllProjects();
                collection.Dispose();
            }
        }
Esempio n. 11
0
 public void AssertDiagnostics(IPythonProjectEntry module, params string[] diagnostics)
 {
     global::System.String[] diags = GetDiagnostics(module);
     foreach (global::System.String d in diags)
     {
         Console.WriteLine($"\"{d.Replace("\\", "\\\\")}\",");
     }
     AssertUtil.AreEqual(diags, diagnostics);
 }
Esempio n. 12
0
        private static void AssertTags(ITextBuffer buffer, params string[] spans)
        {
            var tags = OutliningTaggerProvider.OutliningTagger.ProcessCellTags(
                buffer.CurrentSnapshot,
                CancellationTokens.After1s
                ).ToList();

            AssertUtil.AreEqual(tags.Select(t => t.Span.Span.ToString()), spans);
        }
Esempio n. 13
0
        public void EncodeToStream()
        {
            var sb    = new StringBuilder();
            var bytes = new byte[256];
            int read;

            sb.Append('\ufeff', 12);

            for (int chunkSize = 1; chunkSize < 14; ++chunkSize)
            {
                Console.WriteLine($"Chunk size: {chunkSize}");
                read = ProjectEntry.EncodeToStream(sb, Encoding.UTF8, chunkSize).Read(bytes, 0, bytes.Length);
                Assert.AreEqual(39, read);
                for (int i = 0; i < read; i += 3)
                {
                    Console.WriteLine($"At {i}: {bytes[i]}, {bytes[i + 1]}, {bytes[i + 2]}");
                    AssertUtil.AreEqual(bytes.Skip(i).Take(3).ToArray(), (byte)239, (byte)187, (byte)191);
                }
            }

            for (int chunkSize = 1; chunkSize < 14; ++chunkSize)
            {
                Console.WriteLine($"Chunk size: {chunkSize}");
                read = ProjectEntry.EncodeToStream(sb, new UTF8Encoding(false), chunkSize).Read(bytes, 0, bytes.Length);
                Assert.AreEqual(36, read);
                for (int i = 0; i < read; i += 3)
                {
                    Console.WriteLine($"At {i}: {bytes[i]}, {bytes[i + 1]}, {bytes[i + 2]}");
                    AssertUtil.AreEqual(bytes.Skip(i).Take(3).ToArray(), (byte)239, (byte)187, (byte)191);
                }
            }

            for (int chunkSize = 1; chunkSize < 14; ++chunkSize)
            {
                Console.WriteLine($"Chunk size: {chunkSize}");
                read = ProjectEntry.EncodeToStream(sb, Encoding.Unicode, chunkSize).Read(bytes, 0, bytes.Length);
                Assert.AreEqual(26, read);
                for (int i = 0; i < read; i += 2)
                {
                    Console.WriteLine($"At {i}: {bytes[i]}, {bytes[i + 1]}");
                    AssertUtil.AreEqual(bytes.Skip(i).Take(2).ToArray(), (byte)0xFF, (byte)0xFE);
                }
            }

            for (int chunkSize = 1; chunkSize < 14; ++chunkSize)
            {
                Console.WriteLine($"Chunk size: {chunkSize}");
                read = ProjectEntry.EncodeToStream(sb, new UnicodeEncoding(false, false), chunkSize).Read(bytes, 0, bytes.Length);
                Assert.AreEqual(24, read);
                for (int i = 0; i < read; i += 2)
                {
                    Console.WriteLine($"At {i}: {bytes[i]}, {bytes[i + 1]}");
                    AssertUtil.AreEqual(bytes.Skip(i).Take(2).ToArray(), (byte)0xFF, (byte)0xFE);
                }
            }
        }
Esempio n. 14
0
        public void UnavailableEnvironments()
        {
            var collection = new Microsoft.Build.Evaluation.ProjectCollection();

            try {
                var service         = new MockInterpreterOptionsService();
                var proj            = collection.LoadProject(TestData.GetPath(@"TestData\Environments\Unavailable.pyproj"));
                var contextProvider = new MockProjectContextProvider(proj);

                var logger = new MockLogger();

                using (var provider = new MSBuildProjectInterpreterFactoryProvider(
                           new[] { new Lazy <IProjectContextProvider>(() => contextProvider) },
                           null,
                           new[] { new Lazy <IInterpreterLog>(() => logger) })) {
                    var configs = provider.GetInterpreterConfigurations().ToArray();
                    // force the load...
                    AssertUtil.AreEqual(
                        logger.Errors.ToString()
                        .Replace(TestData.GetPath("TestData\\Environments\\"), "$")
                        .Split('\r', '\n')
                        .Where(s => !string.IsNullOrEmpty(s))
                        .Select(s => s.Trim()),
                        @"Interpreter $env\ has invalid value for 'Id':",
                        @"Interpreter $env\ has invalid value for 'Version': INVALID VERSION",
                        @"Interpreter $env\ has invalid value for 'InterpreterPath': INVALID<>PATH",
                        @"Interpreter $env\ has invalid value for 'WindowsInterpreterPath': INVALID<>PATH"
                        );

                    var factories = provider.GetInterpreterFactories().ToList();
                    foreach (var fact in factories)
                    {
                        Console.WriteLine("{0}: {1}", fact.GetType().FullName, fact.Configuration.Description);
                    }

                    foreach (var fact in factories)
                    {
                        Assert.IsInstanceOfType(
                            fact,
                            typeof(NotFoundInterpreterFactory),
                            string.Format("{0} was not correct type", fact.Configuration.Description)
                            );
                        Assert.IsFalse(fact.Configuration.IsAvailable(), string.Format("{0} was not unavailable", fact.Configuration.Description));
                    }

                    AssertUtil.AreEqual(factories.Select(f => f.Configuration.Description),
                                        "Invalid InterpreterPath (unavailable)",
                                        "Invalid WindowsInterpreterPath (unavailable)"
                                        );
                }
            } finally {
                collection.UnloadAllProjects();
                collection.Dispose();
            }
        }
Esempio n. 15
0
        public async Task HandledImportSquiggle()
        {
            var testCases = new List <Tuple <string, string[]> >();

            testCases.Add(Tuple.Create(
                              "try:\r\n    import spam\r\nexcept ValueError:\r\n    pass\r\n",
                              new[] { @".*warning:.*spam.*\(Python.+:17-21\)" }
                              ));

            testCases.AddRange(
                new[] { "", " BaseException", " Exception", " ImportError", " (ValueError, ImportError)" }
                .Select(ex => Tuple.Create(
                            string.Format("try:\r\n    import spam\r\nexcept{0}:\r\n    pass\r\n", ex),
                            new string[0]
                            ))
                );

            using (PythonEditor view = new PythonEditor())
            {
                var errorProvider = view.VS.ServiceProvider.GetComponentModel().GetService <IErrorProviderFactory>();
                var tagger        = errorProvider.GetErrorTagger(view.View.TextView.TextBuffer);
                // Ensure all tasks have been updated
                var taskProvider = (ErrorTaskProvider)view.VS.ServiceProvider.GetService(typeof(ErrorTaskProvider));
                Assert.IsNotNull(taskProvider, "no ErrorTaskProvider available");

                foreach (var testCase in testCases)
                {
                    view.Text = testCase.Item1;
                    var time = await taskProvider.FlushAsync();

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

                    var squiggles = tagger.GetTaggedSpans(new SnapshotSpan(view.CurrentSnapshot, 0, view.CurrentSnapshot.Length))
                                    .Select(FormatErrorTag)
                                    .ToList();

                    Console.WriteLine(testCase.Item1);
                    Console.WriteLine(" Squiggles found:");
                    foreach (var actual in squiggles)
                    {
                        Console.WriteLine(actual);
                    }
                    Console.WriteLine(" Found {0} squiggle(s)", squiggles.Count);
                    Console.WriteLine();

                    int i = 0;
                    foreach (var expected in testCase.Item2)
                    {
                        Assert.IsTrue(i < squiggles.Count, "Not enough squiggles");
                        AssertUtil.AreEqual(new Regex(expected, RegexOptions.IgnoreCase | RegexOptions.Singleline), squiggles[i]);
                        i += 1;
                    }
                }
            }
        }
Esempio n. 16
0
        public void AssertHasParameters(IPythonProjectEntry module, string expr, int index, params string[] paramNames)
        {
            var sigs = module.Analysis.GetSignaturesByIndex(expr, index).ToArray();

            foreach (var s in sigs)
            {
                var parameters = string.Join(", ", s.Parameters.Select(p => $"{p.Name} : {p.Type ?? "(null)"} = {p.DefaultValue ?? "(null)"}"));
                Trace.WriteLine($"{s.Name}({parameters})");
            }
            AssertUtil.AreEqual(sigs.Single().Parameters.Select(p => p.Name), paramNames);
        }
        public void BuiltinFunctionSigHelp()
        {
            var view = CreateViewAndAnalyze();

            view.Type("min(");

            var session = view.TopSession as ISignatureHelpSession;

            Assert.IsNotNull(session);

            AssertUtil.AreEqual(new Regex(@".+?min\(x\: object\).+?"), session.Signatures[0].Documentation);
        }
        public void FindRequirementsRegexTest()
        {
            var r = PythonProjectNode.FindRequirementRegex;

            AssertUtil.AreEqual(r.Matches("aaaa bbbb cccc").Cast <Match>().Select(m => m.Value),
                                "aaaa",
                                "bbbb",
                                "cccc"
                                );
            AssertUtil.AreEqual(r.Matches("aaaa#a\r\nbbbb#b\r\ncccc#c\r\n").Cast <Match>().Select(m => m.Value),
                                "aaaa",
                                "bbbb",
                                "cccc"
                                );

            AssertUtil.AreEqual(r.Matches("a==1 b!=2 c<=3").Cast <Match>().Select(m => m.Value),
                                "a==1",
                                "b!=2",
                                "c<=3"
                                );

            AssertUtil.AreEqual(r.Matches("a==1 b!=2 c<=3").Cast <Match>().Select(m => m.Groups["name"].Value),
                                "a",
                                "b",
                                "c"
                                );

            AssertUtil.AreEqual(r.Matches("a==1#a\r\nb!=2#b\r\nc<=3#c\r\n").Cast <Match>().Select(m => m.Value),
                                "a==1",
                                "b!=2",
                                "c<=3"
                                );

            AssertUtil.AreEqual(r.Matches("a == 1 b != 2 c <= 3").Cast <Match>().Select(m => m.Value),
                                "a == 1",
                                "b != 2",
                                "c <= 3"
                                );

            AssertUtil.AreEqual(r.Matches("a == 1 b != 2 c <= 3").Cast <Match>().Select(m => m.Groups["name"].Value),
                                "a",
                                "b",
                                "c"
                                );

            AssertUtil.AreEqual(r.Matches("a -u b -f:x c").Cast <Match>().Select(m => m.Groups["name"].Value),
                                "a",
                                "b",
                                "c"
                                );
        }
Esempio n. 19
0
        public void TreeLayout_MultiNode()
        {
            // Verify that a tree with multiple nodes can be drawn
            // Note that  the DefaultNodeSize option is being used

            var t = new TREEMODEL.Drawing();

            t.Root = new TREEMODEL.Node("Root");

            var na = new TREEMODEL.Node("A");
            var nb = new TREEMODEL.Node("B");

            var na1 = new TREEMODEL.Node("A1");
            var na2 = new TREEMODEL.Node("A2");

            var nb1 = new TREEMODEL.Node("B1");
            var nb2 = new TREEMODEL.Node("B2");

            t.Root.Children.Add(na);
            t.Root.Children.Add(nb);

            na.Children.Add(na1);
            na.Children.Add(na2);

            nb.Children.Add(nb1);
            nb1.Children.Add(nb2);

            t.LayoutOptions.DefaultNodeSize = new VA.Drawing.Size(1, 1);

            var app  = this.GetVisioApplication();
            var doc  = this.GetNewDoc();
            var page = app.ActivePage;

            t.Render(page);

            AssertUtil.AreEqual(5.25, 8.0, VisioAutomationTest.GetPageSize(page), 0.05);

            Assert.AreEqual("Root", t.Root.VisioShape.Text);
            Assert.AreEqual("A", na.VisioShape.Text);
            Assert.AreEqual("B", nb.VisioShape.Text);

            Assert.AreEqual("A1", na1.VisioShape.Text);
            Assert.AreEqual("A2", na2.VisioShape.Text);

            Assert.AreEqual("B1", nb1.VisioShape.Text);
            Assert.AreEqual("B2", nb2.VisioShape.Text);

            doc.Close(true);
        }
Esempio n. 20
0
        public void TreeLayout_SingleNode()
        {
            // Verify that a tree with a single node can be drawn
            var t = new TREEMODEL.Drawing();

            t.Root = new TREEMODEL.Node("Root");

            var app  = this.GetVisioApplication();
            var doc  = this.GetNewDoc();
            var page = app.ActivePage;

            t.Render(page);

            AssertUtil.AreEqual(3.0, 1.5, VisioAutomationTest.GetPageSize(page), 0.05);

            doc.Close(true);
        }
Esempio n. 21
0
        private static void AddLightBulbTest(EditorWindow doc, int line, int column, string[] expectedActions, int invokeAction = -1, string expectedText = null)
        {
            doc.InvokeTask(async() => {
                var point = doc.TextView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(line - 1).Start.Add(column - 1);
                doc.TextView.Caret.MoveTo(point);

                // Note that this waits for language server to be up and running
                // but that doesn't mean the quick actions are ready for that document
                // so the test will need to wait/try again until the correct results
                // are in or until a predetermined timeout.
                await doc.WaitForLanguageServerInitializedAtCaretAsync();
            });

            if (expectedActions.Length > 0)
            {
                using (var sh = doc.StartLightBulbSession()) {
                    var actions = sh.Session.Actions.ToList();
                    if (expectedActions[0] == "*")
                    {
                        AssertUtil.ContainsAtLeast(
                            actions.Select(a => a.DisplayText.Replace("__", "_")),
                            expectedActions.Skip(1)
                            );
                    }
                    else
                    {
                        AssertUtil.AreEqual(
                            actions.Select(a => a.DisplayText.Replace("__", "_")).ToArray(),
                            expectedActions
                            );
                    }

                    if (invokeAction >= 0)
                    {
                        var action = actions.FirstOrDefault(a => a.DisplayText.Replace("__", "_") == expectedActions[invokeAction]);
                        Assert.IsNotNull(action, "No action named " + expectedActions[invokeAction]);
                        doc.Invoke(() => action.Invoke());
                        doc.WaitForText(expectedText);
                    }
                }
            }
            else
            {
                doc.StartLightBulbSessionNoSession();
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Test linked files with a project home set (done by save as in this test)
        /// https://nodejstools.codeplex.com/workitem/1511
        /// </summary>
        public void TestLinkedWithProjectHome(VisualStudioApp app, ProjectGenerator pg)
        {
            foreach (var projectType in pg.ProjectTypes)
            {
                using (var solution = MultiProjectLinkedFiles(projectType).ToVs(app)) {
                    var project = (solution as VisualStudioInstance).Project;

                    // save the project to an odd location.  This will result in project home being set.
                    var newProjName = "TempFile";
                    try {
                        project.SaveAs(TestData.GetTempPath() + newProjName + projectType.ProjectExtension);
                    } catch (UnauthorizedAccessException) {
                        Assert.Inconclusive("Couldn't save the file");
                    }

                    // create a temporary file and add a link to it in the project
                    solution.FindItem(newProjName).Select();
                    string tempFile;
                    using (FileUtils.TemporaryTextFile(out tempFile, "Test file")) {
                        using (var addExistingDlg = AddExistingItemDialog.FromDte((solution as VisualStudioInstance).App)) {
                            addExistingDlg.FileName = tempFile;
                            addExistingDlg.AddLink();
                        }

                        // Save the project to commit that link to the project file
                        project.Save();

                        // verify that the project file contains the correct text for Link
                        // (file path is relative to home folder)
                        var projectHomeFolder = project.Properties.Item("ProjectHome").Value as string;
                        var fileText          = File.ReadAllText(project.FullName);
                        var relativeTempFile  = PathUtils.GetRelativeFilePath(
                            projectHomeFolder,
                            tempFile
                            );

                        var pattern = string.Format(
                            @"<Content Include=""{0}"">\s*<Link>{1}</Link>\s*</Content>",
                            Regex.Escape(relativeTempFile),
                            Regex.Escape(Path.GetFileName(tempFile)));

                        AssertUtil.AreEqual(new Regex(pattern), fileText);
                    }
                }
            }
        }
Esempio n. 23
0
        public void BoxLayout_Test_single_node_padding()
        {
            var layout = new BoxL.BoxLayout();

            layout.Root = new BoxL.Container(BoxL.Direction.BottomToTop);
            var root = layout.Root;
            var n1   = root.AddBox(10, 5);

            root.PaddingBottom = 1.0;
            root.PaddingLeft   = 1.0;
            root.PaddingRight  = 1.0;
            root.PaddingTop    = 1.0;

            layout.PerformLayout();
            double delta = 0.00000001;

            AssertUtil.AreEqual(1.0, 1.0, 11, 6, n1.Rectangle, delta);
        }
Esempio n. 24
0
        public void NonDefaultInterpreter()
        {
            var mockProvider = new MockPythonInterpreterFactoryProvider("Test Provider 1",
                                                                        new MockPythonInterpreterFactory(MockInterpreterConfiguration("Test Factory 1", new Version(2, 7))),
                                                                        new MockPythonInterpreterFactory(MockInterpreterConfiguration("Test Factory 2", new Version(3, 0), InterpreterUIMode.CannotBeDefault)),
                                                                        new MockPythonInterpreterFactory(MockInterpreterConfiguration("Test Factory 3", new Version(3, 3), InterpreterUIMode.CannotBeAutoDefault))
                                                                        );

            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    var container    = CreateCompositionContainer();
                    var service      = container.GetExportedValue <IInterpreterOptionsService>();
                    var interpreters = container.GetExportedValue <IInterpreterRegistryService>();
                    var oldDefault   = service.DefaultInterpreter;
                    var oldProviders = ((InterpreterRegistryService)interpreters).SetProviders(new[] {
                        new Lazy <IPythonInterpreterFactoryProvider, Dictionary <string, object> >(
                            () => mockProvider,
                            new Dictionary <string, object>()
                        {
                            { "InterpreterFactoryId", "Mock" }
                        }
                            )
                    });
                    try {
                        list.Service      = service;
                        list.Interpreters = interpreters;
                        var environments = list.Environments;

                        AssertUtil.AreEqual(
                            wpf.Invoke(() => environments.Select(ev => ev.Description).ToList()),
                            "Test Factory 1", "Test Factory 2", "Test Factory 3"
                            );
                        // TF 1 and 3 can be set as default
                        AssertUtil.AreEqual(
                            wpf.Invoke(() => environments.Select(ev => ev.CanBeDefault).ToList()),
                            true, false, true
                            );
                    } finally {
                        ((InterpreterRegistryService)interpreters).SetProviders(oldProviders);
                        service.DefaultInterpreter = oldDefault;
                    }
                }
        }
Esempio n. 25
0
        public void NoTraceFunction()
        {
            // http://pytools.codeplex.com/workitem/662
            using (var replEval = Evaluator) {
                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
        public void AstMro() {
            var O = new AstPythonType("O");
            var A = new AstPythonType("A");
            var B = new AstPythonType("B");
            var C = new AstPythonType("C");
            var D = new AstPythonType("D");
            var E = new AstPythonType("E");
            var F = new AstPythonType("F");

            F.SetBases(null, new[] { O });
            E.SetBases(null, new[] { O });
            D.SetBases(null, new[] { O });
            C.SetBases(null, new[] { D, F });
            B.SetBases(null, new[] { D, E });
            A.SetBases(null, new[] { B, C });

            AssertUtil.AreEqual(AstPythonType.CalculateMro(A).Select(t => t.Name), "A", "B", "C", "D", "E", "F", "O");
            AssertUtil.AreEqual(AstPythonType.CalculateMro(B).Select(t => t.Name), "B", "D", "E", "O");
            AssertUtil.AreEqual(AstPythonType.CalculateMro(C).Select(t => t.Name), "C", "D", "F", "O");
        }
Esempio n. 27
0
        public void BuiltinFunctionSigHelp()
        {
            using (var view = new PythonEditor()) {
                view.Type("min(");

                for (int retries = 10; retries > 0; --retries)
                {
                    using (var sh = view.View.WaitForSession <ISignatureHelpSession>()) {
                        var doc = sh.Session.Signatures[0].Documentation;
                        if (doc.Contains("still being calculated"))
                        {
                            view.VS.Sleep(100);
                            continue;
                        }
                        AssertUtil.AreEqual(new Regex(@"^min\(x\: object\).+?"), doc);
                        break;
                    }
                }
            }
        }
Esempio n. 28
0
        public async Task UnresolvedImportSquiggle()
        {
            List <string> squiggles;

            using (PythonEditor view = new PythonEditor("import fob, oar\r\nfrom baz import *\r\nfrom spam import eggs"))
            {
                var errorProvider = view.VS.ServiceProvider.GetComponentModel().GetService <IErrorProviderFactory>();
                var tagger        = errorProvider.GetErrorTagger(view.View.TextView.TextBuffer);
                // Ensure all tasks have been updated
                var taskProvider = (ErrorTaskProvider)view.VS.ServiceProvider.GetService(typeof(ErrorTaskProvider));
                var time         = await taskProvider.FlushAsync();

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

                squiggles = tagger.GetTaggedSpans(new SnapshotSpan(view.CurrentSnapshot, 0, view.CurrentSnapshot.Length))
                            .Select(FormatErrorTag)
                            .ToList();
            }

            Console.WriteLine(" Squiggles found:");
            foreach (var actual in squiggles)
            {
                Console.WriteLine(actual);
            }
            Console.WriteLine(" Found {0} squiggle(s)", squiggles.Count);

            int i = 0;

            foreach (global::System.String expected in new[] {
                // Ensure that the warning includes the module name
                @".*warning:.*fob.*\(Python.+:7-10\)",
                @".*warning:.*oar.*\(Python.+:12-15\)",
                @".*warning:.*baz.*\(Python.+:22-25\)",
                @".*warning:.*spam.*\(Python.+:41-45\)"
            })
            {
                Assert.IsTrue(i < squiggles.Count, "Not enough squiggles");
                AssertUtil.AreEqual(new Regex(expected, RegexOptions.IgnoreCase | RegexOptions.Singleline), squiggles[i]);
                i += 1;
            }
        }
Esempio n. 29
0
        private static void AddSmartTagTest(EditorWindow doc, int line, int column, string[] expectedActions, int invokeAction = -1, string expectedText = null)
        {
            doc.InvokeTask(async() => {
                var point = doc.TextView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(line - 1).Start.Add(column - 1);
                doc.TextView.Caret.MoveTo(point);
                await doc.WaitForAnalyzerAtCaretAsync();
            });

            if (expectedActions.Length > 0)
            {
                using (var sh = doc.StartSmartTagSession()) {
                    var actions = sh.Session.Actions.ToList();
                    if (expectedActions[0] == "*")
                    {
                        AssertUtil.ContainsAtLeast(
                            actions.Select(a => a.DisplayText.Replace("__", "_")),
                            expectedActions.Skip(1)
                            );
                    }
                    else
                    {
                        AssertUtil.AreEqual(
                            actions.Select(a => a.DisplayText.Replace("__", "_")).ToArray(),
                            expectedActions
                            );
                    }

                    if (invokeAction >= 0)
                    {
                        var action = actions.FirstOrDefault(a => a.DisplayText.Replace("__", "_") == expectedActions[invokeAction]);
                        Assert.IsNotNull(action, "No action named " + expectedActions[invokeAction]);
                        doc.Invoke(() => action.Invoke());
                        doc.WaitForText(expectedText);
                    }
                }
            }
            else
            {
                doc.StartSmartTagSessionNoSession();
            }
        }
Esempio n. 30
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.AreEqual(execute.Result, ExecutionResult.Success);
            replWindow.ClearScreen();

            execute = replEval.ExecuteText("sys.gettrace()");
            execute.Wait();
            AssertUtil.AreEqual(
                new Regex(@"\<bound method Thread.trace_func of \<Thread.+\>\>"),
                replWindow.Output
                );
            replWindow.ClearScreen();
        }