Esempio n. 1
0
        public virtual async Task AttachWithOutputRedirection()
        {
            var expectedOutput = new[] { "stdout", "stderr" };

            string script = TestData.GetPath(@"TestData\DebuggerProject\AttachOutput.py");
            var    p      = Process.Start(Version.InterpreterPath, "\"" + script + "\"");

            try {
                using (var dumpWriter = new MiniDumpWriter(p)) {
                    Thread.Sleep(1000);
                    var proc = PythonProcess.Attach(p.Id, PythonDebugOptions.RedirectOutput);
                    try {
                        var attached = new TaskCompletionSource <bool>();
                        proc.ProcessLoaded += (sender, args) => {
                            Console.WriteLine("Process loaded");
                            attached.SetResult(true);
                        };
                        await proc.StartListeningAsync();

                        await attached.Task.WithTimeout(20000, "Failed to attach within 20s");

                        await proc.ResumeAsync(TimeoutToken());

                        var          bpHit  = new TaskCompletionSource <bool>();
                        PythonThread thread = null;
                        proc.BreakpointHit += (sender, args) => {
                            thread = args.Thread;
                            bpHit.SetResult(true);
                        };
                        var bp = proc.AddBreakpoint(script, 5);
                        await bp.AddAsync(TimeoutToken());

                        await bpHit.Task.WithTimeout(20000, "Failed to hit breakpoint within 20s");

                        Assert.IsNotNull(thread);

                        var actualOutput = new List <string>();
                        proc.DebuggerOutput += (sender, e) => {
                            Console.WriteLine("Debugger output: '{0}'", e.Output);
                            actualOutput.Add(e.Output);
                        };

                        var frame = thread.Frames[0];
                        Assert.AreEqual("False", (await frame.ExecuteTextAsync("attached", ct: CancellationTokens.After15s)).StringRepr);
                        await frame.ExecuteTextAsync("attached = True", ct : TimeoutToken());

                        await proc.ResumeAsync(TimeoutToken());

                        WaitForExit(proc);
                        AssertUtil.ArrayEquals(expectedOutput, actualOutput);
                    } finally {
                        await DetachProcessAsync(proc);
                    }

                    dumpWriter.Cancel();
                }
            } finally {
                DisposeProcess(p);
            }
        }
Esempio n. 2
0
        public virtual void AttachWithOutputRedirection()
        {
            var expectedOutput = new[] { "stdout", "stderr" };

            string script = TestData.GetPath(@"TestData\DebuggerProject\AttachOutput.py");
            var    p      = Process.Start(Version.InterpreterPath, "\"" + script + "\"");

            try {
                Thread.Sleep(1000);
                var proc = PythonProcess.Attach(p.Id, PythonDebugOptions.RedirectOutput);
                try {
                    var attached = new AutoResetEvent(false);
                    proc.ProcessLoaded += (sender, args) => {
                        Console.WriteLine("Process loaded");
                        attached.Set();
                    };
                    proc.StartListening();

                    Assert.IsTrue(attached.WaitOne(20000), "Failed to attach within 20s");
                    proc.Resume();

                    var          bpHit  = new AutoResetEvent(false);
                    PythonThread thread = null;
                    proc.BreakpointHit += (sender, args) => {
                        thread = args.Thread;
                        bpHit.Set();
                    };
                    var bp = proc.AddBreakPoint(script, 5);
                    bp.Add();

                    Assert.IsTrue(bpHit.WaitOne(20000), "Failed to hit breakpoint within 20s");
                    Assert.IsNotNull(thread);

                    var actualOutput = new List <string>();
                    proc.DebuggerOutput += (sender, e) => {
                        Console.WriteLine("Debugger output: '{0}'", e.Output);
                        actualOutput.Add(e.Output);
                    };

                    var frame = thread.Frames[0];
                    Assert.AreEqual("False", frame.ExecuteTextAsync("attached").Result.StringRepr);
                    Assert.IsTrue(frame.ExecuteTextAsync("attached = True").Wait(20000), "Failed to complete evaluation within 20s");

                    proc.Resume();
                    WaitForExit(proc);
                    AssertUtil.ArrayEquals(expectedOutput, actualOutput);
                } finally {
                    DetachProcess(proc);
                }
            } finally {
                DisposeProcess(p);
            }
        }
