Beispiel #1
0
        public void InstalledFactories()
        {
            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    list.Service = GetInterpreterOptionsService();

                    var expected = new HashSet <string>(
                        PythonPaths.Versions
                        .Where(v => !v.IsIronPython)
                        .Select(v => v.InterpreterPath),
                        StringComparer.OrdinalIgnoreCase
                        );
                    var actual = wpf.Invoke(() => new HashSet <string>(
                                                list.Environments.Select(ev => (string)ev.InterpreterPath),
                                                StringComparer.OrdinalIgnoreCase
                                                ));

                    Console.WriteLine("Expected - Actual: " + string.Join(", ", expected.Except(actual).OrderBy(s => s)));
                    Console.WriteLine("Actual - Expected: " + string.Join(", ", actual.Except(expected).OrderBy(s => s)));

                    AssertUtil.ContainsExactly(
                        expected,
                        actual
                        );
                }
        }
Beispiel #2
0
        public void AddFactories()
        {
            var mockService = new MockInterpreterOptionsService();

            using (var wpf = new WpfProxy())
                using (var list = wpf.Invoke(() => new EnvironmentListProxy(wpf))) {
                    var provider = new MockPythonInterpreterFactoryProvider("Test Provider 1",
                                                                            new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 1", MockInterpreterConfiguration(new Version(2, 7))),
                                                                            new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 2", MockInterpreterConfiguration(new Version(3, 0))),
                                                                            new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 3", MockInterpreterConfiguration(new Version(3, 3)))
                                                                            );

                    list.Service = mockService;

                    Assert.AreEqual(0, list.Environments.Count);

                    mockService.AddProvider(provider);
                    Assert.AreEqual(3, list.Environments.Count);
                    provider.AddFactory(new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 4", MockInterpreterConfiguration(new Version(2, 7))));
                    Assert.AreEqual(4, list.Environments.Count);
                    provider.AddFactory(new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 5", MockInterpreterConfiguration(new Version(3, 0))));
                    Assert.AreEqual(5, list.Environments.Count);
                    provider.AddFactory(new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 6", MockInterpreterConfiguration(new Version(3, 3))));
                    Assert.AreEqual(6, list.Environments.Count);
                }
        }
Beispiel #3
0
        public void FactoryWithValidPath()
        {
            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    var service  = new MockInterpreterOptionsService();
                    var provider = new MockPythonInterpreterFactoryProvider("Test Provider");
                    service.AddProvider(provider);
                    list.Service = service;

                    foreach (var version in PythonPaths.Versions)
                    {
                        Console.WriteLine("Path: <{0}>", version.InterpreterPath);
                        provider.RemoveAllFactories();
                        provider.AddFactory(new MockPythonInterpreterFactory(
                                                Guid.NewGuid(),
                                                "Test Factory",
                                                version.Configuration
                                                ));
                        var view = list.Environments.Single();
                        Assert.IsTrue(
                            list.CanExecute(DBExtension.StartRefreshDB, view),
                            string.Format("Cannot refresh DB for {0}", version.InterpreterPath)
                            );
                    }
                }
        }
Beispiel #4
0
        public void HasInterpreters()
        {
            var sp          = new MockServiceProvider();
            var mockService = new MockInterpreterOptionsService();

            mockService.AddProvider(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))),
                                                                             new MockPythonInterpreterFactory(MockInterpreterConfiguration("Test Factory 3", new Version(3, 3)))
                                                                             ));
            mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider 2",
                                                                             new MockPythonInterpreterFactory(MockInterpreterConfiguration("Test Factory 4", new Version(2, 7))),
                                                                             new MockPythonInterpreterFactory(MockInterpreterConfiguration("Test Factory 5", new Version(3, 0))),
                                                                             new MockPythonInterpreterFactory(MockInterpreterConfiguration("Test Factory 6", new Version(3, 3))),
                                                                             new MockPythonInterpreterFactory(MockInterpreterConfiguration("Test Factory 7", new Version(3, 3), InterpreterUIMode.Hidden))
                                                                             ));

            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    list.Service      = mockService;
                    list.Interpreters = mockService;
                    var environments = list.Environments;

                    Assert.AreEqual(6, environments.Count);
                    AssertUtil.ContainsExactly(
                        wpf.Invoke(() => environments.Select(ev => ev.Description).ToList()),
                        "Test Factory 1 2.7",
                        "Test Factory 2 3.0",
                        "Test Factory 3 3.3",
                        "Test Factory 4 2.7",
                        "Test Factory 5 3.0",
                        "Test Factory 6 3.3"
                        );
                }
        }
