Esempio n. 1
0
        public void TestSourceRepoPackageSourcesChanged()
        {
            // Arrange
            var localAppDataPath   = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            var localPackageSource = new Configuration.PackageSource(localAppDataPath);
            var oldPackageSources  = new List <Configuration.PackageSource> {
                localPackageSource
            };
            var packageSourceProvider    = new TestPackageSourceProvider(oldPackageSources);
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(packageSourceProvider);

            // Act
            var oldEffectivePackageSources = sourceRepositoryProvider.GetRepositories().ToList();

            // Assert
            Assert.Equal(1, oldEffectivePackageSources.Count);
            Assert.Equal(localAppDataPath, oldEffectivePackageSources[0].PackageSource.Source);

            // Main Act
            var newPackageSources = new List <Configuration.PackageSource> {
                TestSourceRepositoryUtility.V3PackageSource, localPackageSource
            };

            packageSourceProvider.SavePackageSources(newPackageSources);

            var newEffectivePackageSources = sourceRepositoryProvider.GetRepositories().ToList();

            // Main Assert
            Assert.Equal(2, newEffectivePackageSources.Count);
            Assert.Equal(TestSourceRepositoryUtility.V3PackageSource.Source, newEffectivePackageSources[0].PackageSource.Source);
            Assert.Equal(localAppDataPath, newEffectivePackageSources[1].PackageSource.Source);
        }
Esempio n. 2
0
        public void TestSourceRepoPackageSourcesChanged2()
        {
            // Arrange
            using (var settingsPath = TestPackageSourceSettings.CreateAndGetSettingFilePath())
            {
                var settings = new Configuration.Settings(settingsPath);
                var packageSourceProvider    = new Configuration.PackageSourceProvider(settings);
                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(packageSourceProvider);

                // Act
                var oldEffectivePackageSources = sourceRepositoryProvider.GetRepositories().ToList();

                // Assert
                Assert.Equal(1, oldEffectivePackageSources.Count);
                Assert.Equal(TestSourceRepositoryUtility.V2PackageSource.Source, oldEffectivePackageSources[0].PackageSource.Source);

                // Main Act
                var newPackageSources = new List <Configuration.PackageSource>
                {
                    TestSourceRepositoryUtility.V3PackageSource,
                    TestSourceRepositoryUtility.V2PackageSource
                };
                packageSourceProvider.SavePackageSources(newPackageSources);

                var newEffectivePackageSources = sourceRepositoryProvider.GetRepositories().ToList();

                // Main Assert
                Assert.Equal(2, newEffectivePackageSources.Count);
                Assert.Equal(TestSourceRepositoryUtility.V3PackageSource.Source, newEffectivePackageSources[0].PackageSource.Source);
                Assert.Equal(TestSourceRepositoryUtility.V2PackageSource.Source, newEffectivePackageSources[1].PackageSource.Source);
            }
        }
Esempio n. 3
0
        public async Task GetDownloadResourceResultAsync_MultipleSources_DownloadsPackage()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[]
            {
                new PackageSource("https://www.myget.org/F/aspnetvnext/api/v2/"),
                TestSourceRepositoryUtility.V3PackageSource,
                new PackageSource("http://unit.test"),
            });

            var packageIdentity = new PackageIdentity("jQuery", new NuGetVersion("1.8.2"));

            // Act
            using (var cacheContext = new SourceCacheContext())
                using (var packagesDirectory = TestDirectory.Create())
                    using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(
                               sourceRepositoryProvider.GetRepositories(),
                               packageIdentity,
                               new PackageDownloadContext(cacheContext),
                               packagesDirectory,
                               NullLogger.Instance,
                               CancellationToken.None))
                    {
                        var targetPackageStream = downloadResult.PackageStream;

                        // Assert
                        Assert.True(targetPackageStream.CanSeek);
                    }
        }
        public void TestSourceRepoPackageSourcesChanged2()
        {
            // Arrange
            var settingsPath             = TestPackageSourceSettings.CreateAndGetSettingFilePath();
            var settings                 = new Settings(settingsPath);
            var packageSourceProvider    = new PackageSourceProvider(settings);
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(packageSourceProvider);

            // Act
            var oldEffectivePackageSources = sourceRepositoryProvider.GetRepositories().ToList();

            // Assert
            Assert.Equal(1, oldEffectivePackageSources.Count);
            Assert.Equal(TestSourceRepositoryUtility.V2PackageSource.Source, oldEffectivePackageSources[0].PackageSource.Source);

            // Main Act
            var newPackageSources = new List <PackageSource>()
            {
                TestSourceRepositoryUtility.V3PackageSource,
                TestSourceRepositoryUtility.V2PackageSource
            };

            packageSourceProvider.SavePackageSources(newPackageSources);

            var newEffectivePackageSources = sourceRepositoryProvider.GetRepositories().ToList();

            // Main Assert
            Assert.Equal(2, newEffectivePackageSources.Count);
            Assert.Equal(TestSourceRepositoryUtility.V3PackageSource.Source, newEffectivePackageSources[0].PackageSource.Source);
            Assert.Equal(TestSourceRepositoryUtility.V2PackageSource.Source, newEffectivePackageSources[1].PackageSource.Source);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(settingsPath);
        }
        public async Task TestDownloadPackage_MultipleSources_FoundOnMultiple()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[]
            {
                TestSourceRepositoryUtility.V3PackageSource,
                TestSourceRepositoryUtility.V3PackageSource,
                new PackageSource("http://blah.com"),
                TestSourceRepositoryUtility.V2PackageSource,
                TestSourceRepositoryUtility.V2PackageSource,
            });

            var packageIdentity = new PackageIdentity("jQuery", new NuGetVersion("1.8.2"));

            // Act
            using (var cacheContext = new SourceCacheContext())
                using (var packagesDirectory = TestDirectory.Create())
                    using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(
                               sourceRepositoryProvider.GetRepositories(),
                               packageIdentity,
                               new PackageDownloadContext(cacheContext),
                               packagesDirectory,
                               NullLogger.Instance,
                               CancellationToken.None))
                    {
                        var targetPackageStream = downloadResult.PackageStream;

                        // Assert
                        Assert.True(targetPackageStream.CanSeek);
                    }
        }
Esempio n. 6
0
        public async Task TestDownloadPackage_MultipleSources()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[]
            {
                new Configuration.PackageSource("https://www.myget.org/F/aspnetvnext/api/v2/"),
                TestSourceRepositoryUtility.V3PackageSource,
                new Configuration.PackageSource("http://blah.com"),
            });

            var packageIdentity = new PackageIdentity("jQuery", new NuGetVersion("1.8.2"));

            // Act
            using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(sourceRepositoryProvider.GetRepositories(),
                                                                                               packageIdentity,
                                                                                               Configuration.NullSettings.Instance,
                                                                                               Common.NullLogger.Instance,
                                                                                               CancellationToken.None))
            {
                var targetPackageStream = downloadResult.PackageStream;

                // Assert
                Assert.True(targetPackageStream.CanSeek);
            }
        }
