コード例 #1
0
        public async Task Restore_FallbackFolderContainsAllPackages()
        {
            using (var sourceDir = TestFileSystemUtility.CreateRandomTestFolder())
                using (var fallbackDir1 = TestFileSystemUtility.CreateRandomTestFolder())
                    using (var fallbackDir2 = TestFileSystemUtility.CreateRandomTestFolder())
                        using (var packagesDir = TestFileSystemUtility.CreateRandomTestFolder())
                            using (var projectDir = TestFileSystemUtility.CreateRandomTestFolder())
                            {
                                var specPath = Path.Combine(projectDir, "XPlatRestoreTests", "project.json");
                                var spec     = XPlatTestUtils.BasicConfigNetCoreApp;

                                XPlatTestUtils.AddDependency(spec, "a", "1.0.0");
                                XPlatTestUtils.AddDependency(spec, "b", "1.0.0");
                                XPlatTestUtils.WriteJson(spec, specPath);

                                var packageA = new SimpleTestPackageContext("a", "1.0.0");
                                var packageB = new SimpleTestPackageContext("b", "1.0.0");

                                var saveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files;

                                await SimpleTestPackageUtility.CreateFolderFeedV3(
                                    fallbackDir2,
                                    saveMode,
                                    packageA,
                                    packageB);

                                var log = new TestCommandOutputLogger();

                                var config = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
    <config>
        <add key=""globalPackagesFolder"" value=""{packagesDir}"" />
    </config>
    <fallbackPackageFolders>
        <add key=""a"" value=""{fallbackDir1}"" />
        <add key=""b"" value=""{fallbackDir2}"" />
    </fallbackPackageFolders>
    <packageSources>
        <add key=""a"" value=""{sourceDir}"" />
    </packageSources>
</configuration>";

                                File.WriteAllText(Path.Combine(projectDir, "NuGet.Config"), config);

                                var args = new string[]
                                {
                                    "restore",
                                    projectDir,
                                };

                                // Act
                                var exitCode = Program.MainInternal(args, log);

                                // Assert
                                Assert.Equal(0, exitCode);
                                Assert.Equal(0, log.Errors);
                                Assert.Equal(0, log.Warnings);
                                Assert.Equal(0, Directory.GetDirectories(packagesDir).Length);
                            }
        }
コード例 #2
0
        public async Task NuGetv3LocalRepository_FindPackagesById_LeavesVersionCaseFoundOnFileSystem()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var id     = "Foo";
                var target = new NuGetv3LocalRepository(workingDir);
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    workingDir,
                    PackageSaveMode.Defaultv3,
                    new SimpleTestPackageContext(id, "1.0.0"),
                    new SimpleTestPackageContext(id, "2.0.0-Beta"));

                // Act
                var packages = target.FindPackagesById(id);

                // Assert
                Assert.Equal(2, packages.Count());
                packages = packages.OrderBy(x => x.Version);
                Assert.Equal(id, packages.ElementAt(0).Id);
                Assert.Equal("1.0.0", packages.ElementAt(0).Version.ToNormalizedString());
                Assert.Equal(id, packages.ElementAt(1).Id);
                Assert.Equal("2.0.0-beta", packages.ElementAt(1).Version.ToNormalizedString());
            }
        }
コード例 #3
0
        public async void AddPkg_UnconditionalAddWithNoRestore_Success(string packageFrameworks,
                                                                       string projectFrameworks,
                                                                       string userInputVersion)
        {
            // Arrange

            using (var pathContext = new SimpleTestPathContext())
            {
                var projectA = XPlatTestUtils.CreateProject(projectName, pathContext, projectFrameworks);
                var packageX = XPlatTestUtils.CreatePackage(frameworkString: packageFrameworks);

                // Generate Package
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                var packageArgs   = XPlatTestUtils.GetPackageReferenceArgs(packageX.Id, userInputVersion, projectA, noRestore: true);
                var commandRunner = new AddPackageReferenceCommandRunner();

                // Act
                var result = commandRunner.ExecuteCommand(packageArgs, MsBuild)
                             .Result;
                var projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;

                // If noRestore is set, then we do not perform compatibility check.
                // The added package reference will be unconditional
                var itemGroup = XPlatTestUtils.GetItemGroupForAllFrameworks(projectXmlRoot);

                // Assert
                Assert.Equal(0, result);
                Assert.NotNull(itemGroup);
                Assert.True(XPlatTestUtils.ValidateReference(itemGroup, packageX.Id, userInputVersion));
            }
        }