Beispiel #5
0
        public void ImportWizardSemicolons()
        {
            // https://pytools.codeplex.com/workitem/2022
            using (var wpf = new WpfProxy()) {
                var settings   = wpf.Create(() => new ImportSettings(null, null));
                var sourcePath = TestData.GetTempPath(randomSubPath: true);
                // Create a fake set of files to import
                Directory.CreateDirectory(Path.Combine(sourcePath, "ABC"));
                File.WriteAllText(Path.Combine(sourcePath, "ABC", "a;b;c.py"), "");
                Directory.CreateDirectory(Path.Combine(sourcePath, "A;B;C"));
                File.WriteAllText(Path.Combine(sourcePath, "A;B;C", "abc.py"), "");

                settings.SourcePath = sourcePath;

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                var proj = XDocument.Load(path);

                AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
                                           "ABC\\a%3bb%3bc.py",
                                           "A%3bB%3bC\\abc.py"
                                           );
                AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
                                           "ABC",
                                           "A%3bB%3bC"
                                           );
            }
        }
Beispiel #6
0
        public void ImportWizardInterpreter()
        {
            using (var wpf = new WpfProxy()) {
                var settings = wpf.Create(() => new ImportSettings(null, null));
                settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\");
                settings.Filters    = "*.py;*.pyproj";

                var interpreter = new PythonInterpreterView("Test", Guid.NewGuid(), new Version(2, 7), null);
                settings.Dispatcher.Invoke((Action)(() => settings.AvailableInterpreters.Add(interpreter)));
                //settings.AddAvailableInterpreter(interpreter);
                settings.SelectedInterpreter = interpreter;
                settings.ProjectPath         = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                var proj = XDocument.Load(path);

                Assert.AreEqual(interpreter.Id, Guid.Parse(proj.Descendant("InterpreterId").Value));
                Assert.AreEqual(interpreter.Version, Version.Parse(proj.Descendant("InterpreterVersion").Value));

                var interp = proj.Descendant("InterpreterReference");
                Assert.AreEqual(string.Format("{0:B}\\{1}", interpreter.Id, interpreter.Version),
                                interp.Attribute("Include").Value);
            }
        }
Beispiel #7
0
        public void AddUpdateRemoveConfigurableFactory()
        {
            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    list.Service = GetInterpreterOptionsService();

                    var before = wpf.Invoke(() => new HashSet <string>(
                                                list.Environments.Select(ev => (string)ev.InterpreterPath),
                                                StringComparer.OrdinalIgnoreCase
                                                ));

                    var configurable = list.Service.KnownProviders.OfType <ConfigurablePythonInterpreterFactoryProvider>().FirstOrDefault();
                    Assert.IsNotNull(configurable, "No configurable provider available");
                    var fact = configurable.SetOptions(new InterpreterFactoryCreationOptions {
                        Id = Guid.NewGuid(),
                        LanguageVersionString = "2.7",
                        // The actual file doesn't matter, except to test that it
                        // is added
                        InterpreterPath = TestData.GetPath("HelloWorld\\HelloWorld.pyproj")
                    });

                    try {
                        var afterAdd = wpf.Invoke(() => new HashSet <string>(
                                                      list.Environments.Select(ev => (string)ev.InterpreterPath),
                                                      StringComparer.OrdinalIgnoreCase
                                                      ));

                        Assert.AreNotEqual(before.Count, afterAdd.Count, "Did not add a new environment");
                        AssertUtil.ContainsExactly(
                            afterAdd.Except(before),
                            TestData.GetPath("HelloWorld\\HelloWorld.pyproj")
                            );

                        configurable.SetOptions(new InterpreterFactoryCreationOptions {
                            Id = fact.Id,
                            LanguageVersion = fact.Configuration.Version,
                            InterpreterPath = TestData.GetPath("HelloWorld2\\HelloWorld.pyproj")
                        });

                        var afterUpdate = wpf.Invoke(() => new HashSet <string>(
                                                         list.Environments.Select(ev => (string)ev.InterpreterPath),
                                                         StringComparer.OrdinalIgnoreCase
                                                         ));

                        Assert.AreEqual(afterAdd.Count, afterUpdate.Count, "Should not add/remove an environment");
                        AssertUtil.ContainsExactly(
                            afterUpdate.Except(before),
                            TestData.GetPath("HelloWorld2\\HelloWorld.pyproj")
                            );
                    } finally {
                        configurable.RemoveInterpreter(fact.Id);
                    }

                    var afterRemove = wpf.Invoke(() => new HashSet <string>(
                                                     list.Environments.Select(ev => (string)ev.InterpreterPath),
                                                     StringComparer.OrdinalIgnoreCase
                                                     ));
                    AssertUtil.ContainsExactly(afterRemove, before);
                }
        }
