Example #1
0
#pragma warning restore xUnit1004 // Test methods should not be skipped
        public async Task CacheSkipInvalidTemplatesTest()
        {
            string cacheLocation  = TestUtils.CreateTemporaryFolder();
            string v2FileLocation = SetupInvalidTemplateCache(cacheLocation);

            var environment = A.Fake <IEnvironment>();

            var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(hostIdentifier: this.GetType().Name, virtualize: true, environment: environment);
            var templatePackageManager    = new TemplatePackageManager(engineEnvironmentSettings);

            engineEnvironmentSettings.Components.AddComponent(typeof(ITemplateSearchProviderFactory), new NuGetMetadataSearchProviderFactory());

            NewCommand        myCommand   = (NewCommand)NewCommandFactory.Create("new", _ => engineEnvironmentSettings.Host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var               parseResult = myCommand.Parse($"new search --unknown");
            SearchCommandArgs args        = new SearchCommandArgs((SearchCommand)parseResult.CommandResult.Command, parseResult);

            var templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, default).ConfigureAwait(false);

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings);
            CliSearchFiltersFactory   factory           = new CliSearchFiltersFactory(templatePackages);

            A.CallTo(() => environment.GetEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE")).Returns(v2FileLocation);
            var searchResults = await searchCoordinator.SearchAsync(
                factory.GetPackFilter(args),
                CliSearchFiltersFactory.GetMatchingTemplatesFilter(args),
                default).ConfigureAwait(false);

            Assert.Equal(1, searchResults.Count);
            Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org");
            var nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org");

            Assert.Equal(0, nugetSearchResults.SearchHits.Count);
        }
        public async Task CacheSearchPackageFilterTest(string commandTemplate, string commandPackage, int packMatchCount, int templateMatchCount)
        {
            TemplateDiscoveryMetadata mockTemplateDiscoveryMetadata = SetupDiscoveryMetadata(false);

            MockCliNuGetMetadataSearchSource.SetupMockData(mockTemplateDiscoveryMetadata);
            EngineEnvironmentSettings.SettingsLoader.Components.Register(typeof(MockCliNuGetMetadataSearchSource));

            Dictionary <string, string> rawCommandInputs = new Dictionary <string, string>();
            MockNewCommandInput         commandInput     = new MockNewCommandInput(rawCommandInputs)
            {
                TemplateName  = commandTemplate,
                PackageFilter = commandPackage
            };

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(EngineEnvironmentSettings, commandInput, DefaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync();

            Assert.True(searchResults.AnySources);
            if (packMatchCount == 0)
            {
                Assert.Equal(0, searchResults.MatchesBySource.Count);
            }
            else
            {
                Assert.Equal(1, searchResults.MatchesBySource.Count);
                Assert.Equal(packMatchCount, searchResults.MatchesBySource[0].PacksWithMatches.Count);
                Assert.Equal(templateMatchCount, searchResults.MatchesBySource[0].PacksWithMatches[_packThreeInfo].TemplateMatches.Count);
            }
        }
        public async Task CacheSearchCliSymbolNameFilterTest()
        {
            TemplateDiscoveryMetadata mockTemplateDiscoveryMetadata = SetupDiscoveryMetadata(true);

            MockCliNuGetMetadataSearchSource.SetupMockData(mockTemplateDiscoveryMetadata);
            _engineEnvironmentSettings.SettingsLoader.Components.Register(typeof(MockCliNuGetMetadataSearchSource));

            INewCommandInput commandInput = new MockNewCommandInput("foo").WithTemplateOption("framework", "netcoreapp2.0");

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(_engineEnvironmentSettings, commandInput, DefaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync().ConfigureAwait(false);

            Assert.True(searchResults.AnySources);
            Assert.Equal(1, searchResults.MatchesBySource.Count);
            Assert.Equal(1, searchResults.MatchesBySource[0].PacksWithMatches.Count);
            Assert.Single(searchResults.MatchesBySource[0].PacksWithMatches[_packTwoInfo].TemplateMatches.Where(t => string.Equals(t.Info.Name, _fooTwoTemplate.Name)));

            INewCommandInput shortNameCommandInput = new MockNewCommandInput("foo").WithTemplateOption("f", "netcoreapp2.0");

            TemplateSearchCoordinator shortNameSearchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(_engineEnvironmentSettings, shortNameCommandInput, DefaultLanguage);
            SearchResults             shortNameSearchResults     = await searchCoordinator.SearchAsync().ConfigureAwait(false);

            Assert.True(shortNameSearchResults.AnySources);
            Assert.Equal(1, shortNameSearchResults.MatchesBySource.Count);
            Assert.Equal(1, shortNameSearchResults.MatchesBySource[0].PacksWithMatches.Count);
            Assert.Single(shortNameSearchResults.MatchesBySource[0].PacksWithMatches[_packTwoInfo].TemplateMatches.Where(t => string.Equals(t.Info.Name, _fooTwoTemplate.Name)));
        }
        // Return true if there are any matches, false otherwise.
        private async Task <bool> SearchForTemplateMatchesAsync()
        {
            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(_environment, _commandInput, _defaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync();

            if (searchResults.AnySources)
            {
                // Only show the searching online message if there are sources to search.
                // It's a bit out of order to do the search first, then display the message.
                // But there's no way to know whether or not there are sources without searching.
                // ...theoretically the search source initialization is separate from the search, but the initialization is most of the work.
                Reporter.Output.WriteLine(LocalizableStrings.SearchingOnlineNotification.Bold().Red());
            }
            else
            {
                return(false);
            }

            foreach (TemplateSourceSearchResult sourceResult in searchResults.MatchesBySource)
            {
                string sourceHeader = string.Format(LocalizableStrings.SearchResultSourceIndicator, sourceResult.SourceDisplayName);

                Reporter.Output.WriteLine(sourceHeader);
                Reporter.Output.WriteLine(new string('-', sourceHeader.Length));

                foreach (TemplatePackSearchResult matchesForPack in sourceResult.PacksWithMatches.Values)
                {
                    DisplayResultsForPack(matchesForPack);
                    Reporter.Output.WriteLine();
                }
            }

            return(searchResults.MatchesBySource.Count > 0);
        }
Example #5
0
        public async Task SearchOverrideCache_FailsWhenFileDoesntExist()
        {
            string searchFilePath = "do-not-exist";
            var    environment    = new MockEnvironment();

            environment.SetEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", searchFilePath);

            IEngineEnvironmentSettings engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(hostIdentifier: this.GetType().Name, virtualize: true, environment: environment);

            engineEnvironmentSettings.Components.AddComponent(typeof(ITemplateSearchProviderFactory), new NuGetMetadataSearchProviderFactory());

            const string templateName = "foo";

            Func <TemplatePackageSearchData, IReadOnlyList <ITemplateInfo> > filter =
                templatePack => templatePack.Templates
                .Where(t => ((ITemplateInfo)t).Name.Contains(templateName, StringComparison.OrdinalIgnoreCase))
                .ToList();

            var searchCoordinator = new TemplateSearchCoordinator(engineEnvironmentSettings);
            var searchResult      = await searchCoordinator.SearchAsync(p => true, filter, default).ConfigureAwait(false);

            Assert.NotNull(searchResult);
            Assert.Equal(1, searchResult.Count);
            Assert.False(searchResult[0].Success);
            Assert.False(string.IsNullOrWhiteSpace(searchResult[0].ErrorMessage));
            Assert.True(searchResult[0].SearchHits.Count == 0);
            Assert.Equal("Local search cache 'do-not-exist' does not exist.", searchResult[0].ErrorMessage);

            //provider should not copy local file to settings
            Assert.False(engineEnvironmentSettings.Host.FileSystem.FileExists(Path.Combine(engineEnvironmentSettings.Paths.HostVersionSettingsDir, "nugetTemplateSearchInfo.json")));
        }
Example #6
0
        public async Task SearchReturnsErrorOnIncorrectVersionCache()
        {
            var    jsonObject     = JObject.FromObject(new { version = "3.0", TemplatePackages = Array.Empty <string>() });
            string searchFilePath = Path.Combine(TestUtils.CreateTemporaryFolder(), "searchCache.json");

            File.WriteAllText(searchFilePath, jsonObject.ToString());

            var environment = new MockEnvironment();

            environment.SetEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE", searchFilePath);

            IEngineEnvironmentSettings engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(hostIdentifier: this.GetType().Name, virtualize: true, environment: environment);

            engineEnvironmentSettings.Components.AddComponent(typeof(ITemplateSearchProviderFactory), new NuGetMetadataSearchProviderFactory());

            const string templateName = "foo";

            Func <TemplatePackageSearchData, IReadOnlyList <ITemplateInfo> > filter =
                templatePack => templatePack.Templates
                .Where(t => ((ITemplateInfo)t).Name.Contains(templateName, StringComparison.OrdinalIgnoreCase))
                .ToList();

            var searchCoordinator = new TemplateSearchCoordinator(engineEnvironmentSettings);
            var searchResult      = await searchCoordinator.SearchAsync(p => true, filter, default).ConfigureAwait(false);

            Assert.NotNull(searchResult);
            Assert.Equal(1, searchResult.Count);
            Assert.False(searchResult[0].Success);
            Assert.False(string.IsNullOrWhiteSpace(searchResult[0].ErrorMessage));
            Assert.True(searchResult[0].SearchHits.Count == 0);
            Assert.Equal("The template search cache data is not supported.", searchResult[0].ErrorMessage);

            //provider should not copy local file to settings
            Assert.False(engineEnvironmentSettings.Host.FileSystem.FileExists(Path.Combine(engineEnvironmentSettings.Paths.HostVersionSettingsDir, "nugetTemplateSearchInfo.json")));
        }
Example #7
0
        public async Task SearchLocalCache()
        {
            var environment = new MockEnvironment();

            environment.SetEnvironmentVariable("DOTNET_NEW_LOCAL_SEARCH_FILE_ONLY", "true");

            IEngineEnvironmentSettings engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(hostIdentifier: this.GetType().Name, virtualize: true, environment: environment);

            engineEnvironmentSettings.Components.AddComponent(typeof(ITemplateSearchProviderFactory), new NuGetMetadataSearchProviderFactory());

            const string templateName = "api";

            Func <TemplatePackageSearchData, IReadOnlyList <ITemplateInfo> > filter =
                templatePack => templatePack.Templates
                .Where(t => ((ITemplateInfo)t).Name.Contains(templateName, StringComparison.OrdinalIgnoreCase))
                .ToList();

            var searchCoordinator = new TemplateSearchCoordinator(engineEnvironmentSettings);
            Func <Task <IReadOnlyList <SearchResult> > > search = async() =>
            {
                var result = await searchCoordinator.SearchAsync(p => true, filter, default).ConfigureAwait(false);

                if (result != null && result.Count > 0 && !string.IsNullOrWhiteSpace(result[0].ErrorMessage))
                {
                    var errorMessage = result[0].ErrorMessage;
                    if (errorMessage !.Contains("The SSL connection could not be established"))
                    {
                        throw new HttpRequestException(errorMessage);
                    }
                }
                return(result !);
            };
            var searchResult = await TestUtils.AttemptSearch <IReadOnlyList <SearchResult>, HttpRequestException>(3, TimeSpan.FromSeconds(10), search);

            Assert.NotNull(searchResult);
            Assert.Equal(1, searchResult.Count);
            Assert.False(searchResult[0].Success);
            Assert.False(string.IsNullOrWhiteSpace(searchResult[0].ErrorMessage));
            Assert.True(searchResult[0].SearchHits.Count == 0);
            Assert.Equal($"Local search cache '{Path.Combine(engineEnvironmentSettings.Paths.HostVersionSettingsDir, "nugetTemplateSearchInfo.json")}' does not exist.", searchResult[0].ErrorMessage);

            environment.SetEnvironmentVariable("DOTNET_NEW_LOCAL_SEARCH_FILE_ONLY", null);
            searchResult = await TestUtils.AttemptSearch <IReadOnlyList <SearchResult>, HttpRequestException>(3, TimeSpan.FromSeconds(10), search);

            Assert.NotNull(searchResult);
            Assert.Equal(1, searchResult.Count);
            Assert.True(searchResult[0].Success);
            Assert.True(string.IsNullOrWhiteSpace(searchResult[0].ErrorMessage));
            Assert.True(searchResult[0].SearchHits.Count > 0);

            environment.SetEnvironmentVariable("DOTNET_NEW_LOCAL_SEARCH_FILE_ONLY", "true");
            searchResult = await TestUtils.AttemptSearch <IReadOnlyList <SearchResult>, HttpRequestException>(3, TimeSpan.FromSeconds(10), search);

            Assert.NotNull(searchResult);
            Assert.Equal(1, searchResult.Count);
            Assert.True(searchResult[0].Success);
            Assert.True(string.IsNullOrWhiteSpace(searchResult[0].ErrorMessage));
            Assert.True(searchResult[0].SearchHits.Count > 0);
        }
        /// <summary>
        /// Executes searching for the templates in configured remote sources.
        /// Performs validation for the commands, search for the templates in configured remote source, displays the results in table format
        /// </summary>
        /// <param name="environmentSettings">environment settings</param>
        /// <param name="commandInput">new command data</param>
        /// <param name="defaultLanguage">default language for the host</param>
        /// <returns><c>CreationResultStatus.Success</c> when the templates were found and displayed;
        /// <c>CreationResultStatus.Cancelled</c> when the command validation fails;
        /// <c>CreationResultStatus.NotFound</c> when no templates found based on the filter criteria.
        /// </returns>
        internal static async Task <CreationResultStatus> SearchForTemplateMatchesAsync(IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, string defaultLanguage)
        {
            if (!ValidateCommandInput(commandInput))
            {
                return(CreationResultStatus.Cancelled);
            }

            Reporter.Output.WriteLine(LocalizableStrings.SearchOnlineNotification);
            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(environmentSettings, commandInput, defaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync().ConfigureAwait(false);

            if (!searchResults.AnySources)
            {
                Reporter.Error.WriteLine(LocalizableStrings.SearchOnlineNoSources.Bold().Red());
                return(CreationResultStatus.NotFound);
            }

            if (searchResults.MatchesBySource.Count > 0)
            {
                string packageIdToShow = null;
                foreach (TemplateSourceSearchResult sourceResult in searchResults.MatchesBySource)
                {
                    DisplayResultsForPack(sourceResult, environmentSettings, commandInput, defaultLanguage);

                    var firstMicrosoftAuthoredPack = sourceResult.PacksWithMatches.FirstOrDefault(p => p.Value.TemplateMatches.Any(t => string.Equals(t.Info.Author, "Microsoft")));
                    if (!firstMicrosoftAuthoredPack.Equals(default(KeyValuePair <PackInfo, TemplatePackSearchResult>)))
                    {
                        packageIdToShow = firstMicrosoftAuthoredPack.Key.Name;
                    }
                }

                Reporter.Output.WriteLine();
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.SearchResultInstallHeader, commandInput.CommandName));
                if (string.IsNullOrWhiteSpace(packageIdToShow))
                {
                    packageIdToShow = searchResults.MatchesBySource.First().PacksWithMatches.First().Key.Name;
                }
                Reporter.Output.WriteLine("Example:");
                Reporter.Output.WriteLine(string.Format(LocalizableStrings.SearchResultInstallCommand, commandInput.CommandName, packageIdToShow));
                return(CreationResultStatus.Success);
            }
            else
            {
                string filters        = string.Join(", ", SupportedFilterOptions.SupportedSearchFilters.Where(filter => filter.IsFilterSet(commandInput)).Select(filter => $"{filter.Name}='{filter.FilterValue(commandInput)}'"));
                string searchCriteria = string.IsNullOrWhiteSpace(commandInput.TemplateName)
                    ? filters
                    : string.IsNullOrWhiteSpace(filters) ? commandInput.TemplateName : string.Join(", ", commandInput.TemplateName, filters);

                Reporter.Error.WriteLine(string.Format(LocalizableStrings.NoTemplatesMatchingInputParameters, searchCriteria).Bold().Red());
                return(CreationResultStatus.NotFound);
            }
        }
        public async Task CacheSearchLanguageMismatchFilterTest()
        {
            TemplateDiscoveryMetadata mockTemplateDiscoveryMetadata = SetupDiscoveryMetadata(false);

            MockCliNuGetMetadataSearchSource.SetupMockData(mockTemplateDiscoveryMetadata);
            _engineEnvironmentSettings.SettingsLoader.Components.Register(typeof(MockCliNuGetMetadataSearchSource));

            MockNewCommandInput commandInput = new MockNewCommandInput("bar", "VB");

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(_engineEnvironmentSettings, commandInput, DefaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync().ConfigureAwait(false);

            Assert.True(searchResults.AnySources);
            Assert.Equal(0, searchResults.MatchesBySource.Count);
        }
        public async Task CacheSearchCliSymbolNameMismatchFilterTest()
        {
            TemplateDiscoveryMetadata mockTemplateDiscoveryMetadata = SetupDiscoveryMetadata(true);

            MockCliNuGetMetadataSearchSource.SetupMockData(mockTemplateDiscoveryMetadata);
            _engineEnvironmentSettings.SettingsLoader.Components.Register(typeof(MockCliNuGetMetadataSearchSource));

            // "tfm" is not a vaild symbol for the "foo" template. So it should not match.
            INewCommandInput commandInput = new MockNewCommandInput("foo").WithTemplateOption("tfm", "netcoreapp2.0");

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(_engineEnvironmentSettings, commandInput, DefaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync().ConfigureAwait(false);

            Assert.True(searchResults.AnySources);
            Assert.Equal(0, searchResults.MatchesBySource.Count);
        }
        public async Task CacheSearchLanguageFilterTest()
        {
            TemplateDiscoveryMetadata mockTemplateDiscoveryMetadata = SetupDiscoveryMetadata(false);

            MockCliNuGetMetadataSearchSource.SetupMockData(mockTemplateDiscoveryMetadata);
            _engineEnvironmentSettings.SettingsLoader.Components.Register(typeof(MockCliNuGetMetadataSearchSource));

            Dictionary <string, string> rawCommandInputs = new Dictionary <string, string>();
            MockNewCommandInput         commandInput     = new MockNewCommandInput("bar", "F#");

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(_engineEnvironmentSettings, commandInput, DefaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync().ConfigureAwait(false);

            Assert.True(searchResults.AnySources);
            Assert.Equal(1, searchResults.MatchesBySource.Count);
            Assert.Equal(1, searchResults.MatchesBySource[0].PacksWithMatches.Count);
            Assert.Single(searchResults.MatchesBySource[0].PacksWithMatches[_packThreeInfo].TemplateMatches.Where(t => string.Equals(t.Info.Name, _barFSharpTemplate.Name)));
        }
        public async Task CacheSearchNameMatchTest()
        {
            TemplateDiscoveryMetadata mockTemplateDiscoveryMetadata = SetupDiscoveryMetadata(false);

            MockCliNuGetMetadataSearchSource.SetupMockData(mockTemplateDiscoveryMetadata);
            EngineEnvironmentSettings.SettingsLoader.Components.Register(typeof(MockCliNuGetMetadataSearchSource));

            INewCommandInput commandInput = new MockNewCommandInput("foo");

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(EngineEnvironmentSettings, commandInput, DefaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync();

            Assert.True(searchResults.AnySources);
            Assert.Equal(1, searchResults.MatchesBySource.Count);
            Assert.Equal(2, searchResults.MatchesBySource[0].PacksWithMatches.Count);
            Assert.Single(searchResults.MatchesBySource[0].PacksWithMatches[_packOneInfo].TemplateMatches.Where(t => string.Equals(t.Info.Name, _fooOneTemplate.Name)));
            Assert.Single(searchResults.MatchesBySource[0].PacksWithMatches[_packTwoInfo].TemplateMatches.Where(t => string.Equals(t.Info.Name, _fooTwoTemplate.Name)));
        }
        public async Task CacheSearchCliSymbolNameFilterTest()
        {
            TemplateDiscoveryMetadata mockTemplateDiscoveryMetadata = SetupDiscoveryMetadata(true);

            MockCliNuGetMetadataSearchSource.SetupMockData(mockTemplateDiscoveryMetadata);
            EngineEnvironmentSettings.SettingsLoader.Components.Register(typeof(MockCliNuGetMetadataSearchSource));

            // The template symbol is "Framework" (capital "F"). This checks that the host specific override is applied
            Dictionary <string, string> rawCommandInputs = new Dictionary <string, string>()
            {
                { "framework", "netcoreapp2.0" }
            };
            INewCommandInput commandInput = new MockNewCommandInput(rawCommandInputs)
            {
                TemplateName = "foo"
            };

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(EngineEnvironmentSettings, commandInput, DefaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync();

            Assert.True(searchResults.AnySources);
            Assert.Equal(1, searchResults.MatchesBySource.Count);
            Assert.Equal(1, searchResults.MatchesBySource[0].PacksWithMatches.Count);
            Assert.Single(searchResults.MatchesBySource[0].PacksWithMatches[_packTwoInfo].TemplateMatches.Where(t => string.Equals(t.Info.Name, _fooTwoTemplate.Name)));

            // same check, except with the short version of Framework, namely "f"
            Dictionary <string, string> shortNameCheckRawCommandInputs = new Dictionary <string, string>()
            {
                { "f", "netcoreapp2.0" }
            };
            INewCommandInput shortNameCommandInput = new MockNewCommandInput(shortNameCheckRawCommandInputs)
            {
                TemplateName = "foo"
            };

            TemplateSearchCoordinator shortNameSearchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(EngineEnvironmentSettings, shortNameCommandInput, DefaultLanguage);
            SearchResults             shortNameSearchResults     = await searchCoordinator.SearchAsync();

            Assert.True(shortNameSearchResults.AnySources);
            Assert.Equal(1, shortNameSearchResults.MatchesBySource.Count);
            Assert.Equal(1, shortNameSearchResults.MatchesBySource[0].PacksWithMatches.Count);
            Assert.Single(shortNameSearchResults.MatchesBySource[0].PacksWithMatches[_packTwoInfo].TemplateMatches.Where(t => string.Equals(t.Info.Name, _fooTwoTemplate.Name)));
        }
Example #14
0
        public async Task CacheSearchTagFilterTest(string commandTemplate, string commandTag, int packMatchCount, int templateMatchCount)
        {
            string cacheLocation  = TestUtils.CreateTemporaryFolder();
            string v1FileLocation = SetupDiscoveryMetadata(cacheLocation, false);
            string v2FileLocation = SetupTemplateCache(cacheLocation, false);

            var environment = A.Fake <IEnvironment>();
            var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment(
                virtualize: true,
                environment: environment,
                additionalComponents: BuiltInTemplatePackagesProviderFactory.GetComponents(includeTestTemplates: false));
            var templatePackageManager = new TemplatePackageManager(engineEnvironmentSettings);

            engineEnvironmentSettings.Components.AddComponent(typeof(ITemplateSearchProviderFactory), new NuGetMetadataSearchProviderFactory());

            NewCommand        myCommand   = (NewCommand)NewCommandFactory.Create("new", _ => engineEnvironmentSettings.Host, _ => new TelemetryLogger(null, false), new NewCommandCallbacks());
            var               parseResult = myCommand.Parse($"new search {commandTemplate} --tag {commandTag}");
            SearchCommandArgs args        = new SearchCommandArgs((SearchCommand)parseResult.CommandResult.Command, parseResult);

            var templatePackages = await templatePackageManager.GetManagedTemplatePackagesAsync(false, default).ConfigureAwait(false);

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(engineEnvironmentSettings);
            CliSearchFiltersFactory   factory           = new CliSearchFiltersFactory(templatePackages);

            foreach (var location in new[] { v1FileLocation, v2FileLocation })
            {
                A.CallTo(() => environment.GetEnvironmentVariable("DOTNET_NEW_SEARCH_FILE_OVERRIDE")).Returns(location);
                var searchResults = await searchCoordinator.SearchAsync(
                    factory.GetPackFilter(args),
                    CliSearchFiltersFactory.GetMatchingTemplatesFilter(args),
                    default).ConfigureAwait(false);

                Assert.Equal(1, searchResults.Count);
                Assert.Single(searchResults, result => result.Provider.Factory.DisplayName == "NuGet.org");
                var nugetSearchResults = searchResults.Single(result => result.Provider.Factory.DisplayName == "NuGet.org");
                Assert.Equal(packMatchCount, nugetSearchResults.SearchHits.Count);
                if (packMatchCount != 0)
                {
                    Assert.Equal(templateMatchCount, nugetSearchResults.SearchHits.Sum(res => res.MatchedTemplates.Count));
                }
            }
        }
        public async Task TwoSourcesAreBothSearched()
        {
            var provider1 = new MockTemplateSearchProvider();
            var provider2 = new MockTemplateSearchProvider();

            _engineEnvironmentSettings.Components.AddComponent(
                typeof(ITemplateSearchProviderFactory),
                new MockTemplateSearchProviderFactory(Guid.NewGuid(), "provider1", provider1));

            _engineEnvironmentSettings.Components.AddComponent(
                typeof(ITemplateSearchProviderFactory),
                new MockTemplateSearchProviderFactory(Guid.NewGuid(), "provider2", provider2));

            var searchCoordinator = new TemplateSearchCoordinator(_engineEnvironmentSettings);
            var searchResult      = await searchCoordinator.SearchAsync(p => true, p => p.Templates.ToList(), default).ConfigureAwait(false);

            Assert.Equal(2, searchResult.Count());
            Assert.Single(searchResult, r => r.Provider.Factory.DisplayName == "provider1");
            Assert.Single(searchResult, r => r.Provider.Factory.DisplayName == "provider2");

            Assert.True(provider2.WasSearched);
        }
        public async Task CacheSearchTypeFilterTest(string commandTemplate, string commandType, int matchCount)
        {
            TemplateDiscoveryMetadata mockTemplateDiscoveryMetadata = SetupDiscoveryMetadata(false);

            MockCliNuGetMetadataSearchSource.SetupMockData(mockTemplateDiscoveryMetadata);
            _engineEnvironmentSettings.SettingsLoader.Components.Register(typeof(MockCliNuGetMetadataSearchSource));

            MockNewCommandInput commandInput = new MockNewCommandInput(commandTemplate, type: commandType);

            TemplateSearchCoordinator searchCoordinator = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(_engineEnvironmentSettings, commandInput, DefaultLanguage);
            SearchResults             searchResults     = await searchCoordinator.SearchAsync().ConfigureAwait(false);

            Assert.True(searchResults.AnySources);
            if (matchCount == 0)
            {
                Assert.Equal(0, searchResults.MatchesBySource.Count);
            }
            else
            {
                Assert.Equal(1, searchResults.MatchesBySource.Count);
                Assert.Equal(matchCount, searchResults.MatchesBySource[0].PacksWithMatches.Count);
            }
        }
        public async Task SourcesCorrectlyReturnResults()
        {
            List <MockTemplateSearchProvider> createdProviders = new List <MockTemplateSearchProvider>();
            var sourcesToSetup = GetMockNameSearchResults();

            foreach (var source in sourcesToSetup)
            {
                var provider = new MockTemplateSearchProvider();
                createdProviders.Add(provider);
                provider.Results = source.Value;
                _engineEnvironmentSettings.Components.AddComponent(
                    typeof(ITemplateSearchProviderFactory),
                    new MockTemplateSearchProviderFactory(Guid.NewGuid(), source.Key, provider));
            }

            const string templateName = "foo";

            Func <TemplatePackageSearchData, IReadOnlyList <ITemplateInfo> > filter =
                templatePack => templatePack.Templates
                .Where(t => ((ITemplateInfo)t).Name.Contains(templateName, StringComparison.OrdinalIgnoreCase))
                .ToList();

            var searchCoordinator = new TemplateSearchCoordinator(_engineEnvironmentSettings);
            var searchResult      = await searchCoordinator.SearchAsync(p => true, filter, default).ConfigureAwait(false);

            Assert.Equal(2, searchResult.Count);

            var searchResultDictionary = searchResult.ToDictionary(r => r.Provider.Factory.DisplayName);

            Assert.True(searchResultDictionary.ContainsKey("source one"));
            Assert.True(searchResultDictionary.ContainsKey("source two"));

            Assert.Equal(3, searchResultDictionary["source two"].SearchHits.Count);
            Assert.Equal(2, searchResultDictionary["source one"].SearchHits.Count);

            Assert.True(createdProviders.All(p => p.WasSearched));
        }
Example #18
0
        /// <summary>
        /// Executes searching for the templates in configured remote sources.
        /// Performs validation for the commands, search for the templates in configured remote source, displays the results in table format.
        /// </summary>
        /// <param name="environmentSettings">environment settings.</param>
        /// <param name="templatePackageManager"></param>
        /// <param name="commandArgs">new command data.</param>
        /// <param name="defaultLanguage">default language for the host.</param>
        /// <param name="cancellationToken"></param>
        /// <returns><see cref="NewCommandStatus.Success"/> when the templates were found and displayed;
        /// <see cref="NewCommandStatus.MissingRequiredOption"/> when the command validation fails;
        /// <see cref="NewCommandStatus.NotFound"/> when no templates found based on the filter criteria.
        /// </returns>
        internal static async Task <NewCommandStatus> SearchForTemplateMatchesAsync(
            IEngineEnvironmentSettings environmentSettings,
            TemplatePackageManager templatePackageManager,
            SearchCommandArgs commandArgs,
            string?defaultLanguage,
            CancellationToken cancellationToken)
        {
            if (!ValidateCommandInput(commandArgs))
            {
                return(NewCommandStatus.MissingRequiredOption);
            }

            Reporter.Output.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Info_SearchInProgress);
            IReadOnlyList <IManagedTemplatePackage> templatePackages =
                await templatePackageManager.GetManagedTemplatePackagesAsync(force : false, cancellationToken : cancellationToken).ConfigureAwait(false);

            TemplateSearchCoordinator searchCoordinator    = CliTemplateSearchCoordinatorFactory.CreateCliTemplateSearchCoordinator(environmentSettings);
            CliSearchFiltersFactory   searchFiltersFactory = new CliSearchFiltersFactory(templatePackages);

            IReadOnlyList <SearchResult>?searchResults = await searchCoordinator.SearchAsync(
                searchFiltersFactory.GetPackFilter(commandArgs),
                CliSearchFiltersFactory.GetMatchingTemplatesFilter(commandArgs),
                cancellationToken).ConfigureAwait(false);

            if (!searchResults.Any())
            {
                Reporter.Error.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Error_NoSources.Bold().Red());
                return(NewCommandStatus.NotFound);
            }

            foreach (SearchResult result in searchResults)
            {
                if (!result.Success)
                {
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Info_MatchesFromSource, result.Provider.Factory.DisplayName));
                    Reporter.Error.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Error_SearchFailure, result.ErrorMessage).Red().Bold());
                    continue;
                }

                Reporter.Output.WriteLine(string.Format(LocalizableStrings.CliTemplateSearchCoordinator_Info_MatchesFromSource, result.Provider.Factory.DisplayName));
                if (result.SearchHits.Any())
                {
                    DisplayResultsForPack(result.SearchHits, environmentSettings, commandArgs, defaultLanguage);
                }
                else
                {
                    //TODO: implement it for template options matching
                    //IReadOnlyDictionary<string, string?>? appliedParameterMatches = TemplateCommandInput.GetTemplateParametersFromCommand(commandArgs);
                    // No templates found matching the following input parameter(s): {0}.
                    Reporter.Error.WriteLine(
                        string.Format(
                            LocalizableStrings.NoTemplatesMatchingInputParameters,
                            GetInputParametersString(commandArgs))
                        .Bold().Red());
                }
            }
            Reporter.Output.WriteLine();
            if (searchResults.Where(r => r.Success).SelectMany(r => r.SearchHits).Any())
            {
                string packageIdToShow = EvaluatePackageToShow(searchResults);
                Reporter.Output.WriteLine(LocalizableStrings.CliTemplateSearchCoordinator_Info_InstallHelp);
                Reporter.Output.WriteCommand(
                    Example
                    .For <NewCommand>(commandArgs.ParseResult)
                    .WithSubcommand <InstallCommand>()
                    .WithArgument(InstallCommand.NameArgument));
                Reporter.Output.WriteLine(LocalizableStrings.Generic_ExampleHeader);
                Reporter.Output.WriteCommand(
                    Example
                    .For <NewCommand>(commandArgs.ParseResult)
                    .WithSubcommand <InstallCommand>()
                    .WithArgument(InstallCommand.NameArgument, packageIdToShow));
                return(NewCommandStatus.Success);
            }
            return(NewCommandStatus.NotFound);
        }