コード例 #4
0
        public async Task NuGetv3LocalRepository_FindPackage_VerifyNuspecsCached()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var id     = "Foo";
                var target = new NuGetv3LocalRepository(workingDir);
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    workingDir,
                    PackageSaveMode.Defaultv3,
                    new SimpleTestPackageContext(id, "1.0.0"),
                    new SimpleTestPackageContext(id, "2.0.0-Beta"));

                // Act
                var package1 = target.FindPackage(id, NuGetVersion.Parse("2.0.0-beta"));
                var package2 = target.FindPackage(id, NuGetVersion.Parse("2.0.0-BETA"));
                var package3 = target.FindPackage(id, NuGetVersion.Parse("2.0.0-beta"));

                // Assert
                Assert.True(ReferenceEquals(package1, package3));
                Assert.True(ReferenceEquals(package1.Nuspec, package2.Nuspec));
                Assert.True(ReferenceEquals(package1.Nuspec, package3.Nuspec));

                // These should contain different versions
                Assert.False(ReferenceEquals(package1, package2));
            }
        }
コード例 #5
0
        public async Task InstallationCompatibility_WithInvalidProjectActions_Fails()
        {
            // Arrange
            using (var userPackageFolder = TestDirectory.Create())
            {
                var tc = new TestContext(userPackageFolder);

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    userPackageFolder,
                    PackageSaveMode.Defaultv3,
                    new[]
                {
                    new SimpleTestPackageContext(tc.PackageIdentityA)
                    {
                        PackageTypes = { tc.InvalidPackageType }
                    }
                });

                // Act & Assert
                var ex = Assert.Throws <PackagingException>(() =>
                                                            tc.Target.EnsurePackageCompatibility(
                                                                tc.ProjectKProject,
                                                                tc.NuGetPathContext.Object,
                                                                new NuGetProjectAction[]
                {
                    NuGetProjectAction.CreateInstallProjectAction(tc.PackageIdentityA, tc.SourceRepository, tc.ProjectKProject)
                },
                                                                tc.GetRestoreResult(new[] { tc.PackageIdentityA })));

                Assert.Equal(
                    "Package 'PackageA 1.0.0' has a package type 'Invalid 1.2' that is not supported by project 'TestProjectKNuGetProject'.",
                    ex.Message);
            }
        }
コード例 #6
0
        public async void RemovePkg_UnconditionalRemove_Success()
        {
            // Arrange

            using (var pathContext = new SimpleTestPathContext())
            {
                // Generate Package
                var packageX = XPlatTestUtils.CreatePackage();
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                var projectA = XPlatTestUtils.CreateProject(ProjectName, pathContext, packageX, "net46");

                // Verify that the package reference exists before removing.
                var projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;
                var itemGroup      = XPlatTestUtils.GetItemGroupForAllFrameworks(projectXmlRoot);

                Assert.NotNull(itemGroup);
                Assert.True(XPlatTestUtils.ValidateReference(itemGroup, packageX.Id, "1.0.0"));

                var packageArgs   = XPlatTestUtils.GetPackageReferenceArgs(packageX.Id, projectA);
                var commandRunner = new RemovePackageReferenceCommandRunner();

                // Act
                var result = commandRunner.ExecuteCommand(packageArgs, MsBuild).Result;
                projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;

                // Assert
                Assert.Equal(0, result);
                Assert.True(XPlatTestUtils.ValidateNoReference(projectXmlRoot, packageX.Id));
            }
        }
コード例 #7
0
        public async Task DotnetCliTool_BasicToolRestore()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                var logger = new TestLogger();
                var dgFile = new DependencyGraphSpec();

                var spec = ToolRestoreUtility.GetSpec(
                    Path.Combine(pathContext.SolutionRoot, "fake.csproj"),
                    "a",
                    VersionRange.Parse("1.0.0"),
                    NuGetFramework.Parse("netcoreapp1.0"));

                dgFile.AddProject(spec);
                dgFile.AddRestore(spec.Name);

                var pathResolver = new ToolPathResolver(pathContext.UserPackagesFolder);
                var path         = pathResolver.GetLockFilePath(
                    "a",
                    NuGetVersion.Parse("1.0.0"),
                    NuGetFramework.Parse("netcoreapp1.0"));

                await SimpleTestPackageUtility.CreateFolderFeedV3(pathContext.PackageSource, new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                // Act
                var result = await CommandsTestUtility.RunSingleRestore(dgFile, pathContext, logger);

                // Assert
                Assert.True(result.Success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                Assert.True(File.Exists(path));
            }
        }
コード例 #8
0
        public async void AddPkg_FailureIncompatibleFrameworks(string packageFrameworks, string userInputFrameworks)
        {
            // Arrange

            using (var pathContext = new SimpleTestPathContext())
            {
                var projectA = XPlatTestUtils.CreateProject(projectName, pathContext, "net46; netcoreapp1.0");
                var packageX = XPlatTestUtils.CreatePackage(frameworkString: packageFrameworks);

                // Generate Package
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                var packageArgs = XPlatTestUtils.GetPackageReferenceArgs(packageX.Id, packageX.Version, projectA,
                                                                         frameworks: userInputFrameworks);
                var commandRunner = new AddPackageReferenceCommandRunner();

                // Act
                var result = commandRunner.ExecuteCommand(packageArgs, MsBuild)
                             .Result;
                var projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;

                // Assert
                Assert.Equal(1, result);
                Assert.True(XPlatTestUtils.ValidateNoReference(projectXmlRoot, packageX.Id));
            }
        }