Beispiel #8
0
        public async Task AddUpdateRemoveConfigurableFactoryThroughUI()
        {
            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    list.Service = GetInterpreterOptionsService();

                    var before = wpf.Invoke(() => new HashSet <Guid>(list.Environments.Where(ev => ev.Factory != null).Select(ev => ev.Factory.Id)));

                    var configurable = list.Service.KnownProviders.OfType <ConfigurablePythonInterpreterFactoryProvider>().FirstOrDefault();
                    Assert.IsNotNull(configurable, "No configurable provider available");

                    await list.Execute(ApplicationCommands.New, null);

                    var afterAdd = wpf.Invoke(() => new HashSet <Guid>(list.Environments.Where(ev => ev.Factory != null).Select(ev => ev.Factory.Id)));

                    var difference = new HashSet <Guid>(afterAdd);
                    difference.ExceptWith(before);

                    Console.WriteLine("Added {0}", AssertUtil.MakeText(difference));
                    Assert.AreEqual(1, difference.Count, "Did not add a new environment");
                    var newEnv = list.Service.Interpreters.Single(f => difference.Contains(f.Id));

                    Assert.IsTrue(configurable.IsConfigurable(newEnv), "Did not add a configurable environment");

                    // To remove the environment, we need to trigger the Remove
                    // command on the ConfigurationExtensionProvider's control
                    var view     = wpf.Invoke(() => list.Environments.First(ev => ev.Factory == newEnv));
                    var extView  = wpf.Invoke(() => view.Extensions.OfType <ConfigurationExtensionProvider>().First().WpfObject);
                    var confView = wpf.Invoke(() => (ConfigurationEnvironmentView)((System.Windows.Controls.Grid)extView.FindName("Subcontext")).DataContext);
                    await wpf.Execute((RoutedCommand)ConfigurationExtension.Remove, extView, confView);

                    var afterRemove = wpf.Invoke(() => new HashSet <Guid>(list.Environments.Where(ev => ev.Factory != null).Select(ev => ev.Factory.Id)));
                    AssertUtil.ContainsExactly(afterRemove, before);
                }
        }
Beispiel #9
0
        public void ImportWizardInterpreter()
        {
            using (var wpf = new WpfProxy()) {
                var root = TestData.GetTempPath();
                FileUtils.CopyDirectory(TestData.GetPath(@"TestData\HelloWorld"), Path.Combine(root, "HelloWorld"));

                var settings = wpf.Create(() => new ImportSettings(null, null));
                settings.SourcePath  = PathUtils.GetAbsoluteDirectoryPath(root, "HelloWorld");
                settings.Filters     = "*.py;*.pyproj";
                settings.ProjectPath = PathUtils.GetAbsoluteFilePath(root, @"TestDestination\Subdirectory\ProjectName.pyproj");

                var interpreter = new PythonInterpreterView("Test", "Test|Blah", null);
                settings.Dispatcher.Invoke((Action)(() => settings.AvailableInterpreters.Add(interpreter)));
                //settings.AddAvailableInterpreter(interpreter);
                settings.SelectedInterpreter = interpreter;

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                var proj = XDocument.Load(path);

                Assert.AreEqual(interpreter.Id, proj.Descendant("InterpreterId").Value);

                var interp = proj.Descendant("InterpreterReference");
                Assert.AreEqual(string.Format("{0}", interpreter.Id),
                                interp.Attribute("Include").Value);
            }
        }
Beispiel #10
0
        public void ImportWizardFiltered()
        {
            using (var wpf = new WpfProxy()) {
                var root = TestData.GetTempPath();
                FileUtils.CopyDirectory(TestData.GetPath(@"TestData\HelloWorld"), Path.Combine(root, "HelloWorld"));
                FileUtils.CopyDirectory(TestData.GetPath(@"TestData\SearchPath1"), Path.Combine(root, "SearchPath1"));
                FileUtils.CopyDirectory(TestData.GetPath(@"TestData\SearchPath2"), Path.Combine(root, "SearchPath2"));

                var settings = wpf.Create(() => new ImportSettings(null, null));
                settings.SourcePath  = PathUtils.GetAbsoluteDirectoryPath(root, "HelloWorld");
                settings.Filters     = "*.py";
                settings.SearchPaths = PathUtils.GetAbsoluteDirectoryPath(root, "SearchPath1") + Environment.NewLine + PathUtils.GetAbsoluteDirectoryPath(root, "SearchPath2");
                settings.ProjectPath = PathUtils.GetAbsoluteFilePath(root, @"TestDestination\Subdirectory\ProjectName.pyproj");

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                var proj = XDocument.Load(path);

                Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value);
                Assert.AreEqual("..\\SearchPath1\\;..\\SearchPath2\\", proj.Descendant("SearchPath").Value);
                AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
                                           "Program.py");
                Assert.AreEqual(0, proj.Descendants(proj.GetName("Content")).Count());
            }
        }
Beispiel #11
0
        public void ImportWizardFolders()
        {
            using (var wpf = new WpfProxy()) {
                var settings = wpf.Create(() => new ImportSettings(null));
                settings.SourcePath  = TestData.GetPath("TestData\\HelloWorld2\\");
                settings.Filters     = "*";
                settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                var proj = XDocument.Load(path);

                Assert.AreEqual("..\\..\\HelloWorld2\\", proj.Descendant("ProjectHome").Value);
                Assert.AreEqual("", proj.Descendant("SearchPath").Value);
                AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
                                           "Program.py",
                                           "TestFolder\\SubItem.py",
                                           "TestFolder2\\SubItem.py",
                                           "TestFolder3\\SubItem.py");

                AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
                                           "TestFolder",
                                           "TestFolder2",
                                           "TestFolder3");
            }
        }