Esempio n. 7
0
        public async Task MultipleSources_Works()
        {
            var solutionManager = Mock.Of <INuGetSolutionManagerService>();
            var uiContext       = new Mock <INuGetUIContext>();

            uiContext.Setup(x => x.SolutionManagerService)
            .Returns(solutionManager);

            uiContext.Setup(x => x.ServiceBroker)
            .Returns(Mock.Of <IServiceBroker>());

            var source1 = new PackageSource("https://pkgs.dev.azure.com/dnceng/public/_packaging/nuget-build/nuget/v3/index.json", "NuGetBuild");
            var source2 = new PackageSource("https://api.nuget.org/v3/index.json", "NuGet.org");

            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { source1, source2 });
            var repositories             = sourceRepositoryProvider.GetRepositories();

            var context = new PackageLoadContext(repositories, isSolution: false, uiContext.Object);

            var packageFeed = new MultiSourcePackageFeed(repositories, logger: null, telemetryService: null);
            var loader      = new PackageItemLoader(context, packageFeed, "nuget");

            var loaded = new List <PackageItemListViewModel>();

            foreach (var page in Enumerable.Range(0, 5))
            {
                await loader.LoadNextAsync(null, CancellationToken.None);

                while (loader.State.LoadingStatus == LoadingStatus.Loading)
                {
                    await Task.Delay(TimeSpan.FromSeconds(1));

                    await loader.UpdateStateAsync(progress : null, CancellationToken.None);
                }

                var items = loader.GetCurrent();
                loaded.AddRange(items);

                if (loader.State.LoadingStatus != LoadingStatus.Ready)
                {
                    break;
                }
            }

            // All items should not have a prefix reserved because the feed is multisource
            foreach (var item in loaded)
            {
                Assert.False(item.PrefixReserved);
            }

            Assert.NotEmpty(loaded);
        }
        public async Task InstallingPackageShouldCreateLockFile_CustomLockFileName()
        {
            // Arrange
            using (var packageSource = TestDirectory.Create())
                using (var testSolutionManager = new TestSolutionManager())
                {
                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(
                        new List <PackageSource>()
                    {
                        new PackageSource(packageSource.Path)
                    });

                    var testSettings           = NullSettings.Instance;
                    var token                  = CancellationToken.None;
                    var deleteOnRestartManager = new TestDeleteOnRestartManager();
                    var nuGetPackageManager    = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManager);
                    var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

                    var packageContext = new SimpleTestPackageContext("packageA");
                    packageContext.AddFile("lib/net45/a.dll");
                    SimpleTestPackageUtility.CreateOPCPackage(packageContext, packageSource);

                    var msBuildNuGetProject       = testSolutionManager.AddNewMSBuildProject();
                    var msBuildNuGetProjectSystem = msBuildNuGetProject.ProjectSystem as TestMSBuildNuGetProjectSystem;
                    msBuildNuGetProjectSystem.SetPropertyValue("RestorePackagesWithLockFile", "true");
                    msBuildNuGetProjectSystem.SetPropertyValue("NuGetLockFilePath", "my.lock.json");
                    var packagesConfigPath = msBuildNuGetProject.PackagesConfigNuGetProject.FullPath;
                    var packagesLockPath   = packagesConfigPath.Replace("packages.config", "my.lock.json");
                    var packageIdentity    = packageContext.Identity;

                    // Pre-Assert
                    // Check that the packages.lock.json file does not exist
                    Assert.False(File.Exists(packagesLockPath));

                    // Act
                    await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                                                                  new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                    // Assert
                    // Check that the packages.lock.json file exists after the installation
                    Assert.True(File.Exists(packagesLockPath));
                    Assert.True(msBuildNuGetProjectSystem.FileExistsInProject("my.lock.json"));
                    // Check the number of target frameworks and dependencies in the lock file
                    var lockFile = PackagesLockFileFormat.Read(packagesLockPath);
                    Assert.Equal(1, lockFile.Targets.Count);
                    Assert.Equal(1, lockFile.Targets[0].Dependencies.Count);
                }
        }
        public async Task MultipleSources_Works()
        {
            var solutionManager = Mock.Of <IVsSolutionManager>();
            var uiContext       = Mock.Of <INuGetUIContext>();

            Mock.Get(uiContext)
            .Setup(x => x.SolutionManager)
            .Returns(solutionManager);

            var source1 = new Configuration.PackageSource("https://dotnet.myget.org/F/nuget-volatile/api/v3/index.json", "NuGetVolatile");
            var source2 = new Configuration.PackageSource("https://api.nuget.org/v3/index.json", "NuGet.org");

            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { source1, source2 });
            var repositories             = sourceRepositoryProvider.GetRepositories();

            var context = new PackageLoadContext(repositories, false, uiContext);

            var packageFeed = new MultiSourcePackageFeed(repositories, logger: null);
            var loader      = new PackageItemLoader(context, packageFeed, "nuget");

            var loaded = new List <PackageItemListViewModel>();

            foreach (var page in Enumerable.Range(0, 5))
            {
                await loader.LoadNextAsync(null, CancellationToken.None);

                while (loader.State.LoadingStatus == LoadingStatus.Loading)
                {
                    await Task.Delay(TimeSpan.FromSeconds(1));

                    await loader.UpdateStateAsync(null, CancellationToken.None);
                }

                var items = loader.GetCurrent();
                loaded.AddRange(items);

                if (loader.State.LoadingStatus != LoadingStatus.Ready)
                {
                    break;
                }
            }

            // All items should not have a prefix reserved because the feed is multisource
            foreach (var item in loaded)
            {
                Assert.False(item.PrefixReserved);
            }

            Assert.NotEmpty(loaded);
        }
Esempio n. 10
0
        public async Task DoNotCreateLockFileWhenFeatureDisabled()
        {
            // Arrange
            using (var packageSource = TestDirectory.Create())
                using (var testSolutionManager = new TestSolutionManager())
                {
                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(
                        new List <PackageSource>()
                    {
                        new PackageSource(packageSource.Path)
                    });

                    var testSettings           = NullSettings.Instance;
                    var token                  = CancellationToken.None;
                    var deleteOnRestartManager = new TestDeleteOnRestartManager();
                    var nuGetPackageManager    = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManager);
                    var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

                    var packageContext = new SimpleTestPackageContext("packageA");
                    packageContext.AddFile("lib/net45/a.dll");
                    SimpleTestPackageUtility.CreateOPCPackage(packageContext, packageSource);

                    var msBuildNuGetProject       = testSolutionManager.AddNewMSBuildProject();
                    var msBuildNuGetProjectSystem = msBuildNuGetProject.ProjectSystem as TestMSBuildNuGetProjectSystem;
                    msBuildNuGetProjectSystem.SetPropertyValue("RestorePackagesWithLockFile", "false");
                    var packagesConfigPath = msBuildNuGetProject.PackagesConfigNuGetProject.FullPath;
                    var packagesLockPath   = packagesConfigPath.Replace("packages.config", "packages.lock.json");
                    var packageIdentity    = packageContext.Identity;

                    // Pre-Assert
                    // Check that the packages.lock.json file does not exist
                    Assert.False(File.Exists(packagesLockPath));

                    // Act
                    await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                                                                  new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                    // Assert
                    // Check that the packages.lock.json still does not exist after the installation
                    Assert.False(File.Exists(packagesLockPath));
                }
        }
