<commit_before>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using EnvDTE;
using Microsoft.VisualStudio.ExtensionManager;
using Microsoft.VisualStudio.TemplateWizard;
using Moq;
using NuGet.Test;
using Xunit;
using Xunit.Extensions;
using NuGetConsole;

namespace NuGet.VisualStudio.Test
{
    public class VsTemplateWizardTest
    {
        private static readonly XNamespace VSTemplateNamespace = "http://schemas.microsoft.com/developer/vstemplate/2005";

        private class RepositoryWithPackages
        {
            public RepositoryWithPackages(string repository, XObject[] repositoryChildren)
            {
                this.Repository = repository;
                this.RepositoryChildren = repositoryChildren;
            }

            public string Repository { get; private set; }
            public XObject[] RepositoryChildren { get; private set; }
        }

        private static XDocument BuildDocument(string repository = "template", params XObject[] packagesChildren)
        {
            return BuildDocument(new[] { new RepositoryWithPackages(repository, packagesChildren) });
        }

        private static XDocument BuildDocument(IEnumerable<RepositoryWithPackages> repositoriesWithPackages)
        {
            var elements = new List<XObject>();

            if (repositoriesWithPackages != null && repositoriesWithPackages.Any())
            {
                foreach (var repository in repositoriesWithPackages)
                {
                    var children = new List<XObject>();
                    if (repository.Repository != null)
                    {
                        children.Add(new XAttribute("repository", repository.Repository));
                    }

                    children.AddRange(repository.RepositoryChildren);

                    elements.AddRange(new[] { new XElement(VSTemplateNamespace + "packages", children) });
                }
            }

            return new XDocument(new XElement("VSTemplate",
                new XElement(VSTemplateNamespace + "WizardData", elements)));
        }

        private static XDocument BuildDocumentWithPackage(string repository, XObject additionalChild = null)
        {
            return BuildDocument(repository, BuildPackageElement("pack", "1.0"), additionalChild);
        }