Beispiel #12
0
        public void HasInterpreters()
        {
            var sp          = new MockServiceProvider();
            var service     = new InterpreterOptionsService(sp);
            var mockService = new MockInterpreterOptionsService();

            mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider 1",
                                                                             new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 1", MockInterpreterConfiguration(new Version(2, 7))),
                                                                             new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 2", MockInterpreterConfiguration(new Version(3, 0))),
                                                                             new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 3", MockInterpreterConfiguration(new Version(3, 3)))
                                                                             ));
            mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider 2",
                                                                             new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 4", MockInterpreterConfiguration(new Version(2, 7))),
                                                                             new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 5", MockInterpreterConfiguration(new Version(3, 0))),
                                                                             new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 6", MockInterpreterConfiguration(new Version(3, 3))),
                                                                             new MockPythonInterpreterFactory(Guid.NewGuid(), "Hidden Factory 7", MockInterpreterConfiguration(new Version(3, 3), InterpreterUIMode.Hidden))
                                                                             ));

            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    list.Service = mockService;
                    var environments = list.Environments;

                    Assert.AreEqual(6, environments.Count);
                    AssertUtil.ContainsExactly(
                        wpf.Invoke(() => environments.Select(ev => ev.Description).ToList()),
                        Enumerable.Range(1, 6).Select(i => string.Format("Test Factory {0}", i))
                        );
                }
        }
Beispiel #13
0
        public void PipExtension()
        {
            var service = MakeEmptyVEnv();

            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    list.CreatePipExtension = true;
                    list.Service            = service;

                    var environment = list.Environments.Single();
                    var pip         = (PipExtensionProvider)list.GetExtensionOrAssert <PipExtensionProvider>(environment);

                    pip.CheckPipInstalledAsync().GetAwaiter().GetResult();
                    Assert.AreEqual(false, pip.IsPipInstalled, "venv should not install pip");
                    var task = wpf.Invoke(() => pip.InstallPip().ContinueWith <bool>(LogException));
                    Assert.IsTrue(task.Wait(TimeSpan.FromSeconds(120.0)), "pip install timed out");
                    Assert.IsTrue(task.Result, "pip install failed");
                    Assert.AreEqual(true, pip.IsPipInstalled, "pip was not installed");

                    var packages = pip.GetInstalledPackagesAsync().GetAwaiter().GetResult();
                    AssertUtil.ContainsExactly(packages.Select(pv => pv.Name), "pip", "setuptools");

                    task = wpf.Invoke(() => pip.InstallPackage("ptvsd", true).ContinueWith <bool>(LogException));
                    Assert.IsTrue(task.Wait(TimeSpan.FromSeconds(60.0)), "pip install ptvsd timed out");
                    Assert.IsTrue(task.Result, "pip install ptvsd failed");
                    packages = pip.GetInstalledPackagesAsync().GetAwaiter().GetResult();
                    AssertUtil.ContainsAtLeast(packages.Select(pv => pv.Name), "ptvsd");

                    task = wpf.Invoke(() => pip.UninstallPackage("ptvsd").ContinueWith <bool>(LogException));
                    Assert.IsTrue(task.Wait(TimeSpan.FromSeconds(60.0)), "pip uninstall ptvsd timed out");
                    Assert.IsTrue(task.Result, "pip uninstall ptvsd failed");
                    packages = pip.GetInstalledPackagesAsync().GetAwaiter().GetResult();
                    AssertUtil.DoesntContain(packages.Select(pv => pv.Name), "ptvsd");
                }
        }
Beispiel #14
0
        public void ChangeDefault()
        {
            var service = GetInterpreterOptionsService();

            using (var defaultChanged = new AutoResetEvent(false))
                using (var wpf = new WpfProxy())
                    using (var list = new EnvironmentListProxy(wpf)) {
                        service.DefaultInterpreterChanged += (s, e) => { defaultChanged.Set(); };
                        list.Service = service;
                        var originalDefault = service.DefaultInterpreter;
                        try {
                            foreach (var interpreter in service.Interpreters)
                            {
                                var environment = list.Environments.FirstOrDefault(ev =>
                                                                                   ev.Factory == interpreter
                                                                                   );
                                Assert.IsNotNull(environment, string.Format("Did not find {0}", interpreter.Description));

                                list.Execute(EnvironmentView.MakeGlobalDefault, environment);
                                Assert.IsTrue(defaultChanged.WaitOne(TimeSpan.FromSeconds(10.0)), "Setting default took too long");

                                Assert.AreEqual(interpreter, service.DefaultInterpreter,
                                                string.Format(
                                                    "Failed to change default from {0} to {1}",
                                                    service.DefaultInterpreter.Description,
                                                    interpreter.Description
                                                    ));
                            }
                        } finally {
                            service.DefaultInterpreter = originalDefault;
                        }
                    }
        }