Esempio n. 11
0
        public async Task TestDownloadPackage_MultipleSources_NotFound()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[]
            {
                new Configuration.PackageSource("https://www.myget.org/F/aspnetvnext/api/v2/"),
                new Configuration.PackageSource("http://blah.com"),
            });

            var packageIdentity = new PackageIdentity("jQuery", new NuGetVersion("1.8.2"));

            await Assert.ThrowsAsync <FatalProtocolException>(async() => await PackageDownloader.GetDownloadResourceResultAsync(sourceRepositoryProvider.GetRepositories(),
                                                                                                                                packageIdentity,
                                                                                                                                Configuration.NullSettings.Instance,
                                                                                                                                Common.NullLogger.Instance,
                                                                                                                                CancellationToken.None));
        }
Esempio n. 12
0
        public async Task GetTotalCountAsync_Works()
        {
            var uiContext = Mock.Of <INuGetUIContext>();

            var source1 = new Configuration.PackageSource("https://dotnet.myget.org/F/nuget-volatile/api/v3/index.json", "NuGetVolatile");
            var source2 = new Configuration.PackageSource("https://api.nuget.org/v3/index.json", "NuGet.org");

            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { source1, source2 });
            var repositories             = sourceRepositoryProvider.GetRepositories();

            var context     = new PackageLoadContext(repositories, false, uiContext);
            var packageFeed = new MultiSourcePackageFeed(repositories, logger: null);
            var loader      = new PackageItemLoader(context, packageFeed, "nuget");

            var totalCount = await loader.GetTotalCountAsync(100, CancellationToken.None);

            Assert.NotInRange(totalCount, 0, 99);
        }
        public async Task GetDownloadResourceResultAsync_MultipleSources_PackageDownloadedWhenFoundInMultipleSources()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[]
            {
                TestSourceRepositoryUtility.V3PackageSource,
                TestSourceRepositoryUtility.V3PackageSource,
                new PackageSource("http://unit.test"),
                TestSourceRepositoryUtility.V2PackageSource,
                TestSourceRepositoryUtility.V2PackageSource,
            });

            var packageIdentity = new PackageIdentity("jQuery", new NuGetVersion("1.8.2"));

            // Act
            using (var cacheContext = new SourceCacheContext())
            {
                var downloadContext = new PackageDownloadContext(cacheContext)
                {
                    ExtractionContext = new PackageExtractionContext(
                        PackageSaveMode.Defaultv3,
                        PackageExtractionBehavior.XmlDocFileSaveMode,
                        NullLogger.Instance,
                        signedPackageVerifier: null,
                        signedPackageVerifierSettings: null)
                };

                using (var packagesDirectory = TestDirectory.Create())
                    using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(
                               sourceRepositoryProvider.GetRepositories(),
                               packageIdentity,
                               downloadContext,
                               packagesDirectory,
                               NullLogger.Instance,
                               CancellationToken.None))
                    {
                        var targetPackageStream = downloadResult.PackageStream;

                        // Assert
                        Assert.True(targetPackageStream.CanSeek);
                    }
            }
        }
Esempio n. 14
0
        public async Task PackageReader_NotNull()
        {
            // Prepare
            var solutionManager = Mock.Of <INuGetSolutionManagerService>();
            var uiContext       = new Mock <INuGetUIContext>();

            uiContext.Setup(x => x.SolutionManagerService)
            .Returns(solutionManager);

            uiContext.Setup(x => x.ServiceBroker)
            .Returns(Mock.Of <IServiceBroker>());

            using (var localFeedDir = TestDirectory.Create()) // local feed
            {
                // create test package
                var pkgId = new PackageIdentity("nuget.lpsm.test", new NuGetVersion(0, 0, 1));
                var pkg   = new SimpleTestPackageContext(pkgId.Id, pkgId.Version.ToNormalizedString());
                await SimpleTestPackageUtility.CreatePackagesAsync(localFeedDir.Path, pkg);

                // local test source
                var localUri    = new Uri(localFeedDir.Path, UriKind.Absolute);
                var localSource = new PackageSource(localUri.ToString(), "LocalSource");

                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { localSource });
                var repositories             = sourceRepositoryProvider.GetRepositories();

                var context = new PackageLoadContext(repositories, isSolution: false, uiContext.Object);

                var packageFeed = new MultiSourcePackageFeed(repositories, logger: null, telemetryService: null);
                var loader      = new PackageItemLoader(context, packageFeed, "nuget");

                // Act
                await loader.LoadNextAsync(progress : null, CancellationToken.None);

                var results = loader.GetCurrent();

                // Assert
                Assert.Single(results);
                Assert.NotNull(results.First().PackageReader);
            }
        }
Esempio n. 15
0
        private void Initialize(IReadOnlyList <PackageSource> packageSources = null)
        {
            SourceRepositoryProvider sourceRepositoryProvider;

            if (packageSources == null || packageSources.Count == 0)
            {
                sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            }
            else
            {
                sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(packageSources);
            }

            _solutionManager = new TestVsSolutionManager();
            _testDirectory   = TestDirectory.Create();
            ISettings testSettings           = CreateSettings(sourceRepositoryProvider, _testDirectory);
            var       deleteOnRestartManager = new TestDeleteOnRestartManager();

            _packageManager = new NuGetPackageManager(
                sourceRepositoryProvider,
                testSettings,
                _solutionManager,
                deleteOnRestartManager);
            _state       = new NuGetProjectManagerServiceState();
            _sharedState = new TestSharedServiceState(
                new Microsoft.VisualStudio.Threading.AsyncLazy <NuGetPackageManager>(
                    () => Task.FromResult(_packageManager)),
                new Microsoft.VisualStudio.Threading.AsyncLazy <IVsSolutionManager>(
                    () => Task.FromResult <IVsSolutionManager>(_solutionManager)),
                sourceRepositoryProvider,
                new Microsoft.VisualStudio.Threading.AsyncLazy <IReadOnlyCollection <SourceRepository> >(
                    () => Task.FromResult <IReadOnlyCollection <SourceRepository> >(sourceRepositoryProvider.GetRepositories().ToList())));
            _projectManager = new NuGetProjectManagerService(
                default(ServiceActivationOptions),
                Mock.Of <IServiceBroker>(),
                new AuthorizationServiceClient(Mock.Of <IAuthorizationService>()),
                _state,
                _sharedState);
        }
        public async Task GetDownloadResourceResultAsync_MultipleSources_PackageNotFound()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[]
            {
                new PackageSource("https://www.myget.org/F/aspnetvnext/api/v2/"),
                new PackageSource("http://unit.test"),
            });

            var packageIdentity = new PackageIdentity("jQuery", new NuGetVersion("1.8.2"));

            using (var packagesDirectory = TestDirectory.Create())
                using (var cacheContext = new SourceCacheContext())
                {
                    await Assert.ThrowsAsync <FatalProtocolException>(
                        async() => await PackageDownloader.GetDownloadResourceResultAsync(
                            sourceRepositoryProvider.GetRepositories(),
                            packageIdentity,
                            new PackageDownloadContext(cacheContext),
                            packagesDirectory,
                            NullLogger.Instance,
                            CancellationToken.None));
                }
        }