コード例 #9
0
        public async void AddPkg_FailureUnknownPackage()
        {
            // Arrange

            using (var pathContext = new SimpleTestPathContext())
            {
                var projectA = XPlatTestUtils.CreateProject(projectName, pathContext, "net46; netcoreapp1.0");
                var packageX = XPlatTestUtils.CreatePackage();

                // Generate Package
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                var packageArgs   = XPlatTestUtils.GetPackageReferenceArgs("unknown_package_id", "1.0.0", projectA);
                var commandRunner = new AddPackageReferenceCommandRunner();

                // Act
                var result = commandRunner.ExecuteCommand(packageArgs, MsBuild)
                             .Result;
                var projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;

                // Assert
                Assert.Equal(1, result);
                Assert.True(XPlatTestUtils.ValidateNoReference(projectXmlRoot, packageX.Id));
                Assert.True(XPlatTestUtils.ValidateNoReference(projectXmlRoot, "unknown_package_id"));
            }
        }
コード例 #10
0
        public async Task LocalPackageFileCache_GetShaTwiceVerifyMissingFilesAreNotCached()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var cache        = new LocalPackageFileCache();
                var pathResolver = new VersionFolderPathResolver(pathContext.PackageSource);

                var identity = new PackageIdentity("X", NuGetVersion.Parse("1.0.0"));
                var shaPath  = pathResolver.GetHashPath(identity.Id, identity.Version);

                var exists1 = cache.Sha512Exists(shaPath);

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    identity);

                var exists2 = cache.Sha512Exists(shaPath);
                var sha512  = cache.GetOrAddSha512(shaPath);
                var sha512B = cache.GetOrAddSha512(shaPath);

                // Verify original value was not found
                exists1.Should().BeFalse();

                // Verify false was not cached
                exists2.Should().BeTrue();

                // Verify both hashes are the exact same instance
                Assert.Same(sha512.Value, sha512B.Value);
            }
        }
コード例 #11
0
        public async Task RestoreCommand_FileUriV3Folder()
        {
            // Arrange
            var sources = new List <PackageSource>();

            // Both TxMs reference packageA, but they are different types.
            // Verify that the reference does not show up under libraries.
            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""packageA"": ""4.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(UriUtility.CreateSourceUri(packageSource.FullName).AbsoluteUri));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    packageSource.FullName,
                    new PackageIdentity("packageA", NuGetVersion.Parse("4.0.0")));

                // Act
                var command = new RestoreCommand(request);
                var result  = await command.ExecuteAsync();

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success);
                Assert.Equal(1, lockFile.Libraries.Count);
            }
        }
コード例 #12
0
        public async void AddPkg_ConditionalAddWithUserInputFramework_Success(string packageFrameworks, string projectFrameworks, string userInputFrameworks)
        {
            // Arrange

            using (var pathContext = new SimpleTestPathContext())
            {
                var projectA = XPlatTestUtils.CreateProject(projectName, pathContext, "net46; netcoreapp1.0");
                var packageX = XPlatTestUtils.CreatePackage(frameworkString: packageFrameworks);

                // Generate Package
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                var packageArgs = XPlatTestUtils.GetPackageReferenceArgs(packageX.Id, packageX.Version, projectA,
                                                                         frameworks: userInputFrameworks);
                var commandRunner   = new AddPackageReferenceCommandRunner();
                var commonFramework = XPlatTestUtils.GetCommonFramework(packageFrameworks, projectFrameworks, userInputFrameworks);

                // Act
                var result = commandRunner.ExecuteCommand(packageArgs, MsBuild)
                             .Result;
                var projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;
                var itemGroup      = XPlatTestUtils.GetItemGroupForFramework(projectXmlRoot, commonFramework);

                // Assert
                Assert.Equal(0, result);
                Assert.NotNull(itemGroup);
                Assert.True(XPlatTestUtils.ValidateReference(itemGroup, packageX.Id, packageX.Version));
            }
        }