Beispiel #15
0
 private static string CreateRequestedProject(dynamic settings)
 {
     return(Task.Run(async() => {
         return await await WpfProxy.FromObject((object)settings).InvokeAsync(
             async() => await(Task <string>) settings.CreateRequestedProjectAsync()
             );
     })
            .GetAwaiter()
            .GetResult());
 }
Beispiel #16
0
        public void ImportWizardStartupFile()
        {
            using (var wpf = new WpfProxy()) {
                var settings = wpf.Create(() => new ImportSettings(null, null));
                settings.SourcePath  = TestData.GetPath("TestData\\HelloWorld\\");
                settings.Filters     = "*.py;*.pyproj";
                settings.StartupFile = "Program.py";
                settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                var proj = XDocument.Load(path);

                Assert.AreEqual("Program.py", proj.Descendant("StartupFile").Value);
            }
        }
Beispiel #17
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;
                    }
                }
        }
Beispiel #18
0
        public void LoadUnloadProjectFactories()
        {
            var service      = new MockInterpreterOptionsService();
            var mockProvider = new MockPythonInterpreterFactoryProvider("Test Provider");

            mockProvider.AddFactory(new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Environment", MockInterpreterConfiguration(new Version(2, 7))));
            service.AddProvider(mockProvider);

            var loaded = new LoadedProjectInterpreterFactoryProvider();

            service.AddProvider(loaded);
            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    list.Service = service;

                    // List only contains one entry
                    AssertUtil.ContainsExactly(
                        wpf.Invoke(() => list.Environments.Select(ev => ev.Description).ToList()),
                        "Test Environment"
                        );

                    var project = new MockPythonInterpreterFactoryProvider("Fake Project");
                    project.AddFactory(new MockPythonInterpreterFactory(Guid.NewGuid(), "Fake Environment", MockInterpreterConfiguration(new Version(2, 7))));

                    loaded.ProjectLoaded(project, null);

                    // List now contains two entries
                    AssertUtil.ContainsExactly(
                        wpf.Invoke(() => list.Environments.Select(ev => ev.Description).ToList()),
                        "Test Environment",
                        "Fake Environment"
                        );

                    loaded.ProjectUnloaded(project);

                    // List only has one entry again
                    AssertUtil.ContainsExactly(
                        wpf.Invoke(() => list.Environments.Select(ev => ev.Description).ToList()),
                        "Test Environment"
                        );
                }
        }
Beispiel #19
0
        public void ImportWizardStartupFile()
        {
            using (var wpf = new WpfProxy()) {
                var root = TestData.GetTempPath();
                FileUtils.CopyDirectory(TestData.GetPath(@"TestData\HelloWorld"), Path.Combine(root, "HelloWorld"));

                var settings = wpf.Create(() => new ImportSettings(null, null));
                settings.SourcePath  = PathUtils.GetAbsoluteDirectoryPath(root, "HelloWorld");
                settings.Filters     = "*.py;*.pyproj";
                settings.StartupFile = "Program.py";
                settings.ProjectPath = PathUtils.GetAbsoluteFilePath(root, @"TestDestination\Subdirectory\ProjectName.pyproj");

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                var proj = XDocument.Load(path);

                Assert.AreEqual("Program.py", proj.Descendant("StartupFile").Value);
            }
        }
Beispiel #20
0
        private static void ImportWizardCustomizationsWorker(ProjectCustomization customization, Action <XDocument> verify)
        {
            using (var wpf = new WpfProxy()) {
                var settings = wpf.Create(() => new ImportSettings(null, null));
                settings.SourcePath       = TestData.GetPath("TestData\\HelloWorld\\");
                settings.Filters          = "*.py;*.pyproj";
                settings.StartupFile      = "Program.py";
                settings.UseCustomization = true;
                settings.Customization    = customization;
                settings.ProjectPath      = Path.Combine(TestData.GetTempPath("ImportWizardCustomizations_" + customization.GetType().Name), "Project.pyproj");
                Directory.CreateDirectory(Path.GetDirectoryName(settings.ProjectPath));

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                Console.WriteLine(File.ReadAllText(path));
                var proj = XDocument.Load(path);

                verify(proj);
            }
        }