Esempio n. 17
0
        public async Task GetTotalCountAsync_Works()
        {
            var solutionManager = Mock.Of <INuGetSolutionManagerService>();
            var uiContext       = Mock.Of <INuGetUIContext>();

            Mock.Get(uiContext)
            .Setup(x => x.SolutionManagerService)
            .Returns(solutionManager);

            var source1 = new PackageSource("https://pkgs.dev.azure.com/dnceng/public/_packaging/nuget-build/nuget/v3/index.json", "NuGetBuild");
            var source2 = new PackageSource("https://api.nuget.org/v3/index.json", "NuGet.org");

            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { source1, source2 });
            var repositories             = sourceRepositoryProvider.GetRepositories();

            var context = new PackageLoadContext(repositories, false, uiContext);

            var packageFeed = new MultiSourcePackageFeed(repositories, logger: null, telemetryService: null);
            var loader      = new PackageItemLoader(context, packageFeed, "nuget");

            var totalCount = await loader.GetTotalCountAsync(100, CancellationToken.None);

            Assert.NotInRange(totalCount, 0, 99);
        }
Esempio n. 18
0
        public async Task PackageReader_NotNull()
        {
            // Prepare
            var solutionManager = Mock.Of <INuGetSolutionManagerService>();
            var uiContext       = new Mock <INuGetUIContext>();

            uiContext.Setup(x => x.SolutionManagerService)
            .Returns(solutionManager);
            var searchService = new Mock <INuGetSearchService>(MockBehavior.Strict);

            var packageSearchMetadata = new PackageSearchMetadataBuilder.ClonedPackageSearchMetadata()
            {
                Identity       = new PackageIdentity("NuGet.org", new NuGetVersion("1.0")),
                PrefixReserved = true
            };

            var packageSearchMetadataContextInfo = new List <PackageSearchMetadataContextInfo>()
            {
                PackageSearchMetadataContextInfo.Create(packageSearchMetadata)
            };

            var searchResult = new SearchResultContextInfo(packageSearchMetadataContextInfo, new Dictionary <string, LoadingStatus> {
                { "Search", LoadingStatus.Loading }
            }, false);

            searchService.Setup(x =>
                                x.SearchAsync(
                                    It.IsAny <IReadOnlyCollection <IProjectContextInfo> >(),
                                    It.IsAny <IReadOnlyCollection <PackageSourceContextInfo> >(),
                                    It.IsAny <IReadOnlyCollection <string> >(),
                                    It.IsAny <string>(),
                                    It.IsAny <SearchFilter>(),
                                    It.IsAny <NuGet.VisualStudio.Internal.Contracts.ItemFilter>(),
                                    It.IsAny <bool>(),
                                    It.IsAny <CancellationToken>()))
            .Returns(new ValueTask <SearchResultContextInfo>(searchResult));

            uiContext.Setup(x => x.ServiceBroker)
            .Returns(Mock.Of <IServiceBroker>());

            using (var localFeedDir = TestDirectory.Create()) // local feed
            {
                // create test package
                var pkgId = new PackageIdentity("nuget.lpsm.test", new NuGetVersion(0, 0, 1));
                var pkg   = new SimpleTestPackageContext(pkgId.Id, pkgId.Version.ToNormalizedString());
                await SimpleTestPackageUtility.CreatePackagesAsync(localFeedDir.Path, pkg);

                // local test source
                var localUri    = new Uri(localFeedDir.Path, UriKind.Absolute);
                var localSource = new PackageSource(localUri.ToString(), "LocalSource");

                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { localSource });
                var repositories             = sourceRepositoryProvider.GetRepositories();

                var context = new PackageLoadContext(isSolution: false, uiContext.Object);

                var packageFeed = new MultiSourcePackageFeed(repositories, logger: null, telemetryService: null);
                var loader      = await PackageItemLoader.CreateAsync(
                    Mock.Of <IServiceBroker>(),
                    context,
                    new List <PackageSourceContextInfo> {
                    PackageSourceContextInfo.Create(localSource)
                },
                    NuGet.VisualStudio.Internal.Contracts.ItemFilter.All,
                    searchService.Object,
                    TestSearchTerm);

                // Act
                await loader.LoadNextAsync(progress : null, CancellationToken.None);

                var results = loader.GetCurrent();

                // Assert
                Assert.Single(results);
                Assert.NotNull(results.First().PackageReader);
            }
        }
        public async Task EmitsSearchTelemetryEvents()
        {
            // Arrange
            var solutionManager = Mock.Of <IVsSolutionManager>();
            var uiContext       = Mock.Of <INuGetUIContext>();

            Mock.Get(uiContext)
            .Setup(x => x.SolutionManager)
            .Returns(solutionManager);

            var telemetryService = new Mock <INuGetTelemetryService>();
            var eventsQueue      = new ConcurrentQueue <TelemetryEvent>();

            telemetryService
            .Setup(x => x.EmitTelemetryEvent(It.IsAny <TelemetryEvent>()))
            .Callback <TelemetryEvent>(e => eventsQueue.Enqueue(e));

            var source = new Configuration.PackageSource("https://api.nuget.org/v3/index.json", "NuGet.org");

            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { source });
            var repositories             = sourceRepositoryProvider.GetRepositories();

            var context = new PackageLoadContext(repositories, false, uiContext);

            var packageFeed = new MultiSourcePackageFeed(repositories, logger: null, telemetryService: telemetryService.Object);

            // Act
            var loader = new PackageItemLoader(context, packageFeed, searchText: "nuget", includePrerelease: true);
            await loader.LoadNextAsync(null, CancellationToken.None);

            await loader.LoadNextAsync(null, CancellationToken.None);

            // Assert
            var events = eventsQueue.ToArray();

            Assert.Equal(4, events.Length);

            var search = events[0];

            Assert.Equal("Search", search.Name);
            Assert.Equal(true, search["IncludePrerelease"]);
            Assert.Equal("nuget", search.GetPiiData().First(p => p.Key == "Query").Value);
            var operationId       = Assert.IsType <string>(search["OperationId"]);
            var parsedOperationId = Guid.ParseExact(operationId, "D");

            var sources = events[1];

            Assert.Equal("SearchPackageSourceSummary", sources.Name);
            Assert.Equal(1, sources["NumHTTPv3Feeds"]);
            Assert.Equal("YesV3", sources["NuGetOrg"]);
            Assert.Equal(operationId, sources["ParentId"]);

            var page0 = events[2];

            Assert.Equal("SearchPage", page0.Name);
            Assert.Equal("Ready", page0["LoadingStatus"]);
            Assert.Equal(0, page0["PageIndex"]);
            Assert.Equal(operationId, page0["ParentId"]);
            Assert.IsType <int>(page0["ResultCount"]);
            Assert.IsType <double>(page0["Duration"]);
            Assert.IsType <double>(page0["ResultsAggregationDuration"]);
            Assert.IsType <string>(page0["IndividualSourceDurations"]);
            Assert.Equal(1, ((JArray)JsonConvert.DeserializeObject((string)page0["IndividualSourceDurations"])).Values <double>().Count());

            var page1 = events[3];

            Assert.Equal("SearchPage", page1.Name);
            Assert.Equal("Ready", page1["LoadingStatus"]);
            Assert.Equal(1, page1["PageIndex"]);
            Assert.Equal(operationId, page1["ParentId"]);
            Assert.IsType <int>(page1["ResultCount"]);
            Assert.IsType <double>(page1["Duration"]);
            Assert.IsType <double>(page1["ResultsAggregationDuration"]);
            Assert.IsType <string>(page1["IndividualSourceDurations"]);
            Assert.Equal(1, ((JArray)JsonConvert.DeserializeObject((string)page1["IndividualSourceDurations"])).Values <double>().Count());

            Assert.Equal(parsedOperationId, loader.State.OperationId);
        }