        private static XElement BuildPackageElement(string id = null, string version = null, bool skipAssemblyReferences = false)
        {
            var packageElement = new XElement(VSTemplateNamespace + "package");
            if (id != null)
            {
                packageElement.Add(new XAttribute("id", id));
            }
            if (version != null)
            {
                packageElement.Add(new XAttribute("version", version));
            }
            if (skipAssemblyReferences)
            {
                packageElement.Add(new XAttribute("skipAssemblyReferences", skipAssemblyReferences.ToString()));
            }
            return packageElement;
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithMissingWizardDataElement()
        {
            // Arrange
            var document = new XDocument(new XElement(VSTemplateNamespace + "VSTemplate"));
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate");

            // Assert
            Assert.Equal(0, results.Count());
        }

        [Theory]
        [InlineData("true", true)]
        [InlineData("false", false)]
        public void GetConfigurationRecognizeIsPreunzippedAttribute(string preunzippedValue, bool expectedResult)
        {
            // Arrange
            var document = BuildDocument();
            document.Element("VSTemplate")
                    .Element(VSTemplateNamespace + "WizardData")
                    .Element(VSTemplateNamespace + "packages")
                    .Add(new XAttribute("isPreunzipped", preunzippedValue));

            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"c:\some\file.vstemplate");

            // Assert
            Assert.Equal(1, results.Count());
            Assert.Equal(expectedResult, results.Single().IsPreunzipped);
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithMissingPackagesElement()
        {
            // Arrange
            var document = new XDocument(
                new XElement(VSTemplateNamespace + "VSTemplate",
                    new XElement(VSTemplateNamespace + "WizardData")
                    ));
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate");

            // Assert
            Assert.Equal(0, results.Count());
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithEmptyPackagesElement()
        {
            // Arrange
            var document = BuildDocument((string)null);
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate");

            // Assert
            Assert.Equal(1, results.Count());
            Assert.Equal(0, results.Single().Packages.Count);
            Assert.Equal(null, results.Single().RepositoryPath);
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithTemplateRepository()
        {
            // Arrange
            var document = BuildDocumentWithPackage("template");
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate");

            // Assert
            Assert.Equal(1, results.Count());
            Assert.Equal(1, results.Single().Packages.Count);
            Assert.Equal(@"C:\Some", results.Single().RepositoryPath);
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithExtensionRepository()
        {
            // Arrange
            var document = BuildDocumentWithPackage("extension", new XAttribute("repositoryId", "myExtensionId"));
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);
            var extensionManagerMock = new Mock<IVsExtensionManager>();
            var extensionMock = new Mock<IInstalledExtension>();
            extensionMock.Setup(e => e.InstallPath).Returns(@"C:\Extension\Dir");
            var extension = extensionMock.Object;
            extensionManagerMock.Setup(em => em.TryGetInstalledExtension("myExtensionId", out extension)).Returns(true);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate", vsExtensionManager: extensionManagerMock.Object);

            // Assert
            Assert.Equal(1, results.Count());
            Assert.Equal(1, results.Single().Packages.Count);
            Assert.Equal(@"C:\Extension\Dir\Packages", results.Single().RepositoryPath);
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithMultipleRepositories()
        {
            // Arrange
            var registryPath = @"SOFTWARE\NuGet\Repository";
            var registryKey = "<KEY>";
            var registryValue = @"C:\AspNetMvc4\Packages";

            var extensionRepository = new RepositoryWithPackages("extension", new XObject[] { new XAttribute("repositoryId", "myExtensionId"), BuildPackageElement("packageFromExtension", "1.0") });
            var registryRepository = new RepositoryWithPackages("registry", new XObject[] { new XAttribute("keyName", registryKey), BuildPackageElement("packageFromRegistry", "2.0") });

            var document = BuildDocument(new[] { extensionRepository, registryRepository });
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);
            var extensionManagerMock = new Mock<IVsExtensionManager>();
            var extensionMock = new Mock<IInstalledExtension>();
            extensionMock.Setup(e => e.InstallPath).Returns(@"C:\Extension\Dir");
            var extension = extensionMock.Object;
            extensionManagerMock.Setup(em => em.TryGetInstalledExtension("myExtensionId", out extension)).Returns(true);

            var hkcu_repository = new Mock<IRegistryKey>();
            var hkcu = new Mock<IRegistryKey>();
            hkcu_repository.Setup(k => k.GetValue(registryKey)).Returns(registryValue);
            hkcu.Setup(r => r.OpenSubKey(registryPath)).Returns(hkcu_repository.Object);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate", vsExtensionManager: extensionManagerMock.Object, registryKeys: new[] { hkcu.Object });

            // Assert
            Assert.Equal(2, results.Count());
            var extensionResult = results.First();
            var registryResult = results.Last();
<commit_msg>Preinstalled package code review tweaks. Fixes 2941.<commit_after>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using EnvDTE;
using Microsoft.VisualStudio.ExtensionManager;
using Microsoft.VisualStudio.TemplateWizard;
using Moq;
using NuGet.Test;
using Xunit;
using Xunit.Extensions;
using NuGetConsole;

namespace NuGet.VisualStudio.Test
{
    public class VsTemplateWizardTest
    {
        private static readonly XNamespace VSTemplateNamespace = "http://schemas.microsoft.com/developer/vstemplate/2005";

        private class VsTemplatePackagesNode
        {
            public VsTemplatePackagesNode(string repository, XObject[] repositoryChildren)
            {
                this.Repository = repository;
                this.ChildNodes = repositoryChildren;
            }

            public string Repository { get; private set; }
            public XObject[] ChildNodes { get; private set; }
        }

        private static XDocument BuildDocument(string repository = "template", params XObject[] packagesChildren)
        {
            return BuildDocument(new[] { new VsTemplatePackagesNode(repository, packagesChildren) });
        }

        private static XDocument BuildDocument(IEnumerable<VsTemplatePackagesNode> repositoriesWithPackages)
        {
            var elements = new List<XObject>();

            if (repositoriesWithPackages != null && repositoriesWithPackages.Any())
            {
                foreach (var repository in repositoriesWithPackages)
                {
                    var children = new List<XObject>();
                    if (repository.Repository != null)
                    {
                        children.Add(new XAttribute("repository", repository.Repository));
                    }

                    children.AddRange(repository.ChildNodes);

                    elements.AddRange(new[] { new XElement(VSTemplateNamespace + "packages", children) });
                }
            }

            return new XDocument(new XElement("VSTemplate",
                new XElement(VSTemplateNamespace + "WizardData", elements)));
        }

        private static XDocument BuildDocumentWithPackage(string repository, XObject additionalChild = null)
        {
            return BuildDocument(repository, BuildPackageElement("pack", "1.0"), additionalChild);
        }

        private static XElement BuildPackageElement(string id = null, string version = null, bool skipAssemblyReferences = false)
        {
            var packageElement = new XElement(VSTemplateNamespace + "package");
            if (id != null)
            {
                packageElement.Add(new XAttribute("id", id));
            }
            if (version != null)
            {
                packageElement.Add(new XAttribute("version", version));
            }
            if (skipAssemblyReferences)
            {
                packageElement.Add(new XAttribute("skipAssemblyReferences", skipAssemblyReferences.ToString()));
            }
            return packageElement;
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithMissingWizardDataElement()
        {
            // Arrange
            var document = new XDocument(new XElement(VSTemplateNamespace + "VSTemplate"));
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate");

            // Assert
            Assert.Equal(0, results.Count());
        }

        [Theory]
        [InlineData("true", true)]
        [InlineData("false", false)]
        public void GetConfigurationRecognizeIsPreunzippedAttribute(string preunzippedValue, bool expectedResult)
        {
            // Arrange
            var document = BuildDocument();
            document.Element("VSTemplate")
                    .Element(VSTemplateNamespace + "WizardData")
                    .Element(VSTemplateNamespace + "packages")
                    .Add(new XAttribute("isPreunzipped", preunzippedValue));

            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"c:\some\file.vstemplate");

            // Assert
            Assert.Equal(1, results.Count());
            Assert.Equal(expectedResult, results.Single().IsPreunzipped);
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithMissingPackagesElement()
        {
            // Arrange
            var document = new XDocument(
                new XElement(VSTemplateNamespace + "VSTemplate",
                    new XElement(VSTemplateNamespace + "WizardData")
                    ));
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate");

            // Assert
            Assert.Equal(0, results.Count());
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithEmptyPackagesElement()
        {
            // Arrange
            var document = BuildDocument((string)null);
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate");

            // Assert
            Assert.Equal(1, results.Count());
            Assert.Equal(0, results.Single().Packages.Count);
            Assert.Equal(null, results.Single().RepositoryPath);
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithTemplateRepository()
        {
            // Arrange
            var document = BuildDocumentWithPackage("template");
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate");

            // Assert
            Assert.Equal(1, results.Count());
            Assert.Equal(1, results.Single().Packages.Count);
            Assert.Equal(@"C:\Some", results.Single().RepositoryPath);
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithExtensionRepository()
        {
            // Arrange
            var document = BuildDocumentWithPackage("extension", new XAttribute("repositoryId", "myExtensionId"));
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);
            var extensionManagerMock = new Mock<IVsExtensionManager>();
            var extensionMock = new Mock<IInstalledExtension>();
            extensionMock.Setup(e => e.InstallPath).Returns(@"C:\Extension\Dir");
            var extension = extensionMock.Object;
            extensionManagerMock.Setup(em => em.TryGetInstalledExtension("myExtensionId", out extension)).Returns(true);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate", vsExtensionManager: extensionManagerMock.Object);

            // Assert
            Assert.Equal(1, results.Count());
            Assert.Equal(1, results.Single().Packages.Count);
            Assert.Equal(@"C:\Extension\Dir\Packages", results.Single().RepositoryPath);
        }

        [Fact]
        public void GetConfigurationFromXmlDocument_WorksWithMultipleRepositories()
        {
            // Arrange
            var registryPath = @"SOFTWARE\NuGet\Repository";
            var registryKey = "<KEY>";
            var registryValue = @"C:\AspNetMvc4\Packages";

            var extensionRepository = new VsTemplatePackagesNode("extension", new XObject[] { new XAttribute("repositoryId", "myExtensionId"), BuildPackageElement("packageFromExtension", "1.0") });
            var registryRepository = new VsTemplatePackagesNode("registry", new XObject[] { new XAttribute("keyName", registryKey), BuildPackageElement("packageFromRegistry", "2.0") });

            var document = BuildDocument(new[] { extensionRepository, registryRepository });
            var wizard = new VsTemplateWizard(null, null, null, null, null, null);
            var extensionManagerMock = new Mock<IVsExtensionManager>();
            var extensionMock = new Mock<IInstalledExtension>();
            extensionMock.Setup(e => e.InstallPath).Returns(@"C:\Extension\Dir");
            var extension = extensionMock.Object;
            extensionManagerMock.Setup(em => em.TryGetInstalledExtension("myExtensionId", out extension)).Returns(true);

            var hkcu_repository = new Mock<IRegistryKey>();
            var hkcu = new Mock<IRegistryKey>();
            hkcu_repository.Setup(k => k.GetValue(registryKey)).Returns(registryValue);
            hkcu.Setup(r => r.OpenSubKey(registryPath)).Returns(hkcu_repository.Object);

            // Act
            var results = wizard.GetConfigurationFromXmlDocument(document, @"C:\Some\file.vstemplate", vsExtensionManager: extensionManagerMock.Object, registryKeys: new[] { hkcu.Object });

            // Assert
            Assert.Equal(2, results.Count());
            var extensionResult = results.First();
            var registryResult = results.Last();

{'fraction_non_alphanumeric': 0.10209213976135695, 'fraction_numerical': 0.0024613408957140565, 'mean_word_length': 2.3062090925172476, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7312481', 'n_tokens_mistral': 4614, 'n_tokens_neox': 4432, 'n_words': 952}