Beispiel #21
0
        public void FactoryWithInvalidPath()
        {
            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    var service  = new MockInterpreterOptionsService();
                    var provider = new MockPythonInterpreterFactoryProvider("Test Provider");
                    service.AddProvider(provider);
                    list.Service      = service;
                    list.Interpreters = service;

                    foreach (string invalidPath in new string[] {
                        null,
                        "",
                        "NOT A REAL PATH",
                        string.Join("\\", Path.GetInvalidPathChars().Select(c => c.ToString()))
                    })
                    {
                        Console.WriteLine("Path: <{0}>", invalidPath ?? "(null)");
                        provider.RemoveAllFactories();
                        provider.AddFactory(new MockPythonInterpreterFactory(
                                                new InterpreterConfiguration(
                                                    "Mock;" + Guid.NewGuid().ToString(),
                                                    "Test Factory",
                                                    invalidPath,
                                                    invalidPath,
                                                    "",
                                                    "",
                                                    "",
                                                    ProcessorArchitecture.None,
                                                    new Version(2, 7)
                                                    )
                                                ));
                        var view = list.Environments.Single();
                        Assert.IsFalse(
                            list.CanExecute(DBExtension.StartRefreshDB, view),
                            string.Format("Should not be able to refresh DB for {0}", invalidPath)
                            );
                    }
                }
        }
Beispiel #22
0
        public void NonDefaultInterpreter()
        {
            var mockProvider = new MockPythonInterpreterFactoryProvider("Test Provider 1",
                                                                        new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 1", MockInterpreterConfiguration(new Version(2, 7))),
                                                                        new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 2", MockInterpreterConfiguration(new Version(3, 0), InterpreterUIMode.CannotBeDefault)),
                                                                        new MockPythonInterpreterFactory(Guid.NewGuid(), "Test Factory 3", MockInterpreterConfiguration(new Version(3, 3), InterpreterUIMode.CannotBeAutoDefault))
                                                                        );

            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    var service      = GetInterpreterOptionsService();
                    var oldDefault   = service.DefaultInterpreter;
                    var oldProviders = ((InterpreterOptionsService)service).SetProviders(new[] { mockProvider });
                    try {
                        list.Service = service;
                        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
                            );

                        // TF 1 should have been selected as the default
                        Assert.AreEqual(
                            "Test Factory 1",
                            wpf.Invoke(() => environments.First(ev => ev.IsDefault).Description)
                            );
                    } finally {
                        ((InterpreterOptionsService)service).SetProviders(oldProviders);
                        service.DefaultInterpreter = oldDefault;
                    }
                }
        }
Beispiel #23
0
        public void ImportWizardSimple()
        {
            using (var wpf = new WpfProxy()) {
                var settings = wpf.Create(() => new ImportSettings(null, null));
                settings.SourcePath  = TestData.GetPath("TestData\\HelloWorld\\");
                settings.Filters     = "*.py;*.pyproj";
                settings.SearchPaths = TestData.GetPath("TestData\\SearchPath1\\") + Environment.NewLine + TestData.GetPath("TestData\\SearchPath2\\");
                settings.ProjectPath = TestData.GetPath("TestData\\TestDestination\\Subdirectory\\ProjectName.pyproj");

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                var proj = XDocument.Load(path);

                Assert.AreEqual("4.0", proj.Descendant("Project").Attribute("ToolsVersion").Value);
                Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value);
                Assert.AreEqual("..\\SearchPath1\\;..\\SearchPath2\\", proj.Descendant("SearchPath").Value);
                AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
                                           "Program.py");
                AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Content")).Select(x => x.Attribute("Include").Value),
                                           "HelloWorld.pyproj");
            }
        }
Beispiel #24
0
        public void AddRemoveProjectFactories()
        {
            var service = new MockInterpreterOptionsService();
            var loaded  = new LoadedProjectInterpreterFactoryProvider();

            service.AddProvider(loaded);
            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    list.Service = service;

                    // List should be empty
                    AssertUtil.ContainsExactly(list.Environments);

                    var project = new MockPythonInterpreterFactoryProvider("Fake Project");

                    loaded.ProjectLoaded(project, null);

                    // List is still empty
                    AssertUtil.ContainsExactly(list.Environments);

                    project.AddFactory(new MockPythonInterpreterFactory(Guid.NewGuid(), "Fake Environment", MockInterpreterConfiguration(new Version(2, 7))));

                    // List now contains one project
                    AssertUtil.ContainsExactly(
                        wpf.Invoke(() => list.Environments.Select(ev => ev.Description).ToList()),
                        "Fake Environment"
                        );

                    project.RemoveAllFactories();

                    // List is empty again
                    AssertUtil.ContainsExactly(list.Environments);

                    loaded.ProjectUnloaded(project);
                }
        }
Beispiel #25
0
 public EnvironmentListProxy(WpfProxy proxy)
 {
     _proxy               = proxy;
     _window              = proxy.InvokeWithRetry(() => new ToolWindow());
     _window.ViewCreated += Window_ViewCreated;
 }
Beispiel #26
0
 protected internal WpfObjectProxy(WpfProxy provider, DependencyObject obj)
 {
     _provider = provider;
     _object   = obj;
 }