Esempio n. 20
0
        public async Task EmitsSearchTelemetryEvents()
        {
            // Arrange
            var solutionManager = Mock.Of <IVsSolutionManager>();
            var uiContext       = Mock.Of <INuGetUIContext>();

            Mock.Get(uiContext)
            .Setup(x => x.SolutionManager)
            .Returns(solutionManager);

            var telemetryService = new Mock <INuGetTelemetryService>();
            var eventsQueue      = new ConcurrentQueue <TelemetryEvent>();

            telemetryService
            .Setup(x => x.EmitTelemetryEvent(It.IsAny <TelemetryEvent>()))
            .Callback <TelemetryEvent>(e => eventsQueue.Enqueue(e));

            // Mock all the remote calls our test will try to make.
            var source = NuGetConstants.V3FeedUrl;
            var query  = "https://api-v2v3search-0.nuget.org/query";

            var responses = new Dictionary <string, string>
            {
                {
                    source,
                    ProtocolUtility.GetResource("NuGet.PackageManagement.UI.Test.compiler.resources.index.json", typeof(PackageItemLoaderTests))
                },
                {
                    query + "?q=nuget&skip=0&take=26&prerelease=true&semVerLevel=2.0.0",
                    ProtocolUtility.GetResource("NuGet.PackageManagement.UI.Test.compiler.resources.nugetSearchPage1.json", typeof(PackageItemLoaderTests))
                },
                {
                    query + "?q=nuget&skip=25&take=26&prerelease=true&semVerLevel=2.0.0",
                    ProtocolUtility.GetResource("NuGet.PackageManagement.UI.Test.compiler.resources.nugetSearchPage2.json", typeof(PackageItemLoaderTests))
                },
            };

            using (var httpSource = new TestHttpSource(new PackageSource(source), responses))
            {
                var injectedHttpSources = new Dictionary <string, HttpSource>();
                injectedHttpSources.Add(source, httpSource);
                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { new PackageSource(source) }, new Lazy <INuGetResourceProvider>[] { new Lazy <INuGetResourceProvider>(() => new TestHttpSourceResourceProvider(injectedHttpSources)) });
                var repositories             = sourceRepositoryProvider.GetRepositories();

                var context = new PackageLoadContext(repositories, false, uiContext);

                var packageFeed = new MultiSourcePackageFeed(repositories, logger: null, telemetryService: telemetryService.Object);

                // Act
                var loader = new PackageItemLoader(context, packageFeed, searchText: "nuget", includePrerelease: true);
                await loader.LoadNextAsync(null, CancellationToken.None);

                await loader.LoadNextAsync(null, CancellationToken.None);

                // Assert
                var events = eventsQueue.ToArray();
                Assert.True(4 == events.Length, string.Join(Environment.NewLine, events.Select(e => e.Name)));

                var search = Assert.Single(events, e => e.Name == "Search");
                Assert.Equal(true, search["IncludePrerelease"]);
                Assert.Equal("nuget", search.GetPiiData().First(p => p.Key == "Query").Value);
                var operationId       = Assert.IsType <string>(search["OperationId"]);
                var parsedOperationId = Guid.ParseExact(operationId, "D");

                var sources = Assert.Single(events, e => e.Name == "SearchPackageSourceSummary");
                Assert.Equal(1, sources["NumHTTPv3Feeds"]);
                Assert.Equal("YesV3", sources["NuGetOrg"]);
                Assert.Equal(operationId, sources["ParentId"]);

                var page0 = Assert.Single(events, e => e.Name == "SearchPage" && e["PageIndex"] is int && (int)e["PageIndex"] == 0);
                Assert.Equal("Ready", page0["LoadingStatus"]);
                Assert.Equal(operationId, page0["ParentId"]);
                Assert.IsType <int>(page0["ResultCount"]);
                Assert.IsType <double>(page0["Duration"]);
                Assert.IsType <double>(page0["ResultsAggregationDuration"]);
                Assert.IsType <string>(page0["IndividualSourceDurations"]);
                Assert.Equal(1, ((JArray)JsonConvert.DeserializeObject((string)page0["IndividualSourceDurations"])).Values <double>().Count());

                var page1 = Assert.Single(events, e => e.Name == "SearchPage" && e["PageIndex"] is int && (int)e["PageIndex"] == 1);
                Assert.Equal("Ready", page1["LoadingStatus"]);
                Assert.Equal(operationId, page1["ParentId"]);
                Assert.IsType <int>(page1["ResultCount"]);
                Assert.IsType <double>(page1["Duration"]);
                Assert.IsType <double>(page1["ResultsAggregationDuration"]);
                Assert.IsType <string>(page1["IndividualSourceDurations"]);
                Assert.Equal(1, ((JArray)JsonConvert.DeserializeObject((string)page1["IndividualSourceDurations"])).Values <double>().Count());

                Assert.Equal(parsedOperationId, loader.State.OperationId);
            }
        }
        public async void DependencyGraphRestoreUtility_LegacyPackageRef_Restore_LockedMode()
        {
            using (var packageSource = TestDirectory.Create())
            {
                // Arrange
                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(
                    new List <Configuration.PackageSource>()
                {
                    new Configuration.PackageSource(packageSource.Path)
                });

                using (var testSolutionManager = new TestSolutionManager(true))
                    using (var randomProjectFolderPath = TestDirectory.Create())
                    {
                        var testSettings            = PopulateSettingsWithSources(sourceRepositoryProvider, randomProjectFolderPath);
                        var testNuGetProjectContext = new TestNuGetProjectContext();
                        var deleteOnRestartManager  = new TestDeleteOnRestartManager();
                        var nuGetPackageManager     = new NuGetPackageManager(
                            sourceRepositoryProvider,
                            testSettings,
                            testSolutionManager,
                            deleteOnRestartManager);

                        var projectTargetFrameworkStr = "net45";
                        var fullProjectPath           = Path.Combine(randomProjectFolderPath, "project1.csproj");

                        var projectNames = new ProjectNames(
                            fullName: fullProjectPath,
                            uniqueName: Path.GetFileName(fullProjectPath),
                            shortName: Path.GetFileNameWithoutExtension(fullProjectPath),
                            customUniqueName: Path.GetFileName(fullProjectPath));
                        var vsProjectAdapter = new TestVSProjectAdapter(
                            fullProjectPath,
                            projectNames,
                            projectTargetFrameworkStr,
                            restorePackagesWithLockFile: "true",
                            restoreLockedMode: true);

                        var projectServices = new TestProjectSystemServices();
                        projectServices.SetupInstalledPackages(
                            NuGetFramework.Parse(projectTargetFrameworkStr),
                            new LibraryDependency
                        {
                            LibraryRange = new LibraryRange(
                                "packageA",
                                VersionRange.Parse("1.*"),
                                LibraryDependencyTarget.Package)
                        });

                        var legacyPRProject = new LegacyPackageReferenceProject(
                            vsProjectAdapter,
                            Guid.NewGuid().ToString(),
                            projectServices,
                            _threadingService);
                        testSolutionManager.NuGetProjects.Add(legacyPRProject);

                        var testLogger     = new TestLogger();
                        var restoreContext = new DependencyGraphCacheContext(testLogger, testSettings);

                        var packageContextA = new SimpleTestPackageContext("packageA", "1.0.0");
                        packageContextA.AddFile("lib/net45/a.dll");
                        SimpleTestPackageUtility.CreateOPCPackage(packageContextA, packageSource);
                        var packageContextB = new SimpleTestPackageContext("packageB", "1.0.0");
                        packageContextB.AddFile("lib/net45/b.dll");
                        SimpleTestPackageUtility.CreateOPCPackage(packageContextB, packageSource);

                        var dgSpec = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(testSolutionManager, restoreContext);

                        var restoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync(
                            testSolutionManager,
                            dgSpec,
                            restoreContext,
                            new RestoreCommandProvidersCache(),
                            (c) => { },
                            sourceRepositoryProvider.GetRepositories(),
                            Guid.Empty,
                            false,
                            true,
                            testLogger,
                            CancellationToken.None);

                        foreach (var restoreSummary in restoreSummaries)
                        {
                            Assert.True(restoreSummary.Success);
                            Assert.False(restoreSummary.NoOpRestore);
                        }

                        Assert.True(File.Exists(Path.Combine(randomProjectFolderPath, "packages.lock.json")));

                        // install a new package
                        projectServices.SetupInstalledPackages(
                            NuGetFramework.Parse(projectTargetFrameworkStr),
                            new LibraryDependency
                        {
                            LibraryRange = new LibraryRange(
                                "packageA",
                                VersionRange.Parse("1.*"),
                                LibraryDependencyTarget.Package)
                        },
                            new LibraryDependency
                        {
                            LibraryRange = new LibraryRange(
                                "packageB",
                                VersionRange.Parse("1.0.0"),
                                LibraryDependencyTarget.Package)
                        });

                        // update the proeject with new ProjectService instance
                        restoreContext.PackageSpecCache.Clear();
                        dgSpec = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(testSolutionManager, restoreContext);

                        // Act
                        restoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync(
                            testSolutionManager,
                            dgSpec,
                            restoreContext,
                            new RestoreCommandProvidersCache(),
                            (c) => { },
                            sourceRepositoryProvider.GetRepositories(),
                            Guid.Empty,
                            false,
                            true,
                            testLogger,
                            CancellationToken.None);

                        // Assert
                        foreach (var restoreSummary in restoreSummaries)
                        {
                            Assert.False(restoreSummary.Success);
                        }
                    }
            }
        }
        public async void DependencyGraphRestoreUtility_LegacyPackageRef_Restore_GenerateLockFile()
        {
            using (var packageSource = TestDirectory.Create())
            {
                // Arrange
                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(
                    new List <Configuration.PackageSource>()
                {
                    new Configuration.PackageSource(packageSource.Path)
                });

                using (var testSolutionManager = new TestSolutionManager(true))
                    using (var randomProjectFolderPath = TestDirectory.Create())
                    {
                        var testSettings            = PopulateSettingsWithSources(sourceRepositoryProvider, randomProjectFolderPath);
                        var testNuGetProjectContext = new TestNuGetProjectContext();
                        var deleteOnRestartManager  = new TestDeleteOnRestartManager();
                        var nuGetPackageManager     = new NuGetPackageManager(
                            sourceRepositoryProvider,
                            testSettings,
                            testSolutionManager,
                            deleteOnRestartManager);

                        // set up projects
                        var projectTargetFrameworkStr = "net45";
                        var fullProjectPathB          = Path.Combine(randomProjectFolderPath, "ProjectB", "project2.csproj");
                        var projectNamesB             = new ProjectNames(
                            fullName: fullProjectPathB,
                            uniqueName: Path.GetFileName(fullProjectPathB),
                            shortName: Path.GetFileNameWithoutExtension(fullProjectPathB),
                            customUniqueName: Path.GetFileName(fullProjectPathB));
                        var vsProjectAdapterB = new TestVSProjectAdapter(
                            fullProjectPathB,
                            projectNamesB,
                            projectTargetFrameworkStr);

                        var projectServicesB = new TestProjectSystemServices();
                        projectServicesB.SetupInstalledPackages(
                            NuGetFramework.Parse(projectTargetFrameworkStr),
                            new LibraryDependency
                        {
                            LibraryRange = new LibraryRange(
                                "packageB",
                                VersionRange.Parse("1.*"),
                                LibraryDependencyTarget.Package)
                        });

                        var legacyPRProjectB = new LegacyPackageReferenceProject(
                            vsProjectAdapterB,
                            Guid.NewGuid().ToString(),
                            projectServicesB,
                            _threadingService);

                        var projectPathA     = Path.Combine(randomProjectFolderPath, "ProjectA");
                        var fullProjectPathA = Path.Combine(projectPathA, "project1.csproj");
                        var projectNamesA    = new ProjectNames(
                            fullName: fullProjectPathA,
                            uniqueName: Path.GetFileName(fullProjectPathA),
                            shortName: Path.GetFileNameWithoutExtension(fullProjectPathA),
                            customUniqueName: Path.GetFileName(fullProjectPathA));
                        var vsProjectAdapterA = new TestVSProjectAdapter(
                            fullProjectPathA,
                            projectNamesA,
                            projectTargetFrameworkStr,
                            restorePackagesWithLockFile: "true");

                        var projectServicesA = new TestProjectSystemServices();
                        projectServicesA.SetupInstalledPackages(
                            NuGetFramework.Parse(projectTargetFrameworkStr),
                            new LibraryDependency
                        {
                            LibraryRange = new LibraryRange(
                                "packageA",
                                VersionRange.Parse("1.*"),
                                LibraryDependencyTarget.Package)
                        });
                        projectServicesA.SetupProjectDependencies(
                            new ProjectRestoreReference
                        {
                            ProjectUniqueName = fullProjectPathB,
                            ProjectPath       = fullProjectPathB
                        });

                        var legacyPRProjectA = new LegacyPackageReferenceProject(
                            vsProjectAdapterA,
                            Guid.NewGuid().ToString(),
                            projectServicesA,
                            _threadingService);
                        testSolutionManager.NuGetProjects.Add(legacyPRProjectB);
                        testSolutionManager.NuGetProjects.Add(legacyPRProjectA);

                        var testLogger     = new TestLogger();
                        var restoreContext = new DependencyGraphCacheContext(testLogger, testSettings);
                        var providersCache = new RestoreCommandProvidersCache();

                        var packageContextA = new SimpleTestPackageContext("packageA", "1.0.0");
                        packageContextA.AddFile("lib/net45/a.dll");
                        var packageContextB = new SimpleTestPackageContext("packageB", "1.0.0");
                        packageContextB.AddFile("lib/net45/b.dll");
                        var packages = new List <SimpleTestPackageContext>()
                        {
                            packageContextA, packageContextB
                        };
                        SimpleTestPackageUtility.CreateOPCPackages(packages, packageSource);

                        var dgSpec = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(testSolutionManager, restoreContext);

                        // Act
                        var restoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync(
                            testSolutionManager,
                            dgSpec,
                            restoreContext,
                            providersCache,
                            (c) => { },
                            sourceRepositoryProvider.GetRepositories(),
                            Guid.Empty,
                            false,
                            true,
                            testLogger,
                            CancellationToken.None);

                        // Assert
                        foreach (var restoreSummary in restoreSummaries)
                        {
                            Assert.True(restoreSummary.Success);
                            Assert.False(restoreSummary.NoOpRestore);
                        }

                        Assert.True(File.Exists(Path.Combine(projectPathA, "packages.lock.json")));
                        var lockFile = PackagesLockFileFormat.Read(Path.Combine(projectPathA, "packages.lock.json"));
                        Assert.Equal(1, lockFile.Targets.Count);

                        Assert.Equal(".NETFramework,Version=v4.5", lockFile.Targets[0].Name);
                        Assert.Equal(3, lockFile.Targets[0].Dependencies.Count);
                        Assert.Equal("packageA", lockFile.Targets[0].Dependencies[0].Id);
                        Assert.Equal(PackageDependencyType.Direct, lockFile.Targets[0].Dependencies[0].Type);
                        Assert.Equal("packageB", lockFile.Targets[0].Dependencies[1].Id);
                        Assert.Equal(PackageDependencyType.Transitive, lockFile.Targets[0].Dependencies[1].Type);
                        Assert.Equal("project2", lockFile.Targets[0].Dependencies[2].Id);
                        Assert.Equal(PackageDependencyType.Project, lockFile.Targets[0].Dependencies[2].Type);
                    }
            }
        }
        public async Task GetTotalCountAsync_WithGreaterThanOrEqualToMaxCountResults_ReturnsMaxCount()
        {
            var source1 = new PackageSource("https://dotnet.myget.org/F/nuget-volatile/api/v3/index.json", "NuGetVolatile");
            var source2 = new PackageSource("https://api.nuget.org/v3/index.json", "NuGet.org");
            var sources = new List <PackageSource> {
                source1, source2
            };
            var sourceRepository = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { source1, source2 });

            var solutionManager = new Mock <IVsSolutionManager>();

            solutionManager.SetupGet(x => x.SolutionDirectory).Returns("z:\\SomeRandomPath");
            var settings = new Mock <ISettings>();
            var deleteOnRestartManager = new Mock <IDeleteOnRestartManager>();

            AddService <IDeleteOnRestartManager>(Task.FromResult <object>(deleteOnRestartManager.Object));
            AddService <IVsSolutionManager>(Task.FromResult <object>(solutionManager.Object));
            AddService <ISettings>(Task.FromResult <object>(settings.Object));
            AddService <ISourceRepositoryProvider>(Task.FromResult <object>(sourceRepository));

            var serviceActivationOptions = default(ServiceActivationOptions);
            var serviceBroker            = new Mock <IServiceBroker>();
            var authorizationService     = new AuthorizationServiceClient(Mock.Of <IAuthorizationService>());

            var sharedState = new SharedServiceState(sourceRepository);

            var projectManagerService = new Mock <INuGetProjectManagerService>();

            var installedPackages = new List <IPackageReferenceContextInfo>();
            var projects          = new List <IProjectContextInfo>
            {
                new ProjectContextInfo(
                    Guid.NewGuid().ToString(),
                    ProjectModel.ProjectStyle.PackageReference,
                    NuGetProjectKind.PackageReference)
            };

            projectManagerService.Setup(x => x.GetInstalledPackagesAsync(
                                            It.IsAny <IReadOnlyCollection <string> >(),
                                            It.IsAny <CancellationToken>()))
            .Returns(new ValueTask <IReadOnlyCollection <IPackageReferenceContextInfo> >(installedPackages));