コード例 #13
0
        public async void AddPkg_UnconditionalAddWithoutVersion_Success()
        {
            // Arrange

            using (var pathContext = new SimpleTestPathContext())
            {
                var projectA = XPlatTestUtils.CreateProject(projectName, pathContext, "net46");
                var packageX = XPlatTestUtils.CreatePackage();

                // Generate Package
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                // Since user is not inputing a version, it is converted to a "*"
                var packageArgs   = XPlatTestUtils.GetPackageReferenceArgs(packageX.Id, "*", projectA, noVersion: true);
                var commandRunner = new AddPackageReferenceCommandRunner();

                // Act
                var result = commandRunner.ExecuteCommand(packageArgs, MsBuild)
                             .Result;
                var projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;

                // Assert
                Assert.Equal(0, result);

                // Since user did not specify a version, the package reference will contain the resolved version
                Assert.True(XPlatTestUtils.ValidateReference(projectXmlRoot, packageX.Id, "1.0.0"));
            }
        }
コード例 #14
0
        public async Task NuGetv3LocalRepository_FindPackagesById_InstallStress()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var id     = "a";
                var target = new NuGetv3LocalRepository(workingDir);

                var packages = new ConcurrentQueue <PackageIdentity>();
                var limit    = 100;

                for (int i = 0; i < limit; i++)
                {
                    packages.Enqueue(new PackageIdentity(id, NuGetVersion.Parse($"{i + 1}.0.0")));
                }

                var tasks = new List <Task>();
                var sem   = new ManualResetEventSlim(false);

                for (int i = 0; i < 10; i++)
                {
                    tasks.Add(Task.Run(async() =>
                    {
                        sem.Wait();

                        PackageIdentity identity;
                        while (packages.TryDequeue(out identity))
                        {
                            // Fetch
                            var result = target.FindPackagesById(identity.Id)
                                         .FirstOrDefault(f => f.Version == identity.Version);

                            Assert.Null(result);

                            // Create package
                            await SimpleTestPackageUtility.CreateFolderFeedV3(workingDir,
                                                                              PackageSaveMode.Defaultv3,
                                                                              identity);

                            // Clear
                            target.ClearCacheForIds(new[] { identity.Id });

                            result = target.FindPackagesById(identity.Id)
                                     .FirstOrDefault(f => f.Version == identity.Version);

                            // Assert the package was found
                            Assert.NotNull(result);
                        }
                    }));
                }

                sem.Set();
                await Task.WhenAll(tasks);

                // Assert
                var results2 = target.FindPackagesById(id);
                Assert.Equal(limit, results2.Count());
            }
        }
コード例 #15
0
        public async Task RestoreUAP_VerifyProjectToProjectRestore()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Set up solution, project, and packages
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var projectA = SimpleTestProjectContext.CreateLegacyPackageReference(
                    "a",
                    pathContext.SolutionRoot,
                    NuGetFramework.AnyFramework);

                var projectB = SimpleTestProjectContext.CreateLegacyPackageReference(
                    "b",
                    pathContext.SolutionRoot,
                    NuGetFramework.AnyFramework);

                projectA.Properties.Add("TargetPlatformIdentifier", "UAP");
                projectA.Properties.Add("TargetPlatformVersion", "10.0.14393.0");
                projectA.Properties.Add("TargetPlatformMinVersion", "10.0.10586.0");

                // Set style for A since it has no references
                projectA.Properties.Add("RestoreProjectStyle", "PackageReference");


                projectB.Properties.Add("TargetPlatformIdentifier", "UAP");
                projectB.Properties.Add("TargetPlatformVersion", "10.0.14393.0");
                projectB.Properties.Add("TargetPlatformMinVersion", "10.0.10586.0");

                var packageX = new SimpleTestPackageContext()
                {
                    Id      = "x",
                    Version = "1.0.0"
                };

                projectB.AddPackageToAllFrameworks(packageX);
                projectA.AddProjectToAllFrameworks(projectB);

                solution.Projects.Add(projectA);
                solution.Create(pathContext.SolutionRoot);

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                // Act
                var r = RestoreSolution(pathContext);

                var dgPath = Path.Combine(pathContext.WorkingDirectory, "out.dg");
                var dgSpec = DependencyGraphSpec.Load(dgPath);

                var assetsFile = projectA.AssetsFile;

                // Assert
                Assert.Equal("1.0.0", assetsFile.Libraries.Single(p => p.Name == "x").Version.ToNormalizedString());
            }
        }