Beispiel #27
0
        public void RefreshDBStates()
        {
            using (var fact = new MockPythonInterpreterFactory(
                       Guid.NewGuid(),
                       "Test Factory 1",
                       MockInterpreterConfiguration(
                           PythonPaths.Versions.First().InterpreterPath
                           ),
                       true
                       ))
                using (var wpf = new WpfProxy())
                    using (var list = new EnvironmentListProxy(wpf)) {
                        list.CreateDBExtension = true;

                        var mockService = new MockInterpreterOptionsService();
                        mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider 1", fact));
                        list.Service = mockService;
                        var view = list.Environments.Single();

                        Assert.IsFalse(wpf.Invoke(() => view.IsRefreshingDB));
                        Assert.IsTrue(list.CanExecute(DBExtension.StartRefreshDB, view));
                        Assert.IsFalse(fact.IsCurrent);
                        Assert.AreEqual(MockPythonInterpreterFactory.NoDatabaseReason, fact.GetIsCurrentReason(null));

                        list.Execute(DBExtension.StartRefreshDB, view).GetAwaiter().GetResult();
                        for (int retries = 10; retries > 0 && !wpf.Invoke(() => view.IsRefreshingDB); --retries)
                        {
                            Thread.Sleep(200);
                        }

                        Assert.IsTrue(wpf.Invoke(() => view.IsRefreshingDB));
                        Assert.IsFalse(list.CanExecute(DBExtension.StartRefreshDB, view));
                        Assert.IsFalse(fact.IsCurrent);
                        Assert.AreEqual(MockPythonInterpreterFactory.GeneratingReason, fact.GetIsCurrentReason(null));

                        fact.EndGenerateCompletionDatabase(AnalyzerStatusUpdater.GetIdentifier(fact), false);
                        for (int retries = 10; retries > 0 && wpf.Invoke(() => view.IsRefreshingDB); --retries)
                        {
                            Thread.Sleep(1000);
                        }

                        Assert.IsFalse(wpf.Invoke(() => view.IsRefreshingDB));
                        Assert.IsTrue(list.CanExecute(DBExtension.StartRefreshDB, view));
                        Assert.IsFalse(fact.IsCurrent);
                        Assert.AreEqual(MockPythonInterpreterFactory.MissingModulesReason, fact.GetIsCurrentReason(null));

                        list.Execute(DBExtension.StartRefreshDB, view).GetAwaiter().GetResult();

                        Assert.IsTrue(wpf.Invoke(() => view.IsRefreshingDB));
                        Assert.IsFalse(list.CanExecute(DBExtension.StartRefreshDB, view));
                        Assert.IsFalse(fact.IsCurrent);
                        Assert.AreEqual(MockPythonInterpreterFactory.GeneratingReason, fact.GetIsCurrentReason(null));

                        fact.EndGenerateCompletionDatabase(AnalyzerStatusUpdater.GetIdentifier(fact), true);
                        for (int retries = 10; retries > 0 && wpf.Invoke(() => view.IsRefreshingDB); --retries)
                        {
                            Thread.Sleep(1000);
                        }

                        Assert.IsFalse(wpf.Invoke(() => view.IsRefreshingDB));
                        Assert.IsTrue(list.CanExecute(DBExtension.StartRefreshDB, view));
                        Assert.IsTrue(fact.IsCurrent);
                        Assert.AreEqual(MockPythonInterpreterFactory.UpToDateReason, fact.GetIsCurrentReason(null));
                        Assert.AreEqual(MockPythonInterpreterFactory.UpToDateReason, fact.GetIsCurrentReason(null));
                    }
        }
Beispiel #28
0
        public void AddUpdateRemoveConfigurableFactory()
        {
            using (var wpf = new WpfProxy())
                using (var list = new EnvironmentListProxy(wpf)) {
                    var container    = CreateCompositionContainer();
                    var service      = container.GetExportedValue <IInterpreterOptionsService>();
                    var interpreters = container.GetExportedValue <IInterpreterRegistryService>();
                    list.Service      = service;
                    list.Interpreters = interpreters;

                    var before = wpf.Invoke(() => new HashSet <string>(
                                                list.Environments.Select(ev => (string)ev.InterpreterPath),
                                                StringComparer.OrdinalIgnoreCase
                                                ));

                    var id   = Guid.NewGuid().ToString();
                    var fact = list.Service.AddConfigurableInterpreter(
                        id,
                        new InterpreterConfiguration(
                            "",
                            "Blah",
                            "",
                            TestData.GetPath("HelloWorld\\HelloWorld.pyproj")
                            )
                        );

                    try {
                        var afterAdd = wpf.Invoke(() => new HashSet <string>(
                                                      list.Environments.Select(ev => (string)ev.InterpreterPath),
                                                      StringComparer.OrdinalIgnoreCase
                                                      ));

                        Assert.AreNotEqual(before.Count, afterAdd.Count, "Did not add a new environment");
                        AssertUtil.ContainsExactly(
                            afterAdd.Except(before),
                            TestData.GetPath("HelloWorld\\HelloWorld.pyproj")
                            );

                        list.Service.AddConfigurableInterpreter(
                            id,
                            new InterpreterConfiguration(
                                "",
                                "test",
                                "",
                                TestData.GetPath("HelloWorld2\\HelloWorld.pyproj")
                                )
                            );

                        var afterUpdate = wpf.Invoke(() => new HashSet <string>(
                                                         list.Environments.Select(ev => (string)ev.InterpreterPath),
                                                         StringComparer.OrdinalIgnoreCase
                                                         ));

                        Assert.AreEqual(afterAdd.Count, afterUpdate.Count, "Should not add/remove an environment");
                        AssertUtil.ContainsExactly(
                            afterUpdate.Except(before),
                            TestData.GetPath("HelloWorld2\\HelloWorld.pyproj")
                            );
                    } finally {
                        list.Service.RemoveConfigurableInterpreter(fact);
                    }

                    var afterRemove = wpf.Invoke(() => new HashSet <string>(
                                                     list.Environments.Select(ev => (string)ev.InterpreterPath),
                                                     StringComparer.OrdinalIgnoreCase
                                                     ));
                    AssertUtil.ContainsExactly(afterRemove, before);
                }
        }