#pragma warning disable ISB001 // Dispose of proxies
            serviceBroker.Setup(x => x.GetProxyAsync <INuGetProjectManagerService>(
                                    NuGetServices.ProjectManagerService,
                                    It.IsAny <ServiceActivationOptions>(),
                                    It.IsAny <CancellationToken>()))
            .Returns(new ValueTask <INuGetProjectManagerService>(projectManagerService.Object));
#pragma warning restore ISB001 // Dispose of proxies

            using (var searchService = new NuGetPackageSearchService(
                       serviceActivationOptions,
                       serviceBroker.Object,
                       authorizationService,
                       sharedState))
            {
                const int MaxCount = 100;

                int totalCount = await searchService.GetTotalCountAsync(
                    MaxCount,
                    projects,
                    sources.Select(s => PackageSourceContextInfo.Create(s)).ToList(),
                    targetFrameworks : new List <string>()
                {
                    "net45", "net5.0"
                },
                    new SearchFilter(includePrerelease : true),
                    NuGet.VisualStudio.Internal.Contracts.ItemFilter.All,
                    CancellationToken.None);

                Assert.Equal(MaxCount, totalCount);
            }
        }
        public async void DependencyGraphRestoreUtility_LegacyPackageRef_Restore_PackageShaValidationFailed()
        {
            using (var packageSource = TestDirectory.Create())
            {
                // Arrange
                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(
                    new List <Configuration.PackageSource>()
                {
                    new Configuration.PackageSource(packageSource.Path)
                });

                using (var testSolutionManager = new TestSolutionManager(true))
                    using (var randomProjectFolderPath = TestDirectory.Create())
                    {
                        var testSettings            = PopulateSettingsWithSources(sourceRepositoryProvider, randomProjectFolderPath);
                        var testNuGetProjectContext = new TestNuGetProjectContext();
                        var deleteOnRestartManager  = new TestDeleteOnRestartManager();
                        var nuGetPackageManager     = new NuGetPackageManager(
                            sourceRepositoryProvider,
                            testSettings,
                            testSolutionManager,
                            deleteOnRestartManager);

                        var projectTargetFrameworkStr = "net45";
                        var fullProjectPath           = Path.Combine(randomProjectFolderPath, "project1.csproj");
                        var projectNames = new ProjectNames(
                            fullName: fullProjectPath,
                            uniqueName: Path.GetFileName(fullProjectPath),
                            shortName: Path.GetFileNameWithoutExtension(fullProjectPath),
                            customUniqueName: Path.GetFileName(fullProjectPath));
                        var vsProjectAdapter = new TestVSProjectAdapter(
                            fullProjectPath,
                            projectNames,
                            projectTargetFrameworkStr);

                        var projectServices = new TestProjectSystemServices();
                        projectServices.SetupInstalledPackages(
                            NuGetFramework.Parse(projectTargetFrameworkStr),
                            new LibraryDependency
                        {
                            LibraryRange = new LibraryRange(
                                "packageA",
                                VersionRange.Parse("1.*"),
                                LibraryDependencyTarget.Package)
                        });

                        var legacyPRProject = new LegacyPackageReferenceProject(
                            vsProjectAdapter,
                            Guid.NewGuid().ToString(),
                            projectServices,
                            _threadingService);
                        testSolutionManager.NuGetProjects.Add(legacyPRProject);

                        var testLogger     = new TestLogger();
                        var restoreContext = new DependencyGraphCacheContext(testLogger, testSettings);

                        var packageContext = new SimpleTestPackageContext("packageA", "1.0.0");
                        packageContext.AddFile("lib/net45/a.dll");
                        SimpleTestPackageUtility.CreateOPCPackage(packageContext, packageSource);

                        var dgSpec = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(testSolutionManager, restoreContext);

                        var projectLockFilePath = Path.Combine(randomProjectFolderPath, "packages.project1.lock.json");
                        File.Create(projectLockFilePath).Close();

                        var restoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync(
                            testSolutionManager,
                            dgSpec,
                            restoreContext,
                            new RestoreCommandProvidersCache(),
                            (c) => { },
                            sourceRepositoryProvider.GetRepositories(),
                            Guid.Empty,
                            false,
                            true,
                            testLogger,
                            CancellationToken.None);

                        foreach (var restoreSummary in restoreSummaries)
                        {
                            Assert.True(restoreSummary.Success);
                            Assert.False(restoreSummary.NoOpRestore);
                        }

                        Assert.True(File.Exists(projectLockFilePath));

                        // delete existing restore output files
                        File.Delete(Path.Combine(vsProjectAdapter.MSBuildProjectExtensionsPath, "project.assets.json"));
                        File.Delete(Path.Combine(vsProjectAdapter.MSBuildProjectExtensionsPath, "project1.csproj.nuget.cache"));

                        // clean packages folder
                        var packagesFolder = Path.Combine(randomProjectFolderPath, "packages");
                        Directory.Delete(packagesFolder, true);
                        Directory.CreateDirectory(packagesFolder);

                        // add a new package
                        var newPackageContext = new SimpleTestPackageContext("packageA", "1.0.0");
                        newPackageContext.AddFile("lib/net45/a1.dll");
                        SimpleTestPackageUtility.CreateOPCPackage(newPackageContext, packageSource);

                        // Act
                        restoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync(
                            testSolutionManager,
                            dgSpec,
                            restoreContext,
                            new RestoreCommandProvidersCache(),
                            (c) => { },
                            sourceRepositoryProvider.GetRepositories(),
                            Guid.Empty,
                            false,
                            true,
                            testLogger,
                            CancellationToken.None);

                        // Assert
                        foreach (var restoreSummary in restoreSummaries)
                        {
                            Assert.False(restoreSummary.Success);
                            Assert.True(restoreSummary.Errors.Count > 0);
                            Assert.NotNull(restoreSummary.Errors.FirstOrDefault(message => (message as RestoreLogMessage).Code == NuGetLogCode.NU1403));
                        }
                    }
            }
        }
        public async Task BuildIntegratedRestoreUtility_RestoreDeferredProjectLoad()
        {
            // Arrange
            var projectName = "testproj";

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                  ""dependencies"": {
                    ""packageA"": ""1.0.0""
                  }
                }
              }
            }";

            using (var packageSource = TestDirectory.Create())
                using (var rootFolder = TestDirectory.Create())
                {
                    var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(
                        new List <PackageSource>()
                    {
                        new PackageSource(packageSource.Path)
                    });

                    var packageContext = new SimpleTestPackageContext("packageA");
                    packageContext.AddFile("lib/net45/a.dll");
                    SimpleTestPackageUtility.CreateOPCPackage(packageContext, packageSource);

                    var projectFolder = new DirectoryInfo(Path.Combine(rootFolder, projectName));
                    projectFolder.Create();
                    var projectConfig = Path.Combine(projectFolder.FullName, "project.json");
                    var projectPath   = Path.Combine(projectFolder.FullName, $"{projectName}.csproj");

                    var packageSpec = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", projectConfig);
                    var metadata    = new ProjectRestoreMetadata();
                    packageSpec.RestoreMetadata = metadata;

                    metadata.ProjectStyle      = ProjectStyle.ProjectJson;
                    metadata.ProjectPath       = projectPath;
                    metadata.ProjectJsonPath   = packageSpec.FilePath;
                    metadata.ProjectName       = packageSpec.Name;
                    metadata.ProjectUniqueName = projectPath;
                    foreach (var framework in packageSpec.TargetFrameworks.Select(e => e.FrameworkName))
                    {
                        metadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(framework));
                    }

                    var solutionManager = new TestSolutionManager(false);

                    var testLogger = new TestLogger();

                    var restoreContext = new DependencyGraphCacheContext(testLogger);
                    restoreContext.DeferredPackageSpecs.Add(packageSpec);

                    // Act
                    await DependencyGraphRestoreUtility.RestoreAsync(
                        solutionManager,
                        restoreContext,
                        new RestoreCommandProvidersCache(),
                        (c) => { },
                        sourceRepositoryProvider.GetRepositories(),
                        NullSettings.Instance,
                        testLogger,
                        CancellationToken.None);

                    // Assert
                    Assert.True(File.Exists(Path.Combine(projectFolder.FullName, "project.lock.json")));
                    Assert.True(testLogger.Errors == 0);
                }
        }