コード例 #16
0
        public async Task FallbackPackagePathResolver_FindPackageInFallbackFolder2SkipMissingHashes()
        {
            // Arrange
            using (var mockBaseDirectory = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var userFolder      = Path.Combine(mockBaseDirectory, "global");
                var fallbackFolders = new List <string>()
                {
                    Path.Combine(mockBaseDirectory, "fallback1"),
                    Path.Combine(mockBaseDirectory, "fallback2"),
                };

                Directory.CreateDirectory(userFolder);

                foreach (var fallback in fallbackFolders)
                {
                    Directory.CreateDirectory(fallback);
                }

                var saveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files | PackageSaveMode.Nupkg;

                var targetFolder = fallbackFolders[1];

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    userFolder,
                    saveMode,
                    new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    fallbackFolders[0],
                    saveMode,
                    new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    fallbackFolders[1],
                    saveMode,
                    new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                // Remove hashes from the first two folders
                foreach (var root in new[] { userFolder, fallbackFolders[0] })
                {
                    var localResolver = new VersionFolderPathResolver(root);
                    File.Delete(localResolver.GetHashPath("a", NuGetVersion.Parse("1.0.0")));
                }

                var expected = Path.Combine(targetFolder, "a", "1.0.0");

                var resolver = new FallbackPackagePathResolver(userFolder, fallbackFolders);

                // Act
                var path = resolver.GetPackageDirectory("a", "1.0.0");

                // Assert
                Assert.Equal(expected, path);
            }
        }
コード例 #17
0
        public async Task DotnetCliTool_BasicToolRestore_DifferentVersionRanges()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                var logger = new TestLogger();
                var dgFile = new DependencyGraphSpec();

                var versions = new List <VersionRange>();

                var limit = 100;

                for (int i = 0; i < limit; i++)
                {
                    var version = VersionRange.Parse($"{i + 1}.0.0");
                    versions.Add(version);

                    var spec = ToolRestoreUtility.GetSpec(
                        Path.Combine(pathContext.SolutionRoot, $"fake{i}.csproj"),
                        "a",
                        version,
                        NuGetFramework.Parse("netcoreapp1.0"));

                    dgFile.AddProject(spec);
                    dgFile.AddRestore(spec.Name);
                }

                var pathResolver = new ToolPathResolver(pathContext.UserPackagesFolder);

                foreach (var version in versions)
                {
                    await SimpleTestPackageUtility.CreateFolderFeedV3(pathContext.PackageSource, new PackageIdentity("a", version.MinVersion));
                }

                // Act
                var results = await CommandsTestUtility.RunRestore(dgFile, pathContext, logger);

                // Assert
                Assert.Equal(limit, results.Count);

                foreach (var result in results)
                {
                    Assert.True(result.Success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                }

                foreach (var version in versions)
                {
                    var path = pathResolver.GetLockFilePath(
                        "a",
                        version.MinVersion,
                        NuGetFramework.Parse("netcoreapp1.0"));

                    Assert.True(File.Exists(path));
                }
            }
        }
コード例 #18
0
        private async Task CreateFeeds(string rootV2, string rootV3, string rootUnzip, string rootPackagesConfig, params PackageIdentity[] packages)
        {
            foreach (var package in packages)
            {
                SimpleTestPackageUtility.CreateFolderFeedV2(rootV2, package);
                await SimpleTestPackageUtility.CreateFolderFeedV3(rootV3, package);

                SimpleTestPackageUtility.CreateFolderFeedUnzip(rootUnzip, package);
                await SimpleTestPackageUtility.CreateFolderFeedPackagesConfigAsync(rootPackagesConfig, package);
            }
        }
コード例 #19
0
        public async Task RestoreUAP_VerifyNoContentFiles()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Set up solution, project, and packages
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var projectA = SimpleTestProjectContext.CreateLegacyPackageReference(
                    "a",
                    pathContext.SolutionRoot,
                    NuGetFramework.AnyFramework);

                var packageX = new SimpleTestPackageContext()
                {
                    Id      = "x",
                    Version = "1.0.0"
                };

                packageX.AddFile("contentFiles/any/any/a.txt");

                projectA.AddPackageToAllFrameworks(packageX);

                projectA.Properties.Add("TargetPlatformIdentifier", "UAP");
                projectA.Properties.Add("TargetPlatformVersion", "10.0.14393.0");
                projectA.Properties.Add("TargetPlatformMinVersion", "10.0.10586.0");

                solution.Projects.Add(projectA);
                solution.Create(pathContext.SolutionRoot);

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                // Act
                var r = RestoreSolution(pathContext);

                var dgPath = Path.Combine(pathContext.WorkingDirectory, "out.dg");
                var dgSpec = DependencyGraphSpec.Load(dgPath);

                var propsXML  = XDocument.Load(projectA.PropsOutput);
                var styleNode = propsXML.Root.Elements().First().Elements(XName.Get("NuGetProjectStyle", "http://schemas.microsoft.com/developer/msbuild/2003")).FirstOrDefault();

                var projectSpec = dgSpec.Projects.Single();

                // Assert
                Assert.Equal(ProjectStyle.PackageReference, projectSpec.RestoreMetadata.ProjectStyle);
                Assert.Equal("PackageReference", styleNode.Value);
                Assert.Equal(NuGetFramework.Parse("UAP10.0.10586.0"), projectSpec.TargetFrameworks.Single().FrameworkName);

                Assert.DoesNotContain("a.txt", propsXML.ToString());
            }
        }