Beispiel #29
0
        private void ImportWizardVirtualEnvWorker(
            PythonVersion python,
            string venvModuleName,
            string expectedFile,
            bool brokenBaseInterpreter
            )
        {
            var mockService = new MockInterpreterOptionsService();

            mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider",
                                                                             new MockPythonInterpreterFactory(python.Configuration)
                                                                             ));

            using (var wpf = new WpfProxy()) {
                var settings   = wpf.Create(() => new ImportSettings(null, mockService));
                var sourcePath = TestData.GetTempPath(randomSubPath: true);
                // Create a fake set of files to import
                File.WriteAllText(Path.Combine(sourcePath, "main.py"), "");
                Directory.CreateDirectory(Path.Combine(sourcePath, "A"));
                File.WriteAllText(Path.Combine(sourcePath, "A", "__init__.py"), "");
                // Create a real virtualenv environment to import
                using (var p = ProcessOutput.RunHiddenAndCapture(python.InterpreterPath, "-m", venvModuleName, Path.Combine(sourcePath, "env"))) {
                    Console.WriteLine(p.Arguments);
                    p.Wait();
                    Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines)));
                    Assert.AreEqual(0, p.ExitCode);
                }

                if (brokenBaseInterpreter)
                {
                    var cfgPath = Path.Combine(sourcePath, "env", "Lib", "orig-prefix.txt");
                    if (File.Exists(cfgPath))
                    {
                        File.WriteAllText(cfgPath, string.Format("C:\\{0:N}", Guid.NewGuid()));
                    }
                    else if (File.Exists((cfgPath = Path.Combine(sourcePath, "env", "pyvenv.cfg"))))
                    {
                        File.WriteAllLines(cfgPath, File.ReadAllLines(cfgPath)
                                           .Select(line => {
                            if (line.StartsWith("home = "))
                            {
                                return(string.Format("home = C:\\{0:N}", Guid.NewGuid()));
                            }
                            return(line);
                        })
                                           );
                    }
                }

                Console.WriteLine("All files:");
                foreach (var f in Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories))
                {
                    Console.WriteLine(PathUtils.GetRelativeFilePath(sourcePath, f));
                }

                Assert.IsTrue(
                    File.Exists(Path.Combine(sourcePath, "env", expectedFile)),
                    "Virtualenv was not created correctly"
                    );

                settings.SourcePath = sourcePath;

                string path = CreateRequestedProject(settings);

                Assert.AreEqual(settings.ProjectPath, path);
                var proj = XDocument.Load(path);

                // Does not include any .py files from the virtualenv
                AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value),
                                           "main.py",
                                           "A\\__init__.py"
                                           );
                // Does not contain 'env'
                AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value),
                                           "A"
                                           );

                var env = proj.Descendants(proj.GetName("Interpreter")).SingleOrDefault();
                if (brokenBaseInterpreter)
                {
                    Assert.IsNull(env);
                }
                else
                {
                    Assert.AreEqual("env\\", env.Attribute("Include").Value);
                    Assert.AreNotEqual("", env.Descendant("Id").Value);
                    Assert.AreEqual(string.Format("env ({0})", python.Configuration.Description), env.Descendant("Description").Value);
                    Assert.AreEqual("scripts\\python.exe", env.Descendant("InterpreterPath").Value, true);
                    Assert.AreEqual("scripts\\pythonw.exe", env.Descendant("WindowsInterpreterPath").Value, true);
                    Assert.AreEqual("PYTHONPATH", env.Descendant("PathEnvironmentVariable").Value, true);
                    Assert.AreEqual(python.Configuration.Version.ToString(), env.Descendant("Version").Value, true);
                    Assert.AreEqual(python.Configuration.Architecture.ToString("X"), env.Descendant("Architecture").Value, true);
                }
            }
        }