Esempio n. 3
0
        public async Task GetSearchPaths()
        {
            Python.AssertInstalled();

            var paths = await PythonLibraryPath.GetUncachedDatabaseSearchPathsAsync(Python.InterpreterPath);

            Console.WriteLine("Paths for {0}", Python.InterpreterPath);
            foreach (var path in paths)
            {
                Console.WriteLine("{0} {1}", path.Path, path.IsStandardLibrary ? "(stdlib)" : "");
            }

            // Python.PrefixPath and LibraryPath should be included.
            // We can't assume anything else
            var expected = Python.IsCPython ? new[] {
                Python.PrefixPath.ToLowerInvariant().TrimEnd('\\'),
                Path.Combine(Python.PrefixPath, "Lib").ToLowerInvariant()
            } : new[] {
                Path.Combine(Python.PrefixPath, "Lib").ToLowerInvariant()
            };

            AssertUtil.ContainsAtLeast(paths.Select(p => p.Path.ToLowerInvariant().TrimEnd('\\')), expected);

            // All paths should exist
            AssertUtil.ArrayEquals(paths.Where(p => !Directory.Exists(p.Path)).ToList(), new PythonLibraryPath[0]);

            // Ensure we can round-trip the entries via ToString/Parse
            var asStrings  = paths.Select(p => p.ToString()).ToList();
            var asPaths    = asStrings.Select(PythonLibraryPath.Parse).ToList();
            var asStrings2 = asPaths.Select(p => p.ToString()).ToList();

            AssertUtil.ArrayEquals(asStrings, asStrings2);
            AssertUtil.ArrayEquals(paths, asPaths, (o1, o2) => {
                PythonLibraryPath p1 = (PythonLibraryPath)o1, p2 = (PythonLibraryPath)o2;
                return(p1.Path == p2.Path && p1.IsStandardLibrary == p2.IsStandardLibrary);
            });

            var dbPath = Path.Combine(TestData.GetTempPath(), "database.path");

            Assert.IsNull(PythonLibraryPath.GetCachedDatabaseSearchPaths(dbPath),
                          "Should not have found cached paths in an empty directory");

            PythonLibraryPath.WriteDatabaseSearchPaths(dbPath, paths);
            Assert.IsTrue(File.Exists(dbPath));
            var paths2 = PythonLibraryPath.GetCachedDatabaseSearchPaths(dbPath);

            AssertUtil.ArrayEquals(paths, paths2, (o1, o2) => {
                PythonLibraryPath p1 = (PythonLibraryPath)o1, p2 = (PythonLibraryPath)o2;
                return(p1.Path == p2.Path && p1.IsStandardLibrary == p2.IsStandardLibrary);
            });
        }
Esempio n. 4
0
        public void TestPassInTestList()
        {
            var executor      = new TestExecutor();
            var recorder      = new MockTestExecutionRecorder();
            var expectedTests = Enumerable.Repeat(TestInfo.TestAdapterATests, 10).SelectMany();
            var runContext    = CreateRunContext(expectedTests, Version.InterpreterPath, dryRun: true);
            var testCases     = expectedTests.Select(tr => tr.TestCase);

            executor.RunTests(testCases, runContext, recorder);
            PrintTestResults(recorder);

            AssertUtil.ArrayEquals(
                expectedTests.Select(t => t.TestCase.FullyQualifiedName).ToList(),
                recorder.Results.Select(t => t.TestCase.FullyQualifiedName).ToList()
                );
        }