コード例 #20
0
        public async Task Cycle_PackageCircularDependencyVerifyCycleDetected()
        {
            // Arrange
            using (var cacheContext = new SourceCacheContext())
                using (var pathContext = new SimpleTestPathContext())
                {
                    var logger  = new TestLogger();
                    var sources = new List <PackageSource>
                    {
                        new PackageSource(pathContext.PackageSource)
                    };

                    var spec1 = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "netstandard1.6");
                    spec1.TargetFrameworks[0].Dependencies.Add(new LibraryDependency()
                    {
                        LibraryRange = new LibraryRange("X", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package)
                    });

                    var specs = new[] { spec1 };

                    // Create fake projects, the real data is in the specs
                    var projects = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, specs);

                    var packageX = new SimpleTestPackageContext("x", "1.0.0");
                    var packageY = new SimpleTestPackageContext("y", "1.0.0");
                    var packageZ = new SimpleTestPackageContext("z", "1.0.0");

                    // X -> Y -> Z -> X
                    packageX.Dependencies.Add(packageY);
                    packageY.Dependencies.Add(packageZ);
                    packageZ.Dependencies.Add(packageX);

                    await SimpleTestPackageUtility.CreateFolderFeedV3(pathContext.PackageSource, packageX, packageY, packageZ);

                    // Create dg file
                    var dgFile = new DependencyGraphSpec();

                    // Only add projectA
                    dgFile.AddProject(spec1);
                    dgFile.AddRestore(spec1.RestoreMetadata.ProjectUniqueName);

                    dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg"));

                    // Act
                    var summaries = await NETCoreRestoreTestUtility.RunRestore(pathContext, logger, sources, dgFile, cacheContext);

                    var success = summaries.All(s => s.Success);

                    // Assert
                    Assert.False(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                    Assert.Contains("Cycle detected", string.Join(Environment.NewLine, logger.ErrorMessages));
                }
        }
コード例 #21
0
        public async Task NuGetv3LocalRepository_Exists_WorksForAllCases(string id)
        {
            using (var workingDir = TestDirectory.Create())
            {
                var target = new NuGetv3LocalRepository(workingDir);
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    workingDir,
                    PackageSaveMode.Defaultv3,
                    new SimpleTestPackageContext("foo", "1.0.0"));

                target.Exists(id, NuGetVersion.Parse("1.0.0")).Should().BeTrue();
            }
        }
コード例 #22
0
        public async void AddPkg_UnconditionalAddWithDotnetCliToolAndNoRestore_Success(string packageFrameworks,
                                                                                       string projectFrameworks,
                                                                                       string userInputVersion)
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Generate DotNetCliToolReference Package
                var packageDotnetCliToolX = XPlatTestUtils.CreatePackage(packageId: "PackageDotnetCliToolX",
                                                                         packageType: PackageType.DotnetCliTool);

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageDotnetCliToolX);

                // Generate test package
                var packageY = XPlatTestUtils.CreatePackage(packageId: "PackageY");

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageY);

                var projectA = XPlatTestUtils.CreateProject(projectName, pathContext, "net46");

                projectA.DotnetCLIToolReferences.Add(packageDotnetCliToolX);

                projectA.Save();

                // Verify that the package reference exists before removing.
                var projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;
                var itemGroup      = XPlatTestUtils.GetItemGroupForAllFrameworks(projectXmlRoot, packageType: PackageType.DotnetCliTool);

                Assert.NotNull(itemGroup);
                Assert.True(XPlatTestUtils.ValidateReference(itemGroup, packageDotnetCliToolX.Id, "1.0.0", PackageType.DotnetCliTool));

                var packageArgs   = XPlatTestUtils.GetPackageReferenceArgs(packageY.Id, userInputVersion, projectA, noRestore: true);
                var commandRunner = new AddPackageReferenceCommandRunner();

                // Act
                var result = commandRunner.ExecuteCommand(packageArgs, MsBuild).Result;
                projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;
                itemGroup      = XPlatTestUtils.GetItemGroupForAllFrameworks(projectXmlRoot);

                // Assert
                Assert.Equal(0, result);
                Assert.NotNull(itemGroup);
                Assert.True(XPlatTestUtils.ValidateReference(itemGroup, packageY.Id, userInputVersion));
            }
        }