Esempio n. 5
0
        public void TestPassOnCommandLine()
        {
            var executor      = new TestExecutor();
            var recorder      = new MockTestExecutionRecorder();
            var expectedTests = TestInfo.TestAdapterATests;
            var runContext    = CreateRunContext(expectedTests, Version.InterpreterPath, dryRun: true);
            var testCases     = runContext.TestCases;

            executor.RunTests(testCases, runContext, recorder);
            PrintTestResults(recorder);

            AssertUtil.ArrayEquals(
                expectedTests.Select(t => t.TestCase.FullyQualifiedName).ToList(),
                recorder.Results.Select(t => t.TestCase.FullyQualifiedName).ToList()
                );
        }
Esempio n. 6
0
        public void TypeShedChildModules()
        {
            string[] expected;

            using (var analysis = CreateAnalysis(Latest)) {
                analysis.SetLimits(new AnalysisLimits()
                {
                    UseTypeStubPackages = false
                });
                try {
                    var entry = analysis.AddModule("test-module", @"import urllib");
                    analysis.WaitForAnalysis();

                    expected = analysis.Analyzer.GetModuleMembers(entry.AnalysisContext, new[] { "urllib" }, false)
                               .Select(m => m.Name)
                               .OrderBy(n => n)
                               .ToArray();
                    Assert.AreNotEqual(0, expected.Length);
                    AssertUtil.ContainsAtLeast(expected, "parse", "request");
                } finally {
                    _analysisLog = analysis.GetLogContent(CultureInfo.InvariantCulture);
                }
            }

            using (var analysis = CreateAnalysis(Latest)) {
                analysis.SetTypeStubSearchPath(GetTypeShedPaths(TypeShedPath, analysis.Analyzer.LanguageVersion).ToArray());
                try {
                    var entry = analysis.AddModule("test-module", @"import urllib");
                    analysis.WaitForAnalysis();

                    var mods = analysis.Analyzer.GetModuleMembers(entry.AnalysisContext, new[] { "urllib" }, false)
                               .Select(m => m.Name)
                               .OrderBy(n => n)
                               .ToArray();
                    AssertUtil.ArrayEquals(expected, mods);
                } finally {
                    _analysisLog = analysis.GetLogContent(CultureInfo.InvariantCulture);
                }
            }
        }
Esempio n. 7
0
        public void VersionOrdering()
        {
            var versions = ExampleVersions.Select(Pep440Version.Parse).ToList();
            var rnd      = new Random();
            var shuffled = versions
                           .Select(v => new { K = rnd.NextDouble(), V = v })
                           .OrderBy(i => i.K)
                           .Select(i => i.V)
                           .ToList();
            var reversed = versions.AsEnumerable().Reverse().ToList();

            foreach (var src in new[] { shuffled, reversed })
            {
                var sorted = src.OrderBy(v => v).ToList();

                foreach (var p in versions.Zip(sorted, Tuple.Create <Pep440Version, Pep440Version>))
                {
                    Console.WriteLine("{0} {1} {2}", p.Item1, p.Item1.Equals(p.Item2) ? "==" : "!=", p.Item2);
                }
                AssertUtil.ArrayEquals(versions, sorted);
            }
        }
Esempio n. 8
0
        private void CheckPackage(
            IPackage package,
            string expectedName,
            string expectedDescription,
            string expectedAuthor,
            string expectedPublishDateTime,
            SemverVersion expectedVersion,
            IEnumerable <SemverVersion> expectedVersions,
            IEnumerable <string> expectedKeywords)
        {
            Assert.AreEqual(expectedName, package.Name, "Invalid name.");
            Assert.AreEqual(expectedDescription, package.Description, "Invalid description.");
            string actualAuthorString = null == package.Author ? null : package.Author.Name;

            Assert.AreEqual(expectedAuthor, actualAuthorString, "Invalid author.");
            Assert.AreEqual(expectedPublishDateTime, package.PublishDateTimeString, "Invalid publish date/time.");
            Assert.AreEqual(expectedVersion, package.Version, "Invalid version.");

            // Sometimes authors include duplicate keywords in the list
            AssertUtil.ArrayEquals(package.Keywords.Distinct().ToList(), expectedKeywords.Distinct().ToList());
            AssertUtil.ArrayEquals(package.AvailableVersions.ToList(), expectedVersions.ToList());
        }
Esempio n. 9
0
        public void DecoratedTests()
        {
            using (var analyzer = MakeTestAnalyzer()) {
                var code  = @"import unittest

def decorator(fn):
    def wrapped(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapped

class MyTest(unittest.TestCase):
    @decorator
    def testAbc(self):
        pass

    @fake_decorator
    def testDef(self):
        pass
";
                var entry = AddModule(analyzer, "Fob", code);

                entry.Analyze(CancellationToken.None, true);
                analyzer.AnalyzeQueuedEntries(CancellationToken.None);

                var tests = TestAnalyzer.GetTestCasesFromAnalysis(entry)
                            .Select(t => $"{t.MethodName}:{t.StartLine}");
                AssertUtil.ArrayEquals(
                    new[] { "testAbc:10", "testDef:14" },
                    tests.ToArray()
                    );

                tests = GetTestCasesFromAst(code, analyzer)
                        .Select(t => $"{t.MethodName}:{t.StartLine}");
                AssertUtil.ArrayEquals(
                    new[] { "testAbc:9", "testDef:13" },
                    tests.ToArray()
                    );
            }
        }
Esempio n. 10
0
        private void FindCharDiffs(string oldText, string newText, params LcsDiff[] expected)
        {
            var diffs = LongestCommonSequence <char> .Find(oldText.ToCharArray(), newText.ToCharArray(), (c1, c2) => c1 == c2);

            AssertUtil.ArrayEquals(expected, diffs.ToArray());
        }
Esempio n. 11
0
        public async Task AttachPtvsd()
        {
            var expectedOutput = new[] { "stdout", "stderr" };

            string script = TestData.GetPath(@"TestData\DebuggerProject\AttachPtvsd.py");
            var    psi    = new ProcessStartInfo(Version.InterpreterPath, PtvsdInterpreterArguments + " \"" + script + "\"")
            {
                WorkingDirectory       = TestData.GetPath(),
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                CreateNoWindow         = true
            };

            var p = Process.Start(psi);

            try {
                PythonProcess proc = null;
                for (int i = 0; ; ++i)
                {
                    Thread.Sleep(1000);
                    try {
                        proc = await PythonRemoteProcess.AttachAsync(
                            new Uri("tcp://secret@localhost?opt=" + PythonDebugOptions.RedirectOutput),
                            false, TimeoutToken());

                        break;
                    } catch (SocketException) {
                        // Failed to connect - the process might have not started yet, so keep trying a few more times.
                        if (i >= 5 || p.HasExited)
                        {
                            throw;
                        }
                    }
                }

                try {
                    var attached = new AutoResetEvent(false);
                    proc.ProcessLoaded += async(sender, e) => {
                        Console.WriteLine("Process loaded");

                        var bp = proc.AddBreakpoint(script, 10);
                        await bp.AddAsync(TimeoutToken());

                        await proc.ResumeAsync(TimeoutToken());

                        attached.Set();
                    };

                    var actualOutput = new List <string>();
                    proc.DebuggerOutput += (sender, e) => {
                        actualOutput.Add(e.Output);
                    };

                    var bpHit = new AutoResetEvent(false);
                    proc.BreakpointHit += async(sender, args) => {
                        Console.WriteLine("Breakpoint hit");
                        bpHit.Set();
                        await proc.ResumeAsync(TimeoutToken());
                    };

                    await proc.StartListeningAsync();

                    Assert.IsTrue(attached.WaitOne(20000), "Failed to attach within 20s");
                    Assert.IsTrue(bpHit.WaitOne(20000), "Failed to hit breakpoint within 20s");

                    p.WaitForExit(DefaultWaitForExitTimeout);
                    AssertUtil.ArrayEquals(expectedOutput, actualOutput);
                } finally {
                    await DetachProcessAsync(proc);
                }
            } finally {
                Console.WriteLine(p.StandardOutput.ReadToEnd());
                Console.WriteLine(p.StandardError.ReadToEnd());
                DisposeProcess(p);
            }
        }