コード例 #23
0
        public async Task NuGetv3LocalRepository_FindPackagesById_Stress()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var id     = "a";
                var target = new NuGetv3LocalRepository(workingDir);

                var packages = new List <PackageIdentity>();

                for (int i = 0; i < 100; i++)
                {
                    packages.Add(new PackageIdentity(id, NuGetVersion.Parse($"{i + 1}.0.0")));
                }

                await SimpleTestPackageUtility.CreateFolderFeedV3(workingDir, packages.ToArray());

                var tasks = new List <Task>();
                var sem   = new ManualResetEventSlim(false);

                for (int i = 0; i < 10; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        sem.Wait();

                        for (int j = 0; j < 100; j++)
                        {
                            // Fetch
                            var result = target.FindPackagesById(id);

                            // Assert
                            Assert.Equal(100, result.Count());

                            // Clear
                            for (int k = 0; k < 100; k++)
                            {
                                target.ClearCacheForIds(new[] { id });
                            }
                        }
                    }));
                }

                sem.Set();
                await Task.WhenAll(tasks);

                // Assert
                var results2 = target.FindPackagesById(id);
                Assert.Equal(100, results2.Count());
            }
        }
コード例 #24
0
        public async Task TestUtility_Solution()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                // Arrange && Act
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var projectA = SimpleTestProjectContext.CreateNETCore(
                    "a",
                    pathContext.SolutionRoot,
                    NuGetFramework.Parse("net45"));

                var packageX = new SimpleTestPackageContext()
                {
                    Id      = "x",
                    Version = "1.0.0"
                };

                var projectJson = JObject.Parse(@"{
                                                    'dependencies': {
                                                    },
                                                    'frameworks': {
                                                        'net45': { }
                                                  }
                                               }");

                var projectB = SimpleTestProjectContext.CreateUAP(
                    "b",
                    pathContext.SolutionRoot,
                    NuGetFramework.Parse("net45"),
                    projectJson);

                projectA.AddPackageToAllFrameworks(packageX);

                solution.Projects.Add(projectA);
                solution.Projects.Add(projectB);
                solution.Create(pathContext.SolutionRoot);

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                // Assert
                Assert.True(File.Exists(Path.Combine(pathContext.SolutionRoot, "solution.sln")));
                Assert.True(File.Exists(Path.Combine(pathContext.SolutionRoot, "a", "a.csproj")));
                Assert.True(File.Exists(Path.Combine(pathContext.WorkingDirectory, "NuGet.Config")));
                Assert.True(File.Exists(Path.Combine(pathContext.SolutionRoot, "b", "b.csproj")));
                Assert.True(File.Exists(Path.Combine(pathContext.SolutionRoot, "b", "project.json")));
            }
        }
コード例 #25
0
        public async Task DotnetCliTool_BasicToolRestore_WithDuplicates()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                var logger = new TestLogger();
                var dgFile = new DependencyGraphSpec();

                for (int i = 0; i < 10; i++)
                {
                    var spec = ToolRestoreUtility.GetSpec(
                        Path.Combine(pathContext.SolutionRoot, "fake.csproj"),
                        "a",
                        VersionRange.Parse("1.0.0"),
                        NuGetFramework.Parse("netcoreapp1.0"),
                        pathContext.UserPackagesFolder,
                        new List <string>()
                    {
                        pathContext.FallbackFolder
                    },
                        new List <PackageSource>()
                    {
                        new PackageSource(pathContext.PackageSource)
                    },
                        new WarningProperties());

                    dgFile.AddProject(spec);
                    dgFile.AddRestore(spec.Name);
                }

                var pathResolver = new ToolPathResolver(pathContext.UserPackagesFolder);
                var path         = pathResolver.GetLockFilePath(
                    "a",
                    NuGetVersion.Parse("1.0.0"),
                    NuGetFramework.Parse("netcoreapp1.0"));

                await SimpleTestPackageUtility.CreateFolderFeedV3(pathContext.PackageSource, new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                // Act
                var results = await CommandsTestUtility.RunRestore(dgFile, pathContext, logger);

                // Assert
                // This should have been de-duplicated
                Assert.Equal(1, results.Count);
                var result = results.Single();

                Assert.True(result.Success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                Assert.True(File.Exists(path));
            }
        }
コード例 #26
0
        public async Task NuGetv3LocalRepository_Exists_DoesNotExist()
        {
            using (var workingDir = TestDirectory.Create())
            {
                var target = new NuGetv3LocalRepository(workingDir);
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    workingDir,
                    PackageSaveMode.Defaultv3,
                    new SimpleTestPackageContext("foo", "1.0.0"));

                target.Exists("foo", NuGetVersion.Parse("2.0.0")).Should().BeFalse();
                target.Exists("bar", NuGetVersion.Parse("1.0.0")).Should().BeFalse();
            }
        }
コード例 #27
0
        public async Task StandaloneProject_BasicRestore()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                var logger = new TestLogger();
                var dgFile = new DependencyGraphSpec();

                var projectJson = @"
                {
                  ""frameworks"": {
                    ""netstandard1.6"": {
                      ""dependencies"": {
                        ""a"": ""1.0.0""
                      }
                    }
                  }
                }";

                var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "x", Path.Combine(pathContext.SolutionRoot, "project.json"));
                spec.RestoreMetadata = new ProjectRestoreMetadata();
                spec.RestoreMetadata.ProjectStyle      = ProjectStyle.Standalone;
                spec.RestoreMetadata.OutputPath        = Path.Combine(pathContext.SolutionRoot, "x");
                spec.RestoreMetadata.ProjectUniqueName = "x";
                spec.RestoreMetadata.ProjectName       = "x";
                spec.RestoreMetadata.ProjectPath       = Path.Combine(pathContext.SolutionRoot, "x.csproj");

                dgFile.AddProject(spec);
                dgFile.AddRestore("x");

                await SimpleTestPackageUtility.CreateFolderFeedV3(pathContext.PackageSource, new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                // Act
                var result = await CommandsTestUtility.RunSingleRestore(dgFile, pathContext, logger);

                var path = Path.Combine(spec.RestoreMetadata.OutputPath, "project.assets.json");

                // Assert
                Assert.True(result.Success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                Assert.True(File.Exists(path));

                var lockFormat = new LockFileFormat();
                var lockFile   = lockFormat.Read(path);

                Assert.Equal(NuGetFramework.Parse("netstandard1.6"), lockFile.Targets.Single().TargetFramework);
                Assert.Equal("a", lockFile.Targets.Single().Libraries.Single().Name);
            }
        }
コード例 #28
0
        public async Task InstallationCompatibility_WithValidProjectActions_Succeeds()
        {
            // Arrange
            using (var userPackageFolder = TestDirectory.Create())
            {
                var tc = new TestContext(userPackageFolder);

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    userPackageFolder,
                    PackageSaveMode.Defaultv3,
                    new[]
                {
                    new SimpleTestPackageContext(tc.PackageIdentityA)
                    {
                        PackageTypes = { PackageType.DotnetCliTool }
                    },
                    new SimpleTestPackageContext(tc.PackageIdentityB)     // Not inspected, because this package is
                                                                          // being uninstalled, not installed.
                    {
                        PackageTypes = { tc.InvalidPackageType }
                    },
                    new SimpleTestPackageContext(tc.PackageIdentityC)
                    {
                        PackageTypes = { PackageType.Dependency }
                    },
                });

                // Act & Assert
                tc.Target.EnsurePackageCompatibility(
                    tc.ProjectKProject,
                    tc.NuGetPathContext.Object,
                    new NuGetProjectAction[]
                {
                    NuGetProjectAction.CreateInstallProjectAction(tc.PackageIdentityA, tc.SourceRepository, tc.ProjectKProject),
                    NuGetProjectAction.CreateUninstallProjectAction(tc.PackageIdentityB, tc.ProjectKProject),
                    NuGetProjectAction.CreateInstallProjectAction(tc.PackageIdentityC, tc.SourceRepository, tc.ProjectKProject)
                },
                    tc.GetRestoreResult(new[]
                {
                    tc.PackageIdentityA,
                    tc.PackageIdentityB,
                    tc.PackageIdentityC
                }));
            }
        }
コード例 #29
0
        public async Task NuGetv3LocalRepository_FindPackage_ReturnsNullWithVersionNotFound()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var id     = "Foo";
                var target = new NuGetv3LocalRepository(workingDir);
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    workingDir,
                    PackageSaveMode.Defaultv3,
                    new SimpleTestPackageContext(id, "1.0.0"),
                    new SimpleTestPackageContext(id, "2.0.0-Beta"));

                // Act
                var package = target.FindPackage(id, NuGetVersion.Parse("3.0.0-BETA"));

                // Assert
                Assert.Null(package);
            }
        }
コード例 #30
0
        public async Task NuGetv3LocalRepository_FindPackage_VerifyRuntimeGraphCached()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var id = "packageX";

                var runtimeJsonX1 = @"{
                  ""runtimes"": {
                    ""unix"": {
                            ""packageX"": {
                                ""runtime.packageX"": ""1.0.0""
                            }
                          }
                        },
                ""supports"": {
                    ""x1.app"": {
                            ""uap10.0"": [
                                ""win10-x86""
                        ]
                    }
                   }
                  }";

                var package = new SimpleTestPackageContext(id, "1.0.0");
                package.RuntimeJson = runtimeJsonX1;

                var target = new NuGetv3LocalRepository(workingDir);
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    workingDir,
                    PackageSaveMode.Defaultv3,
                    package);

                // Act
                var packageResultA = target.FindPackage(id, NuGetVersion.Parse("1.0.0"));
                var packageResultB = target.FindPackage(id, NuGetVersion.Parse("1.0.0"));

                // Assert
                Assert.True(ReferenceEquals(packageResultA.RuntimeGraph, packageResultB.RuntimeGraph));
            }
        }